繁体   English   中英

如何使用 NextJs 在 getServerSideProps 中从 Firebase 获取数据

[英]How to fetch data from Firebase in getServerSideProps with NextJs

我想弄清楚如何从 NextJs 中的 GetServerSideProps 中的 Firebase 获取数据

这是我的数据库文件

import admin from "firebase-admin";
import serviceAccount from "./serviceAccountKey.json";

if (!admin.apps.length) {
  try {
    admin.initializeApp({
      credential: admin.credential.cert(serviceAccount),
    });
  } catch (error) {
    console.log("Firebase admin initialization error", error.stack);
  }
}
export default admin.firestore();

然后在 getServerSideProps 里面

export async function getServerSideProps(context) {
  const id = context.params.profileId;
  const doc = await db.collection("profile").doc(id).get();
  const profile = doc.data();
  return {
    props: { profile },
  };
}

收到以下错误

error - ./node_modules/@google-cloud/storage/build/src/bucket.js:21:0
Module not found: Can't resolve 'fs'

是否有另一种方法可以调用 firebase 而无需使用依赖于文件系统的节点库? 或者有办法解决这个问题吗?

谢谢。

如果您使用的是 firebase firebase-admin ,则只能在 api 函数中使用。 你甚至不能在客户端导入它。 它需要访问客户端不可用的fs模块。 如果您在客户端需要 firebase,请使用@firebase/app npm 模块。

import { initializeApp, getApps } from 'firebase/app'
import { getAnalytics } from 'firebase/analytics'
export const createFirebaseApp = () => {
  const clientCredentials = {
    apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY,
    authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN,
    databaseURL: process.env.NEXT_PUBLIC_FIREBASE_DATABASE_URL,
    projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,
    storageBucket: process.env.NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET,
    messagingSenderId: process.env.NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID,
    appId: process.env.NEXT_PUBLIC_FIREBASE_APP_ID,
    measurementId: process.env.NEXT_PUBLIC_FIREBASE_MEASUREMENT_ID,
  }

  if (getApps().length <= 0) {
    const app = initializeApp(clientCredentials)
    // Check that `window` is in scope for the analytics module!
    if (typeof window !== 'undefined') {
      // Enable analytics. https://firebase.google.com/docs/analytics/get-started
      if ('measurementId' in clientCredentials) {
        getAnalytics()
      }
    }
    return app
  }
}

你可以有两个单独的 firebase 配置文件 一个如上所述用于客户端,另一个使用您定义firebase-admin

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM