Next.js Middleware/Proxy redirect loop at /login in Production, but works perfectly on npm start locally #96332
Replies: 2 comments 3 replies
|
This looks more like a matcher or Amplify configuration issue than a cookie issue. Make sure /login is included in your matcher and avoid redirecting to the current route: export function proxy(request: NextRequest) {
const path = request.nextUrl.pathname
const token = request.cookies.get("session")?.value
if (token && path === "/login") {
return NextResponse.redirect(new URL("/dashboard", request.url))
}
if (!token && path.startsWith("/dashboard")) {
return NextResponse.redirect(new URL("/login", request.url))
}
return NextResponse.next()
}
export const config = {
matcher: ["/login", "/verify-otp", "/dashboard/:path*"],
}The [Next.js Proxy docs](https://nextjs.org/docs/app/api-reference/file-conventions/proxy) say: “The matcher option allows you to target specific paths for the Proxy to run on.” Also ensure the session cookie has path: "/". Then check Amplify’s Rewrites and redirects section for a /login or SPA catch-all rule. One more important point: [Amplify currently documents support only through Next.js 15](https://docs.aws.amazon.com/amplify/latest/userguide/ssr-amplify-support.html). If you use Next.js 16 with proxy.ts, the production environment may not fully support it yet. |
|
Do you have any logs or headers you see during the navigation? Often when Are you able to curl this endpoint while pretending to be logged in as well? Like login, and then in the Chrome Dev tools you can copy a request as |
Uh oh!
There was an error while loading. Please reload this page.
Summary
Hi everyone,
I am facing a strange routing issue where my application works flawlessly in local development (next dev) and during local production simulation (npm run build && npm run start). However, once deployed to my production environment(amplify), it breaks with a redirect loop error specifically when handling the /login route.
The Setup:
The Bug:
When i am logged in i go to dashboard and i have make the public pages like /login,/verify-otp etc but when i am logged in and try to go to the login page my middleware is not working and it is going to the login page even if i have to cookies for login the catch is that the middle ware is working on other public routes but not for login only.
Has anyone encountered this specific environment mismatch between local npm start and live hosting environments? Could this be related to Edge runtime deployment restrictions, or how Next.js handles production cookie headers differently than localhost? Any help or pointers would be greatly appreciated!
Additional information
No response
Example
No response
All reactions