so I was following a tutorial and somehow stuck in a problem wherein if the URL is not existing in the routes.ts
. It redirects to a nested /auth/auth/...../login/
instead of redirecting it to localhost:3000/auth/login
middleware.ts
import authConfig from "./auth.config"
import NextAuth from "next-auth"
import {
DEFAULT_LOGIN_REDIRECT,
publicRoutes,
apiAuthPrefix,
authRoutes
} from '@/routes'
const { auth } = NextAuth(authConfig)
export default auth((req) => {
const { nextUrl } = req;
const isLoggedIn = !!req.auth;
const isApiAuthRoute = nextUrl.pathname.startsWith(apiAuthPrefix);
const isPublicRoute = publicRoutes.includes(nextUrl.pathname);
const isAuthRoute = authRoutes.includes(nextUrl.pathname);
if(isApiAuthRoute){
return ;
}
if(isAuthRoute){
if(isLoggedIn){
return Response.redirect(new URL(DEFAULT_LOGIN_REDIRECT, nextUrl))
}
return ;
}
if(!isLoggedIn && !isPublicRoute){
return Response.redirect(new URL('auth/login', nextUrl))
}
return ;
})
export const config = {
matcher: ["/((?!.+\.[\w]+$|_next).*)", "/", "/(api|trpc)(.*)"],
}
routes.ts
export const publicRoutes = [
"/",
"/auth/new-verification"
]
export const authRoutes = [
"/auth/login",
"/auth/register",
"/auth/error"
]
export const apiAuthPrefix = "/api/auth"
export const DEFAULT_LOGIN_REDIRECT = "/settings"
For example, I’ve created a button here that will redirect to another page that is not included yet in my routes.ts
.
<Button size="sm" variant="link" asChild className="px-0 font-normal">
<Link href="/auth/reset">Forgor Password?</Link>
</Button>;
For example I clicked it.
this is the url
http://localhost:3000/auth/auth/auth/auth/auth/auth/auth/auth/auth/auth/auth/auth/auth/auth/auth/auth/auth/auth/auth/auth/auth/auth/auth/auth/auth/auth/auth/auth/auth/auth/auth/auth/auth/auth/auth/auth/auth/auth/auth/login
2
Answers
In this function statement, I forgot to include a
/
before the(auth/login)
I change it into this
The issue you’re encountering is likely due to the way NextAuth handles unhandled routes. By default, NextAuth redirects unhandled routes to
/auth/login
for authentication. In your case, since the route you’re trying to redirect to (/auth/reset) is not defined in yourroutes.ts
file, NextAuth is redirecting you to/auth/login
instead.To fix this issue, you need to add the
auth/reset
route to yourroutes.ts
file. Here’s what your updatedroutes.ts
file should look like:After making this change, NextAuth should correctly redirect unauthenticated users to the
/auth/login
page, while authenticated users will be able to access the/auth/reset
page as expected.