- Notifications
You must be signed in to change notification settings - Fork4k
Description
Adapter type
@auth/firebase-adapter
Environment
System:
OS: Windows 11 10.0.22621
CPU: (12) x64 11th Gen Intel(R) Core(TM) i5-11400H @ 2.70GHz
Memory: 1.04 GB / 7.75 GB
Binaries:
Node: 21.6.1 - C:\Program Files\
odejs\
ode.EXE
npm: 10.4.0 - C:\Program Files\
odejs\
pm.CMD
Browsers:
Edge: Chromium (122.0.2365.80)
Internet Explorer: 11.0.22621.1
npmPackages:
@auth/firebase-adapter: ^1.5.0 => 1.5.0
next: 14.1.3 => 14.1.3
next-auth: ^4.24.7 => 4.24.7
react: ^18 => 18.2.0
Reproduction URL
https://github.com/GroophyLifefor/reproduction
Describe the issue
Please READ HERE
Scenario: I am a developer, I wanted to use NextAuth, I tried to connect Firebase, "it was working on my computer" :D. I realized that it was not working in production, I tried to solve it in different ways but I could not solve it
First stage - traditional
the auth part of my project is divided into two parts.
/src/app/api/auth/[...nextauth]/route.ts /src/app/options.tsroute.ts
import{authOptions}from'@/app/options';importNextAuthfrom'next-auth';consthandler=NextAuth(authOptions);export{handlerasGET,handlerasPOST};
options.ts
import{NextAuthOptions}from"next-auth";importGoogleProviderfrom"next-auth/providers/google";importFirebaseAdapterfrom"@next-auth/firebase-adapter";import{Adapter}from"next-auth/adapters";exportconstauthOptions:NextAuthOptions={providers:[GoogleProvider({clientId:process.env.GOOGLE_CLIENT_IDasstring,clientSecret:process.env.GOOGLE_CLIENT_SECRETasstring,}),],adapter:FirebaseAdapterasAdapter,secret:"http://127.0.0.1:3000/api/auth",};
The problem I'm having here is, first of all, I get an error like this when compiling.
⚠ ./src/app/options.ts
Attempted import error: '@next-auth/firebase-adapter' does not contain a default export (imported as 'FirebaseAdapter').
This is like a warning but it says error in Vercel deployment and CI/CD stops.
and when I log in, it doesn't register in firebase.
But it's the only one I can log in, so it's a huge plus. that's is why this way first stage
Second Stage - Carriage
route.ts
import{authOptions}from'@/app/options';importNextAuthfrom'next-auth';consthandler=NextAuth(authOptions);export{handlerasGET,handlerasPOST};
options.ts - (M)odified
import{NextAuthOptions}from"next-auth";importGoogleProviderfrom"next-auth/providers/google";import{FirebaseAdapterConfig,FirestoreAdapter}from"@next-auth/firebase-adapter";import{Adapter}from"next-auth/adapters";import{connectToDatabaseNotAsync}from"@/lib/firestore";const{ db}=connectToDatabaseNotAsync();import{getFirestore,collection,query,getDocs,where,limit,doc,getDoc,addDoc,updateDoc,deleteDoc,}from"firebase/firestore";constfirebaseClient={ db, collection, query, getDocs, where, limit, doc, getDoc, addDoc, updateDoc, deleteDoc,};exportconstauthOptions:NextAuthOptions={providers:[GoogleProvider({clientId:process.env.GOOGLE_CLIENT_IDasstring,clientSecret:process.env.GOOGLE_CLIENT_SECRETasstring,}),],adapter:FirestoreAdapter(firebaseClientasFirebaseAdapterConfig)asAdapter,secret:"http://127.0.0.1:3000/api/auth",};
At this stage I no longer get the import error in the build phase, but I get another error that runtime error.
error
blabla'Cause'...14538morecharacters,name:'Error'}[next-auth][error][SESSION_ERROR] https://next-auth.js.org/errors#session_error Unable to detect a Project Id in the current environment.TolearnmoreaboutauthenticationandGoogleAPIs,visit: https://cloud.google.com/docs/authentication/getting-started Error: Unable to detect a Project Id in the current environment.blabla(verylong)(THISTHREETIMESCOMES)atasyncServer.requestListener(C:\\Users\\Groop\\Desktop\\Desktop\\Code\\javascript\\commentinV2\\commentin\ode_modules\ext\\dist\\server\\lib\\start-server.js:140:13){ name:'GetSessionAndUserError',code:undefined}[next-auth][error][SESSION_ERROR] https://next-auth.js.org/errors#session_error Unable to detect a Project Id in the current environment.blablaatasyncServer.requestListener(C:\\Users\\Groop\\Desktop\\Desktop\\Code\\javascript\\commentinV2\\commentin\ode_modules\ext\\dist\\server\\lib\\start-server.js:140:13){ name:'GetUserByAccountError',code:undefined}
also auth too not working!
Third Stage - With over-research and deep found ways
route.ts
import{authOptions}from'@/app/options';importNextAuthfrom'next-auth';consthandler=NextAuth(authOptions);export{handlerasGET,handlerasPOST};
options.ts - (M)odified
import{FirestoreAdapter}from"@auth/firebase-adapter";import{cert}from"firebase-admin/app";import{NextAuthOptions}from"next-auth"import{Adapter}from"next-auth/adapters";importGoogleProviderfrom"next-auth/providers/google";import*asadminfrom'firebase-admin'exportconstauthOptions:NextAuthOptions={// Configure one or more authentication providers// https://next-auth.js.org/providersproviders:[GoogleProvider({clientId:process.env.GOOGLE_IDasstring,clientSecret:process.env.GOOGLE_SECRETasstring,}),],// see https://authjs.dev/reference/adapter/firebase#usage// adapter: FirestoreAdapter({}),adapter:FirestoreAdapter({credential:cert({projectId:process.env.FIREBASE_PROJECT_ID,clientEmail:process.env.FIREBASE_CLIENT_EMAIL,privateKey:process.env.FIREBASE_PRIVATE_KEY,}),})asAdapter,callbacks:{asyncsession({ session, token}){// ...if(token&&token.uid){constfirebaseToken=awaitadmin.auth().createCustomToken(token.uidasstring)//@ts-ignoresession.firebaseToken=firebaseToken}returnsession},},session:{strategy:'jwt',},}
Previously I was only initializing firebase, I was doing it in a file calledfirestore.ts, I didn't feel the need to add it because there is nothing magical, it just initializes plain.
I imported firebase-admin asimport * as admin from 'firebase-admin'
in this case take care as admin so It's not confict with firebase-app initialize
admin.initializeApp({credential:admin.credential.cert({projectId:process.env.FIREBASE_PROJECT_ID,clientEmail:process.env.FIREBASE_CLIENT_EMAIL,privateKey:process.env.FIREBASE_PRIVATE_KEY,}),})
and finally I have made some changes to my home page,
- imported getAuth and signInWithCustomToken from "firebase/auth"
- used getAuth to get auth
- and a function called syncFirebaseAuth that manage signin and signout also called every session changed with useEffect
page.tsx
import{getAuth,signInWithCustomToken}from"firebase/auth";import{connectToDatabase}from"@/lib/firestore";import{FirebaseApp}from"firebase/app";exportdefaultfunctionHome(){const{data:session}=useSession();const[auth,setAuth]=useState<FirebaseApp|null>(null);asyncfunctioninitAuth(){const{ app}=awaitconnectToDatabase();//@ts-ignoresetAuth(getAuth(app));}asyncfunctionsyncFirebaseAuth(){//@ts-ignoreif(session&&session.firebaseToken){try{//@ts-ignoreawaitsignInWithCustomToken(auth,session.firebaseToken);}catch(error){console.error("Error signing in with custom token:",error);}}else{//@ts-ignoreauth.signOut();}}useEffect(()=>{DsyncFirebaseAuth();},[session]); ...}
so provider and adapter values was okey, but still error
error
blabla[next-auth][error][adapter_error_getUserByAccount] https://next-auth.js.org/errors#adapter_error_getuserbyaccount Unable to detect a Project Id in the current environment.TolearnmoreaboutauthenticationandGoogleAPIs,visit: https://cloud.google.com/docs/authentication/getting-started {message:'Unable to detect a Project Id in the current environment. \'+'To learn more about authentication and Google APIs, visit: \'+'https://cloud.google.com/docs/authentication/getting-started',stack:'Error: Unable to detect a Project Id in the current environment. \'+'To learn more about authentication and Google APIs, visit: \'+'https://cloud.google.com/docs/authentication/getting-started\'+' at GoogleAuth.findAndCacheProjectId (C:\\\\Users\\\\Groop\\\\Desktop\\\\Desktop\\\\Code\\\\javascript\\\\commentinV2\\\\commentin\\\ode_modules\\\\google-auth-library\\\\build\\\\src\\\\auth\\\\googleauth.js:124:19)\'+' at process.processTicksAndRejections (node:internal/process/task_queues:95:5)\'+blabla(verylong)'Cause'...24114morecharacters,name:'Error'}[next-auth][error][OAUTH_CALLBACK_HANDLER_ERROR]blabla2\\commentin\ode_modules\ext\\dist\\server\\lib\\router-server.js:377:13)atasyncServer.requestListener(C:\\Users\\Groop\\Desktop\\Desktop\\Code\\javascript\\commentinV2\\commentin\ode_modules\ext\\dist\\server\\lib\\start-server.js:140:13){name:'GetUserByAccountError',code:undefined}
How to reproduce
Actually I couldn't get rid of these errors no matter what I did, if you try to setup it in a normal way you may get these errors.
Expected behavior
error-free, bug-free life



