通过这个示例,我可以让nextjs重定向到一个指定的页面,比如登录页面,如果有人没有经过身份验证。然而,我可以如何修改这个,以便如果用户经过身份验证并且页面是类似登录页面的,将他们重定向到仪表板或其他页面?有一个配置可以实现吗?像matcher会很好地维护私有URL。但是对于我不希望用户在登录状态下访问的特定公共URL,我该如何解决这个问题?这种情况是否可能?
import { NextRequest, NextResponse } from 'next/server'
export async function middleware(req: NextRequest, res: NextResponse) {
const token = req.headers.get('token') // TODO: 从请求头中获取令牌
const userIsAuthenticated = false // TODO: 检查用户是否经过身份验证
console.log('middleware.ts', 'token', token);
if (!userIsAuthenticated) {
const signinUrl = new URL('/login', req.url)
return NextResponse.redirect(signinUrl)
}
return NextResponse.next()
}
// 在这里,您可以指定此中间件函数应该运行的所有路径
// 支持单个字符串值或匹配器数组
export const config = {
matcher: ['/api/auth/:path*', '/'],
} Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
假设您正在使用Next-Auth进行身份验证:
使用
withAuth包装中间件,并使用Next-Auth提供的token变量验证会话,然后根据会话的有效性重定向到您希望的route。这是一个可能有帮助的TS代码:
import { NextResponse } from 'next/server'; import { withAuth, NextRequestWithAuth } from 'next-auth/middleware'; export default withAuth(function middleware (request: NextRequestWithAuth) { const session = request?.nextauth?.token; if (request.nextUrl.pathname === '/') return NextResponse.next(); if (!session && request.nextUrl.pathname !== '/login') return NextResponse.redirect(new URL('/login', request.url)); if (session && request.nextUrl.pathname !== '/dashboard') return NextResponse.redirect(new URL('/dashboard', request.url)); return NextResponse.next(); }, { callbacks: { authorized: () => true, }, }); export const config = { matcher: [ '/((?!api|_next/static|_next/image|favicon.ico).*)', ], };