gladly-team / next-firebase-auth

Simple Firebase authentication for all Next.js rendering strategies
https://nfa-example-git-v1x-gladly-team.vercel.app/
MIT License
1.34k stars 291 forks source link

v1: Cannot access admin SDK while unauthenticated #573

Closed strid408 closed 1 year ago

strid408 commented 1 year ago

Describe the bug

When trying to access the admin SDK in getServerSideProps while unauthenticated the following error appears.

Screenshot 2022-11-05 at 23 02 28

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:

  1. Clone example project from v1.x branch
  2. Add getFirestore from 'firebase-admin/firestore' to getServerSideProps in index.js (root page)
    export const getServerSideProps = withAuthUserTokenSSR()(() => {
    const firestore = getFirestore();
    return {
    props: {},
    }
    })
  3. 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.

kmjennison commented 1 year ago

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