Middleware is a piece of code that executes after the server receives a request, but before it is processed and the response is sent. It is something that happens in the middle, hence the name middleware.
Middlewares are commonly used for user authentication, logging, traffic control, bot detection, and more.
In this lesson, we are going to explain how to create middlewares in Next.js applications, what you can do inside a middleware, and how to configure the middleware so that it will only be activated for selected routes, and how to execute different middlewares for different routes.
Creating a middleware
In Next.js, middlewares can be created by adding a middleware.js
file under the src
directory.
1src
2├── app
3│ ├── favicon.ico
4│ ├── globals.css
5│ ├── layout.jsx
6│ └── page.jsx
7├── libs
8└── middleware.js <===== Middleware
This file should export two things, a middleware
function and a configuration object (config
).
1export function middleware(request) {
2 console.log(request.nextUrl.pathname);
3}
4
5export const config = {
6 matcher: "/:path*",
7};
This example middleware will be executed for every route, and when a route is visited, this middleware will log the requested path.