Search code examples
reactjsnext.jsmiddleware

Next.js middleware.ts file executes twice (I think app renders twice as well)


We're using the middleware and we just found out it executes things twice, even the application itself. I know that middleware is being used in resources as well, so I put a matcher and removed the "favicon" because I heard it can cause this bug.

When we use the middleware, and console.log in "_app.tsx", we see that it renders twice. Also I put a counter in middleware.ts and every page I enter I see that it increases the counter by two.

My middleware.ts page looks like:

import { NextRequest, NextResponse } from "next/server";

let counter = 0;
export function middleware(request: NextRequest) {
  const response = NextResponse.next();
  counter++;

  console.log("middleware #", counter);
  return response;
}

Github repo to reproduce: https://github.com/ornakash/reproduction-template-nextjs

I only see it twice in the server's terminal (in browser I see only one console.log). Do you have any idea why it happens?


Solution

  • I came across the same issue and found that it's not react strict mode. I think this would be illogical anyway, because strict mode is about rendering and request handling should not be affected by multiple renders. On top, the duplicate requests occurred in with strict mode off as well.

    After logging some requests, I found different request methods being present: GET, HEAD, OPTIONS

    So after filtering for http GET I was fine:

    export function middleware(request: NextRequest) {
      if (request.method !== 'GET') {
        return;
      }
      console.log('middleware:', request.method, request.nextUrl.pathname);
    }