How to use matcher in Next JS middleware

Viewed 1285

I am trying to use matcher in my Next js middleware but documentation doesnt say much on how to implement the functionality.

All it shows is this without explaining which file it goes in or how to use the config in the middleware file:

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

Does anyone have a working example of how to set up the matcher for a middleware file in Next js?

Thank you.

2 Answers

I was faced the same issue when learning this framework. I use nexjs v12.2.0. to make middleware is running properly you need to put the middleware.ts or middleware.js in source directory and define the config matcher in it.

In Next.js 12.2 place a single file named middleware.ts within the root directory of your project (next to package.json):

import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'

export function middleware (request: NextRequest) {
  return NextResponse.next()
}

export const config = {
  matcher: ['/api/hello/:helloId'],
}

1.Matching with config:

You have to export an object (Named export) named config from your middleware file :

middleware.js || middleware.ts

//middleware.js

export function middleware(request: NextRequest) {
  return NextResponse.redirect(new URL('/about-2', request.url))
}

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

2.File based Matching:

|-- pages/
│   ├── auth/
│   │   ├── index.js
│   │   └── middlware.js(1)
│   |
│   |── index.js
|   |── middleware.js(2)
|__________________________


//middleware.js(1) will only run on /auth pages

//middleware.js(2) will run on all routes)

Related