Next.js: Creating a Middleware for Advanced Request Handling.

What is Middleware in Next.js?
Middleware is a feature that lets you run logic before a request is completed. You can use it to:
Redirect users.
Protect routes (authentication).
Modify responses.
Handle custom headers or logging.
Example: Protecting Routes with Middleware
Imagine you have a dashboard that should only be accessible to authenticated users. Middleware makes it easy to check the authentication token and redirect unauthorized users.
Step 1: Create Middleware
Middleware files must be named middleware.ts
and placed in the root of your app.
// middleware.ts
import { NextRequest, NextResponse } from 'next/server';
export function middleware(request: NextRequest) {
// Check for a token in cookies (example: `authToken`)
const token = request.cookies.get('authToken')?.value;
// If no token, redirect to login
if (!token) {
return NextResponse.redirect(new URL('/login', request.url));
}
// Allow request to continue
return NextResponse.next();
}
// Specify routes where middleware applies
export const config = {
matcher: ['/dashboard/:path*'], // Apply middleware to all /dashboard routes
};
Step 2: Test Protected Routes
Now, if a user accesses /dashboard or any subpage like /dashboard/settings, they will be redirected to /login unless they have a valid authToken cookie.
Advanced: Custom Headers and Logging
You can also modify the request or response directly in middleware. For example, logging user details or setting custom headers:
export function middleware(request: NextRequest) {
// Log the user's IP
console.log('User IP:', request.ip);
// Add a custom header to the response
const response = NextResponse.next();
response.headers.set('X-Custom-Header', 'Middleware Works!');
return response;
}
Step 3: Debug Middleware
Run your app locally (npm run dev
or yarn dev
) and try accessing the protected routes. If you’re using cookies, you can simulate adding an authToken
in your browser’s dev tools.
Use Cases for Middleware
Authentication and Authorization: Redirect unauthorized users or check user roles.
Localization: Dynamically redirect users based on their location or language preference.
Rate Limiting: Throttle requests to APIs or routes.
Logging and Monitoring: Log request details (e.g., IP address or user agent).
Dynamic Content Delivery: Serve different versions of content based on request headers or cookies.
Why This Is Useful
Performance: Middleware runs before rendering, reducing client-side overhead.
Scalability: Centralizes logic for route handling and request validation.
Security: Helps enforce route protection and authentication without cluttering your page code.
Mastering middleware opens up a whole new layer of possibilities in Next.js for building secure, dynamic, and efficient apps!
Subscribe to my newsletter
Read articles from Reme Le Hane directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by