所以我正在遵循一个教程,但不知怎的陷入了一个问题,其中如果URL不存在于
routes.ts
中。它重定向到嵌套的 /auth/auth/...../login/
,而不是重定向到 localhost:3000/auth/login
中间件.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)(.*)"],
}
路线.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"
例如,我在此处创建了一个按钮,该按钮将重定向到尚未包含在我的
routes.ts
中的另一个页面。
<Button size="sm" variant="link" asChild className="px-0 font-normal">
<Link href="/auth/reset">Forgor Password?</Link>
</Button>;
例如我点击了它。
这是网址
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/登录
您遇到的问题可能是由于 NextAuth 处理未处理路由的方式造成的。默认情况下,NextAuth 将未处理的路由重定向到
/auth/login
进行身份验证。在您的情况下,由于您尝试重定向到的路由 (/auth/reset) 未在您的 routes.ts
文件中定义,因此 NextAuth 会将您重定向到 /auth/login
。
要解决此问题,您需要将
auth/reset
路由添加到 routes.ts
文件中。更新后的 routes.ts
文件应如下所示:
export const publicRoutes = [
"/",
"/auth/new-verification",
"/auth/reset",
]
export const authRoutes = [
"/auth/login",
"/auth/register",
"/auth/error"
]
export const apiAuthPrefix = "/api/auth"
export const DEFAULT_LOGIN_REDIRECT = "/settings"
进行此更改后,NextAuth 应正确地将未经身份验证的用户重定向到
/auth/login
页面,而经过身份验证的用户将能够按预期访问 /auth/reset
页面。