NextJS13 + Auth0 如何根据邮箱验证状态重定向用户
解决NextJS 13 + Auth0未验证邮箱用户重定向问题
针对你使用NextJS 13.4.19 + Auth0 3.1.0在App Router下的场景,要实现未验证邮箱用户登录后重定向到/verify-email页面,需要调整afterCallback的处理逻辑,同时适配App Router的API路由规范,具体方案如下:
核心修改点
- 使用Auth0 SDK提供的
RedirectError触发重定向,这是SDK官方支持的回调流程跳转方式 - 修正API路由的参数类型,适配App Router的
NextRequest规范 - 移除无效的headers修改和直接返回响应的错误写法
完整代码示例
import { handleAuth, handleCallback, handleLogin, RedirectError, Session } from '@auth0/nextjs-auth0'; import { NextRequest } from 'next/server'; const afterCallback = async (req: NextRequest, session: Session) => { if (session.user.email_verified) { console.log('email verified..continuing'); return session; } // 抛出RedirectError触发重定向,SDK会自动处理跳转逻辑 throw new RedirectError('/verify-email'); }; export const GET = handleAuth({ callback: async (req: NextRequest) => { try { console.log('callback method called'); return await handleCallback(req, { afterCallback, }); } catch (error) { console.error(error); // 可选:处理其他错误,比如重定向到统一错误页 return Response.redirect(new URL('/error', req.url)); } }, login: async (req: NextRequest) => { console.log('login method called'); return await handleLogin(req, { returnTo: '/dashboard', // 邮箱验证通过后的默认跳转页 }); }, });
关键说明
RedirectError的作用:这是Auth0 SDK专为回调流程设计的错误类型,抛出后handleCallback会自动拦截并生成重定向响应,无需手动处理headers或返回响应- 参数类型修正:App Router的API路由不再使用
NextApiRequest/NextApiResponse,而是使用标准的NextRequest,需同步调整函数参数类型 - 为什么之前的方法无效:
headers.set报错是因为headers()返回的是只读对象;直接返回NextResponse.redirect不符合afterCallback的返回值约定(该函数预期返回Session对象)
内容的提问来源于stack exchange,提问作者LearnToLive
相关产品推荐
相关产品推荐

