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

问题描述 投票:0回答:2

我刚刚使用 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()
}

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

reactjs typescript next.js middleware next-auth
2个回答
6
投票

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

要解决该问题,请将 if 更改为

!session && path !== "/login"


0
投票

将会有一个明显的解决方案,但我认为检查您是否有其他路由设置也很好。就我而言,/api 和 /_next 目录始终重定向到“/”。

export const config = {
  // Skip all paths that should not be internationalized. This example skips the
  // folders "api", "_next" and all files with an extension (e.g. favicon.ico)
  matcher: ['/((?!api|_next|.*\\..*).*)']
};
© www.soinside.com 2019 - 2024. All rights reserved.