firebase 如何重用next-auth initFirestore对象来从Firestore获取一些数据

6ojccjat  于 2023-06-07  发布在  其他
关注(0)|答案(1)|浏览(143)

我用next-auth v4.22.1建立了一个NextJS v13.4.2项目,让用户通过使用“Login with Google”按钮进行身份验证。我目前也在使用next-auth Firebase适配器。当前文件配置为:
/app/(lib)/firestore.js

import { initFirestore } from "@next-auth/firebase-adapter";
import { cert } from "firebase-admin/app";

export const firestore = initFirestore({
    credential: cert({
        projectId: process.env.FIREBASE_PROJECT_ID,
        clientEmail: process.env.FIREBASE_CLIENT_EMAIL,
        privateKey: process.env.FIREBASE_PRIVATE_KEY,
    }),
});

/app/(lib)/auth.js

import GoogleProvider from "next-auth/providers/google";
import { FirestoreAdapter } from "@next-auth/firebase-adapter";
import { firestore } from "@lib/firestore";

export const authOptions = {
    providers: [
        GoogleProvider({
            clientId: process.env.GOOGLE_ID,
            clientSecret: process.env.GOOGLE_SECRET,
        }),
    ],
    adapter: FirestoreAdapter(firestore),
};

/app/api/auth/[...nextauth]/route.js

import NextAuth from "next-auth";
import { authOptions } from "@lib/auth";

const handler = NextAuth(authOptions);

export { handler as GET, handler as POST };

现在,所有这些工作都很好,但我想做的是从我的Firestore数据库中查询一些数据并将其显示到页面中。所以,我想我可以这样做:

import { firestore } from "@lib/firestore";
import { collection, getDocs } from "firebase/firestore";

const citiesCol = collection(firestore, "cities");
const citiesSnapshot = await getDocs(citiesCol);
const citiesList = citiesSnapshot.docs.map((doc) => doc.data());

但不幸的是,我犯了一个错误:Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore
所以,我的问题是,我可以重用我导出的firestore对象(来自/app/(lib)/firestore.js)来处理下一个认证逻辑,以获取一些数据吗?或者我需要创建一个不同的firebase配置并重新初始化Firestore?

a2mppw5e

a2mppw5e1#

将其作为社区wiki发布以获得可见性。
@samthecodingman:
@next-auth/firebase-adapter是一个服务器端的软件包,这意味着要与firebase-admin一起使用。
您可以通过此link检查示例。
您可能还想在how to add Firebase to your JavaScript project上跟踪此链接。

相关问题