-
Notifications
You must be signed in to change notification settings - Fork 301
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Issue: Next js Middleware Ininite Redirection #371
Comments
@firstaxel Here is my working middleware and stack. I hope it will help.
|
@firstaxel The infinite loop you're running into is a direct result of the code you're writing. You have logic So... when you visit Here's what I'm doing in my middleware to redirect users to sign-in if they try to access a protected route when they aren't logged in: import { stackServerApp } from "@repo/auth/server";
import { type NextRequest, NextResponse } from "next/server";
// This because Next.js doesn't let you match against route groups :(
const routeMaps = {
protected: ["/dashboard", "/onboarding"],
auth: ["/handler", "/sign-in", "/sign-up"],
};
export async function middleware(request: NextRequest) {
const { pathname } = request.nextUrl;
// Check if the user is authenticated
const isAuthenticated = await checkAuthStatus();
// Handle the base route
if (pathname === "/") {
if (isAuthenticated) {
return NextResponse.redirect(new URL("/dashboard", request.url));
} else {
return NextResponse.redirect(new URL("/sign-in", request.url));
}
}
if (routeMaps.auth.some((route) => pathname.includes(route))) {
// If user is already authenticated and trying to access auth routes, redirect to dashboard
if (isAuthenticated) {
return NextResponse.redirect(new URL("/dashboard", request.url));
}
// Otherwise, allow access to auth routes
return NextResponse.next();
}
if (routeMaps.protected.some((route) => pathname.includes(route))) {
// If user is not authenticated and trying to access protected routes, redirect to login
if (!isAuthenticated) {
return NextResponse.redirect(new URL("/sign-in", request.url));
}
// Otherwise, allow access to protected routes
return NextResponse.next();
}
// Handle other routes as needed
return NextResponse.next();
}
// Check if the user is authenticated
async function checkAuthStatus(): Promise<boolean> {
const user = await stackServerApp.getUser();
if (user) {
return true;
}
return false;
}
export const config = {
matcher: [
/*
* Match all request paths except for the ones starting with:
* - api (API routes)
* - _next/static (static files)
* - _next/image (image optimization files)
* - favicon.ico, sitemap.xml, robots.txt (metadata files)
*/
"/((?!api|_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)",
],
}; |
i dont know the issue calling get authServer.getUser() in my nextjs middleware cause infinite redirection
The text was updated successfully, but these errors were encountered: