NextJS 中间件导致“localhost 重定向您太​​多次”错误

PiW*_*852 6 middleware typescript reactjs next.js next-auth

我刚刚使用 NextAuth 在本地托管的 NextJS 应用程序中实现了电子邮件/密码身份验证。当我创建中间件来保护路由时,每当我单击注销按钮时,我都会收到错误“localhost 重定向您太​​多次”。 错误的图像

这是我的middleware.ts文件:

import { NextRequest, NextResponse } from 'next/server'

export default async function middleware(req: NextRequest) {
    const path = req.nextUrl.pathname;

    const session = await getToken({
        req,
        secret: process.env.NEXTAUTH_SECRET,
    });
    if (!session) {
        return NextResponse.redirect(new URL('/login', req.url))
    } else if (session && (path === '/login' || path === '/signup')) {
        return NextResponse.redirect(new URL('/', req.url))
    }
    return NextResponse.next()
}
Run Code Online (Sandbox Code Playgroud)

有没有一种方法可以在没有中间件的情况下保护所有这样的路由,或者在没有重定向的情况下实现功能?蒂亚

小智 8

发生这种情况是因为您编写了一个仅包含条件的 if (!session),然后始终重定向到同一路由 (/login),导致过多的重定向到同一路由。

要解决该问题,请将 if 更改为!session && path !== "/login"