简体   繁体   中英

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. Then, a conditional statement can be used to only run the Middleware when it matches the about/* path:

When I run my local build with pages/_middleware.ts it finishes without errors like it did up to today on production. If I change it to pages/middleware.ts localy it fails with:

./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. Check the migration guide here 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

Also, I had to migrate the functionality to the new URLPattern (explained also in the migration guide)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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