NextJs Middleware with Firebase auth
Unanswered
Sun bear posted this in #help-forum
Sun bearOP
Hi! I am using middleware.ts in NextJs. (for everyone who is not into NextJs yet, as per the official documentation:
I want to use Firebase to authenticate the user in the middleware using Firebase auth and enforce authorization on my website.
I am trying the following piece of code:
But i am encountering so many issues, what is the right approach to use Firebase auth with NextJs middleware?
Middleware allows you to run code before a request is completed. Then, based on the incoming request, you can modify the response by rewriting, redirecting, modifying the request or response headers, or responding directly.
Middleware runs before cached content and routes are matched.
I want to use Firebase to authenticate the user in the middleware using Firebase auth and enforce authorization on my website.
I am trying the following piece of code:
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { onAuthStateChanged } from "firebase/auth";
import { auth } from "./Firebase/firebaseConfig";
export async function middleware(request: NextRequest) {
onAuthStateChanged(auth, (user) => {
if (user) {
return NextResponse.redirect(new URL("/", request.url));
} else {
return NextResponse.redirect(new URL("/sign"));
}
});
}
But i am encountering so many issues, what is the right approach to use Firebase auth with NextJs middleware?
3 Replies
Middleware is server-side code that executes before the response is completed.
the
Correct approach:
1. Verify the user's ID token on the server side.
2. Use Firebase Admin SDK for server-side authentication.
the
onAuthStateChanged
, is designed to work in the browser and not on the server, which means it won't work in Next.js middleware since middleware runs on the server.Correct approach:
1. Verify the user's ID token on the server side.
2. Use Firebase Admin SDK for server-side authentication.
Sun bearOP
thanks, at the moment I am calling a server action from the client side, and in that action using the Firebase signInWithEmailandPassword function to authenticate the user, if it returns the user then I return the positive response from it then perform the user's all that token process (using jose library). showing an error alert on the client side in case of a negative response from this action. this all works fine but is this the correct approach? should I use admin sdk?
Going by the book, Firebase Admin SDK is usually the top pick for server-side operations. It's got the edge in terms of security and efficiency. But it seems like you've got it covered!