v1: Cannot access admin SDK while unauthenticated
strid408 opened this issue · 1 comments
Describe the bug
When trying to access the admin SDK in getServerSideProps while unauthenticated the following error appears.
Versions
next-firebase-auth
1.0.0-canary.17:
Firebase JS SDK: 9.9.1
Next.js: 12.2.3
To Reproduce
Steps to reproduce the behavior:
- Clone example project from v1.x branch
- Add getFirestore from 'firebase-admin/firestore' to getServerSideProps in index.js (root page)
export const getServerSideProps = withAuthUserTokenSSR()(() => {
const firestore = getFirestore();
return {
props: {},
}
})
- See error
Expected behavior
Firebase admin SDK should be accessible inside getServerSideProps even though the client isn't authenticated.
Additional context
While authenticated, the admin SDK works as expected.
Thanks for the clear issue!
I was able to reproduce locally: when the user is authenticated, the default Firebase admin app appears to initialize as expected; when the user is not authenticated, I receive the same error (FirebaseAppError: The default Firebase app does not exist.
). Note that to repro, you have to stop and restart the dev server between changes to make sure the Firebase admin state is cleared.
This debug log is present when it succeeds:
next-firebase-auth: [init] Initialized the Firebase admin SDK.
But that debug log isn't present when it fails, so we're not calling Firebase admin init here.
I believe the cause of this is that we only init Firebase admin on demand, like when we verify the ID token. That works for the package's authentication but will break under the use case described here.
This should be a quick fix by making sure we always init the Firebase admin. We can add initFirebaseAdminSDK
(from: import initFirebaseAdminSDK from 'src/initFirebaseAdminSDK'
) at the top of getUserFromCookies
:
https://github.com/gladly-team/next-firebase-auth/blob/v1.x/src/getUserFromCookies.js