Closed
Description
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
- Initialize Next.JS project.
- Set up Firebase Auth on the client side.
- Set up service worker to inject the
Authorization
header as in https://firebase.google.com/codelabs/firebase-nextjs - Set up Next.JS middleware to secure requests using
initializeServerApp
andAuth
// 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();
}