我正在使用 Next.js 14.2.5、tRPC 和 Next-auth 5.0.0-beta.20(或 Auth.js)制作一个应用程序进行身份验证。用户登录应用程序后,我想将他重定向到另一个页面,但是,当我尝试这样做时,会出现 NEXT_REDIRECT 错误,应用程序什么也不做。据我所知,这个错误是预料之中的,你应该把它抛到 catch 块的末尾,这样 next.js 就可以继续重定向,但这是行不通的。
这是我用于登录的 tRPC 端点的代码:
loginProcedure: publicProcedure.input(LoginSchema).mutation(async (opts) => {
const { input } = opts;
const validatedFields = LoginSchema.safeParse(input);
if (!validatedFields.success) {
throw new TRPCError({ code: "PARSE_ERROR" }); //"invalid fields"
}
const { email, password } = validatedFields.data;
try {
await signIn("credentials", {
email,
password,
redirectTo: DEFAULT_LOGIN_REDIRECT,
});
} catch (error) {
if (error instanceof AuthError) {
switch (error.type) {
case "CredentialsSignin":
throw new TRPCError({
code: "UNAUTHORIZED",
message: "Invalid credentials",
});
default:
throw new TRPCError({
code: "UNAUTHORIZED",
message: "Something went wrong",
});
}
}
console.log(error)
throw error;
}
}),
这是我的 middleware.ts
import { auth } from "@/auth";
import {
DEFAULT_LOGIN_REDIRECT,
apiAuthPrefix,
authRoutes,
publicRoutes,
} from "@/routes";
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("/login", nextUrl))
}
});
export const config = {
matcher: [
// Skip Next.js internals and all static files, unless found in search params
"/((?!_next|[^?]*\\.(?:html?|css|js(?!on)|jpe?g|webp|png|gif|svg|ttf|woff2?|ico|csv|docx?|xlsx?|zip|webmanifest)).*)",
// Always run for API routes
"/(api|trpc)(.*)",
],
};
如果我输入了正确的凭据,登录就不会出现问题,我可以获取当前会话,但重定向永远不会发生。这是 Next.js 错误还是我遗漏了什么?