如果不存在 cookie,则使用 Next JS 中间件重定向到登录页面

Ran*_* MD 6 redirect reactjs next.js

我正在 Next JS 应用程序中实现身份验证。我需要从浏览器获取cookie并在Next js中间件中检查cookie。如果没有 cookie,我需要将页面重定向到“/login”路线。但页面正在中间件中不断发出请求以获取页面。

如果没有cookie,如何重定向页面?

/middleware.js我在(使用 Nextjs 13)中尝试了以下代码

import { NextResponse } from "next/server";

export function middleware(req) {
  const cookie = req.cookies.get("token")?.value;
  if (cookie === undefined) {
    const url = req.nextUrl.clone();
    url.pathname = "/login";
    return NextResponse.redirect(url, req.url);
  }
}

Run Code Online (Sandbox Code Playgroud)

这是浏览器发出的请求 nextjs 中间件请求

小智 9

您必须在中间件上使用匹配器。

你有无限的重定向,因为你没有cookie,你会被重定向到登录页面-->调用中间件-->检查cookie-->cookie为空-->重定向到登录-->反之亦然。

将其添加到您的中间件文件中:

export const config = {
    matcher: [
        '/((?!_next/static|favicon.ico|login|).*)',
    ]
}
Run Code Online (Sandbox Code Playgroud)

来自 /_next/static、/favicon.ico 和 /login 的每个请求都将被忽略。

有关 NextJS 文档的更多信息:https ://nextjs.org/docs/advanced-features/middleware#matcher