NextJS: Run middleware for /pages only

Viewed 542

With the recent change regarding middleware https://nextjs.org/docs/messages/middleware-upgrade-guide.

Now the middleware also gets triggered by requests for /_next and /favicon.ico.

What is the best way to only trigger it for requests for /pages folder. There is the matcher but it would be cumbersome to type all of the pages in it.

I'm currently using middleware to check if cookies exist and redirect the user if the user accesses a page. E.g Redirect the user to /login if the user accesses / and the user is not logged in yet.

2 Answers

To avoid the middleware running when "/_next" or "/favicon.ico" routes are requested simply start your middleware function with:

const { pathname } = req.nextUrl

// Allow the requests if the following is true...
// 1) if the request is a system request /_next
// 2) if the request is to get the favicon.ico
if (pathname.startsWith('/_next') || pathname.startsWith('/favicon.ico')) {
    return NextResponse.next()
}

Not sure it's the cleanest way but it works fine for me. Don't hesitate to tell me if I can make this better.

Here is the snippet of middleware:

// middleware.ts
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'

// This function can be marked `async` if using `await` inside
export function middleware(request: NextRequest) {
  return NextResponse.redirect(new URL('/about-2', request.url))
}

// See "Matching Paths" below to learn more
export const config = {
  matcher: '/about/:path*',
}

If you want middleware to run on all paths:

export const config = {
  matcher: '/:path*',
}

Have you tried this.

Related