Search code examples
firebasenext.jsnext-auth

next-auth with Google provider and Firebase does not create a user in authentication


I have configured next-auth with Firebase in api/auth/[...nextauth].js as follows:

import {FirestoreAdapter} from "@auth/firebase-adapter"
import {cert} from "firebase-admin/app"
import NextAuth from "next-auth"
import GoogleProvider from "next-auth/providers/google"
export const authOptions = {
  // Configure one or more authentication providers
  providers: [
    GoogleProvider({
      clientId: process.env.GOOGLE_CLIENT_ID,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET,
    }
    ),
  ],
  adapter: FirestoreAdapter({
    credential: cert({
      projectId: process.env.FIREBASE_PROJECT_ID,
      clientEmail: process.env.FIREBASE_CLIENT_EMAIL,
      privateKey: process.env.FIREBASE_PRIVATE_KEY.replace(/\\n/g, '\n')
    })
  })

}

export default NextAuth(authOptions)

And I added all the environment variables, Google etc

On the client I'm using the signIn function like so:

<button onClick={() => signIn('google')}
                      
                    >
                        <FcGoogle className=" w-10 h-10" />
</button>

Which once clicked I'm able to sign in successfully and users, sessions,accounts collections are created in Firestore successfully, but there is no record in Firebase authentication. My question is why is this happening and how can I solve this?

Update

I found a similar question nextauth-signin-not-creating-user-in-firebase-authentication with no answers.


Solution

  • You can use signInWithCredential to link, in your next-auth signIn callback:

    const firebaseApp = initializeApp(__FIREBASE_CONFIG__);
    const firebaseAuth = getAuth(firebaseApp);
    
     callbacks: {
        signIn: async ({ user, account, profile, email, credentials }) => {
    
          if (account?.provider === 'google') {
             signInWithCredential(
                firebaseAuth,
                GoogleAuthProvider.credential(
                  account.id_token,
                  account.access_token
                )
              );
            return true;
         }
      }
    }