Open Vicidevs opened 1 month ago
Hey @Vicidevs,
Could you share your middleware.ts
file and next.config.js
file?
import { NextRequest, NextResponse } from "next/server"; import { authMiddleware, redirectToHome, redirectToLogin, } from "next-firebase-auth-edge"; import { authConfig } from "./config/server-config";
const PUBLIC_PATHS = ["/auth/register", "/auth/login", "/auth/reset-password"];
export async function middleware(request: NextRequest) { return authMiddleware(request, { loginPath: "/api/login", logoutPath: "/api/logout", apiKey: authConfig.apiKey, cookieName: authConfig.cookieName, cookieSerializeOptions: authConfig.cookieSerializeOptions, cookieSignatureKeys: authConfig.cookieSignatureKeys, serviceAccount: authConfig.serviceAccount, handleValidToken: async ({ token, decodedToken }, headers) => { // Authenticated user should not be able to access /login, /register and /reset-password routes if (PUBLIC_PATHS.includes(request.nextUrl.pathname)) { return redirectToHome(request); }
return NextResponse.next({
request: {
headers,
},
});
},
handleInvalidToken: async (reason) => {
console.info("Missing or malformed credentials", { reason });
return redirectToLogin(request, {
path: "/auth/login",
publicPaths: PUBLIC_PATHS,
});
},
handleError: async (error) => {
console.error("Unhandled authentication error", { error });
return redirectToLogin(request, {
path: "/auth/login",
publicPaths: PUBLIC_PATHS,
});
},
}); }
export const config = { matcher: [ "/user/:path", "/((?!next|favicon.ico|/auth|_/firebase|api|.\.).*)", "/api/login", "/api/logout", ], };
next.config.js
/* @type {import('next').NextConfig} / const nextConfig = {};
export default nextConfig;
You are using redirectToHome
helper function from next-firebase-auth-edge
which redirects to /
page.
You should write your own redirect function, for example:
export function redirectToUser(request: NextRequest) {
const url = request.nextUrl.clone();
url.pathname = '/user';
return NextResponse.redirect(url);
}
Then, in middleware use it instead of redirectToHome
:
if (PUBLIC_PATHS.includes(request.nextUrl.pathname)) {
return redirectToUser(request);
}
then should probably add second arg e.g "path" to redirectToHome to pass home path to the helper function. I was stuck with this too, wasn't documented. Lmk if a PR will be accepted?
I will introduce another function called redirectToPath
that will help with your cases. I will also update docs to encourage people to write their own redirect functions for more complex use cases.
Thanks for feedback!
I changed the authenticated part to "/user" instead of "/" in the middleware but it keeps on directing me to "/"