Convention
In Next.js, you can implement middleware by creating middleware.js (or .ts) file in a project root directory(you have to create a middleware.js file inside src folder.).
You can only create a one middleware.js (or .ts) file per project, but you can still divide it’s logic in a different modules.
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('/home', request.url))
}
// See "Matching Paths" below to learn more
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