Why does Next.js middleware execute multiple times?
P粉448346289
P粉448346289 2024-01-04 12:43:02
0
1
484

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粉448346289
P粉448346289

reply all(1)
P粉950128819

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: '/',
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template