Middleware in Next.js allows you to run code before a request is completed, enabling you to modify requests and responses. This feature is particularly useful for tasks such as authentication, logging, rate limiting, and more. In this tutorial, we'll explore how to create and use middleware in your Next.js applications.
Middleware functions are executed sequentially, allowing you to chain multiple middlewares together. Each middleware can decide whether to proceed to the next middleware or terminate the request-response cycle. This makes middleware a powerful tool for handling common tasks across your application.
To use middleware in Next.js, you need to create a middleware.js file at the root of your project. This file will export a default function that handles incoming requests.
First, create a middleware.js file in the root directory of your Next.js project:
// middleware.js
export default function middleware(req, ev) {
// Your middleware logic here
}
The middleware function receives two arguments: req (the request object) and ev (an event object). You can use these objects to inspect and modify the request.
Here's a simple example of a middleware that logs the incoming request URL:
// middleware.js
export default function middleware(req, ev) {
console.log(`Request received for: ${req.url}`);
return NextResponse.next();
}
NextResponse to Control FlowThe NextResponse object is used to control the flow of requests. You can use it to modify the response or terminate the request.
Here's an example of a middleware that redirects users to a different page if they are not authenticated:
// middleware.js
import { NextResponse } from 'next/server';
export default function middleware(req) {
const isAuthenticated = checkAuthentication(req);
if (!isAuthenticated) {
return NextResponse.redirect(new URL('/login', req.url));
}
return NextResponse.next();
}
function checkAuthentication(req) {
// Implement your authentication logic here
return false;
}
You can chain multiple middlewares by exporting an array of middleware functions in the middleware.js file:
// middleware.js
import { NextResponse } from 'next/server';
const logMiddleware = (req) => {
console.log(`Request received for: ${req.url}`);
return NextResponse.next();
};
const authMiddleware = (req) => {
const isAuthenticated = checkAuthentication(req);
if (!isAuthenticated) {
return NextResponse.redirect(new URL('/login', req.url));
}
return NextResponse.next();
};
export default [logMiddleware, authMiddleware];
You can apply middleware conditionally based on the request path or other criteria:
// middleware.js
import { NextResponse } from 'next/server';
export default function middleware(req) {
if (req.url.startsWith('/admin')) {
const isAdmin = checkAdmin(req);
if (!isAdmin) {
return NextResponse.redirect(new URL('/', req.url));
}
}
return NextResponse.next();
}
function checkAdmin(req) {
// Implement your admin check logic here
return false;
}
Middleware in Next.js provides a powerful way to handle common tasks across your application. By following the steps outlined in this tutorial, you can create robust middleware functions to enhance the functionality and security of your Next.js applications. Remember to keep your middleware lightweight and secure, and always test thoroughly to ensure it works as expected.