7

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.
  }
}
Floky99
  • 562
  • 2
  • 8
  • 17

1 Answers1

14

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)

mnunezdm
  • 255
  • 2
  • 7
  • Ye this worked, but not sure why it happened all of a sudden... It was working up to this day so that's why it was strange for me :D – Floky99 Jun 30 '22 at 07:27
  • 2
    @florjank Maybe in your package.json you are specifying any min ("next": "^12.1.0",) instead of any patch ("next": "~12.2.0",)? and vercel automatically installed 12.2.0? – mnunezdm Jul 01 '22 at 10:12