title: NextJS Vercel deployment error Nested Middleware is not allowed, found: pages/_middleware
body: <p>All of a sudden my middleware stopped working in deployment. The error is:</p>
  <pre><code>&gt; Build error occurred
  NestedMiddlewareError: Nested Middleware is not allowed, found:
  pages/_middleware
  Please move your code to a single file at /middleware instead.
  </code></pre>
  <p>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:</p>
  <p>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:</p>
  <pre><code>./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
  </code></pre>
  <p>Middleware file:</p>
  <pre><code>import { getToken } from &quot;next-auth/jwt&quot;;
  import { NextRequest, NextResponse } from &quot;next/server&quot;;
  
  export async function middleware(req: NextRequest, res: NextResponse) {
    if (req.nextUrl.pathname === &quot;/&quot;) {
      const session = await getToken({
        req,
        secret: process.env.JWT_SECRET,
        secureCookie: process.env.NODE_ENV === &quot;production&quot;,
      });
      // You could also check for any property on the session object,
      // like role === &quot;admin&quot; or name === &quot;John Doe&quot;, etc.
      if (!session) {
        const url = req.nextUrl.clone();
  
        url.pathname = &quot;/login&quot;;
  
        return NextResponse.redirect(url);
      }
      // If user is authenticated, continue.
    }
  }
  </code></pre>