Next.js Middleware is a feature that enables intercepting requests and running logic prior to a request finishing. This proves useful for authentication, role-based access control, and security enhancements.
Middleware executes before a request is finished, so you can change the response, redirect users, or deny access based on conditions.
To use middleware, create a middleware.ts file inside the root of your Next.js project:
// middleware.ts
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
export function middleware(req: NextRequest) {
const token = req.cookies.get("auth-token");
// Redirect to login if trying to access dashboard without token
if (!token && req.nextUrl.pathname.startsWith("/dashboard")) {
return NextResponse.redirect(new URL("/login", req.url));
}
return NextResponse.next();
}
export const config = {
matcher: ["/dashboard/:path*"] // Protect all dashboard routes
};
You can restrict access based on user roles (e.g., admin-only pages).
export function middleware(req: NextRequest) {
const token = req.cookies.get("auth-token");
const userRole = req.cookies.get("role");
// Redirect to login if no token
if (!token) {
return NextResponse.redirect(new URL("/login", req.url));
}
// Block non-admins from admin routes
if (req.nextUrl.pathname.startsWith("/admin") && userRole !== "admin") {
return NextResponse.redirect(new URL("/unauthorized", req.url));
}
return NextResponse.next();
}
export const config = {
matcher: ["/admin/:path*", "/dashboard/:path*"]
};
You can block users based on IP addresses or rate limit them.
const BLOCKED_IPS = ["192.168.1.1", "205.0.113.0"];
export function middleware(req: NextRequest) {
const ip = req.ip || req.headers.get("x-forwarded-for");
if (BLOCKED_IPS.includes(ip || "")) {
return new NextResponse("Access Denied", { status: 403 });
}
return NextResponse.next();
}
export const config = { matcher: ["/:path*"] }; // Applies to all routes
Redirect users to HTTPS if they try accessing via HTTP.
export function middleware(req: NextRequest) {
if (req.nextUrl.protocol !== "https") {
return NextResponse.redirect(
new URL(`https://${req.nextUrl.host}${req.nextUrl.pathname}`)
);
}
return NextResponse.next();
}
Next.js Middleware is a game-changer for authentication and security. It lets you:
Ready to transform your business with our technology solutions? Contact Us today to Leverage Our ReactJS Expertise.