Search code examples
firebasegoogle-cloud-firestorenext.jsnext-auth

How to reuse the next-auth initFirestore object to also fetch some data from Firestore


I've set up a NextJS v13.4.2 project with next-auth v4.22.1 to let users authenticate by using the 'Login with Google' button. I'm also currently using the next-auth Firebase adapter. The current files configs are:

/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 };

Now, all of this works fine, but what I would like to do is to also query some data from my Firestore db and displaying it into a page. So, I thought I could do that by doing:

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());

But sadly I get the error: Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore

So, my question is, can I reuse the firestore object (from /app/(lib)/firestore.js) that I'm exporting for handling the next-auth logics to also fetch some data? Or do I need to create a different firebase config and initialize Firestore again?


Solution

  • According to @samthecodingman:

    @next-auth/firebase-adapter is a server-side package and this is meant to use with firebase-admin.

    You may check an example through this link.

    You may also want to follow this link on how to add Firebase to your JavaScript project.