NextJS Vercel部署错误Nested Middleware is not allowed,发现:pages/_middleware

Flo*_*y99 8 javascript reactjs next.js vercel

突然我的中间件在部署中停止工作。错误是:

> Build error occurred
NestedMiddlewareError: Nested Middleware is not allowed, found:
pages/_middleware
Please move your code to a single file at /middleware instead.
Run Code Online (Sandbox Code Playgroud)

Vercel 声明是:例如,pages/about/_middleware.ts 中的中间件可以将逻辑移动到存储库根目录中的 /middleware.ts。然后,可以使用条件语句仅在与 about/* 路径匹配时运行中间件:

当我使用pages/_middleware.ts运行本地构建时,它完成时没有错误,就像今天在生产中所做的那样。如果我将其更改为本地的pages/middleware.ts,则会失败:

./pages/middleware.ts
2:1  Error: next/server should not be imported outside of pages/_middleware.js. See: https://nextjs.org/docs/messages/no-server-import-in-page  @next/next/no-server-import-in-page
Run Code Online (Sandbox Code Playgroud)

中间件文件:

import { getToken } from "next-auth/jwt";
import { NextRequest, NextResponse } from "next/server";

export async function middleware(req: NextRequest, res: NextResponse) {
  if (req.nextUrl.pathname === "/") {
    const session = await getToken({
      req,
      secret: process.env.JWT_SECRET,
      secureCookie: process.env.NODE_ENV === "production",
    });
    // You could also check for any property on the session object,
    // like role === "admin" or name === "John Doe", etc.
    if (!session) {
      const url = req.nextUrl.clone();

      url.pathname = "/login";

      return NextResponse.redirect(url);
    }
    // If user is authenticated, continue.
  }
}
Run Code Online (Sandbox Code Playgroud)

mnu*_*zdm 14

有同样的问题。发现 Next 刚刚发布了v12.2.0,它通过一些重大更改使中间件 API 变得稳定。在此处查看迁移指南https://nextjs.org/docs/messages/middleware-upgrade-guide

我只需要将中间件文件从/pages/_middleware.js移动并重命名为/middleware.js

另外,我必须将功能迁移到新的 URLPattern(也在迁移指南中进行了解释)

  • @florjank也许在你的 package.json 中你指定了任何 min ("next": "^12.1.0",) 而不是任何 patch ("next": "~12.2.0",) ?和 vercel 自动安装 12.2.0? (2认同)