Home  >  Q&A  >  body text

Why does Next.js middleware execute multiple times?

I created a new Next.js using npx create-next-app@latest --typescript. After installation (version 13.3.4), without changing any files, I added a new middleware.ts## inside the src folder # file, and I only placed this code:

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

export function middleware(request: NextRequest) {
  console.log("request", request.nextUrl.pathname);
  return NextResponse.next();
}

// EDIT: By putting this block will get expected result.
export const config = {
  matcher: [
    /*
     * Match all request paths except for the ones starting with:
     * - api (API routes)
     * - _next/static (static files)
     * - _next/image (image optimization files)
     * - favicon.ico (favicon file)
     */
    '/((?!api|_next/static|_next/image|favicon.ico).*)',
  ],
};

Console log was hit multiple times. I think it was once? Do I need to do any configuration for this new Next.js installation?

NOTE: I will be performing some cookie logic in the middleware for authentication. screenshot:

P粉448346289P粉448346289261 days ago387

reply all(1)I'll reply

  • P粉950128819

    P粉9501288192024-01-05 09:12:41

    This is normal because middleware runs by default on every request, including requests for resources such as JavaScript, CSS, and image files. As you can read in doc:

    If you log request.nextUrl.pathname you will see the different paths it runs on. To have it execute only for certain paths, you need to use a conditional statement or a matcher object like this:

    import type { NextRequest } from "next/server";
    import { NextResponse } from "next/server";
    
    export function middleware(request: NextRequest) {
      console.log("request", JSON.stringify(request));
      return NextResponse.next();
    }
    
    // The above middleware would only run for the "/" path
    export const config = {
      matcher: '/',
    }

    reply
    0
  • Cancelreply