Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

1.7K
Views
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.
  }
}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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)

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!