Matching Paths
The middleware file will be invoked for every route in your project, If you want to apply to any specific route then you have to mention a route matcher inside middleware.js file
route matcher (specific path):
...Main Middleware Function....
......
export const config = {
matcher: '/profile/:path*',
}
route matcher (multiple path):
...Main Middleware Function....
......
export const config = {
matcher: [ '/profile/:path*', '/about/:path*' ]
}
Syntax:
import { NextResponse } from 'next/server'
export function middleware(request) {
return NextResponse.redirect(new URL('/home', request.url))
}
//Matching Path
export const config = {
matcher: '/about/:path*',
}
Middlewares in Next.js
NextJS is a React framework that is used to build full-stack web applications. It is used both for front-end as well as back-end. It comes with a powerful set of features to simplify the development of React applications. One of its features is Middleware. In this article, we will learn about the middleware in Next.js with examples.
Table of Content
- Middleware in Next.js
- Benefits of Middleware
- Convention
- Matching Paths
- NextResponse
- Using Cookies
- Setting Headers
- CORS
- Producing Response
Contact Us