简体   繁体   English

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

[英]NextJS Vercel deployment error Nested Middleware is not allowed, found: pages/_middleware

All of a sudden my middleware stopped working in deployment.突然间,我的中间件在部署中停止工作。 The error is:错误是:

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

Vercel statement is: For example, a Middleware at pages/about/_middleware.ts can move the logic to /middleware.ts in the root of your repository. Vercel 声明是:例如,pages/about/_middleware.ts 中的中间件可以将逻辑移动到存储库根目录下的 /middleware.ts。 Then, a conditional statement can be used to only run the Middleware when it matches the about/* path:然后,可以使用条件语句仅在匹配 about/* 路径时运行中间件:

When I run my local build with pages/_middleware.ts it finishes without errors like it did up to today on production.当我使用 pages/_middleware.ts 运行我的本地构建时,它完成时没有像今天在生产中那样出现错误。 If I change it to pages/middleware.ts localy it fails with:如果我将其更改为 pages/middleware.ts localy,则会失败:

./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

Middleware file:中间件文件:

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.
  }
}

Had the same issue.有同样的问题。 Found that Next just released v12.2.0 which turns the middleware API stable with some breaking changes.发现 Next 刚刚发布了v12.2.0 ,它通过一些重大更改使中间件 API 变得稳定。 Check the migration guide here https://nextjs.org/docs/messages/middleware-upgrade-guide在此处查看迁移指南https://nextjs.org/docs/messages/middleware-upgrade-guide

I just only had to move and rename my Middleware file from /pages/_middleware.js to /middleware.js我只需要将我的中间件文件从/pages/_middleware.js移动并重命名为/middleware.js

Also, I had to migrate the functionality to the new URLPattern (explained also in the migration guide)此外,我必须将功能迁移到新的 URLPattern(在迁移指南中也有说明)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM