How to use Middleware in Next.js 14: A Comprehensive Guide
In Next.js 14, the middleware.ts
file is a powerful tool for defining middleware, which acts as an interception mechanism during the request handling process. Middleware can execute logic before a request reaches a page or API route, making it ideal for tasks such as authentication, redirection, and request or response modifications.
Route Protection
Implementing route protection in middleware.ts
involves user authentication and IP blacklisting. By examining request details, you can determine whether access to specific routes should be granted. Here’s how to achieve these functionalities:
- User Authentication: Verify the user’s identity by checking authentication tokens or session cookies in the request.
- IP Blacklisting: Block access from blacklisted IP addresses by inspecting the request’s IP address.
Example Code:
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
// A simple IP blacklist
const ipBlacklist = new Set(['192.168.1.100', '203.0.113.1']);
// Function to check if the user is authenticated
function isAuthenticated(req: NextRequest): boolean {
const token = req.cookies.get('authToken');
// Implement your authentication logic here, such as verifying…