Skip to content

[FirebaseServerApp] Failed to initialize in Next.JS Edge Runtime #8299

Closed
@JoseVSeb

Description

@JoseVSeb

Operating System

N/A

Browser Version

N/A

Firebase SDK Version

10.12.2

Firebase SDK Product:

Auth

Describe your project's tooling

Next.JS

Describe the problem

I cannot use initializeServerApp in Next.JS middleware (Edge runtime) to secure the server at middleware as intended.

However, just commenting out isBrowser() guard clause makes it run as intended.

I understand why it fails (Edge runtime is essentially the same as Browser runtime) and why the guard clause is there, but implementing security in Next.JS middleware is a life-saver in code complexity.

Third-party libraries like next-firebase-auth-edge require the use of service account credentials which is not ideal especially since FirebaseServerApp does what is required without the same.

Steps and code to reproduce issue

  1. Initialize Next.JS project.
  2. Set up Firebase Auth on the client side.
  3. Set up service worker to inject the Authorization header as in https://firebase.google.com/codelabs/firebase-nextjs
  4. Set up Next.JS middleware to secure requests using initializeServerApp and Auth
// middleware.ts
const getIdTokenInServer = () => {
  const prefix = "Bearer ";
  const authorizationHeader = headers().get("Authorization");
  if (!authorizationHeader?.startsWith(prefix)) return null;
  return authorizationHeader.split(prefix)[1] ?? null;
};
const getFirebaseServerApp = () => {
  const idToken = getIdTokenInServer();
  // fails with guard clause but works fine if it's removed
  return initializeServerApp(
    firebaseConfig,
    idToken ? { authIdToken: idToken } : {},
  );
};
const getAuthInServer = () => getAuth(getFirebaseServerApp());
export async function middleware(req: NextRequest) {
  const auth = getAuthInServer();
  await auth.authStateReady()

  if (!auth.currentUser) return NextResponse.redirect(/** redirect url */);

  /** other authorization logic */

  return NextResponse.next();
}

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions