ReactJS

    Next.js Middleware: How to Use It for Authentication & Security


    Introduction

    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.

    1. What is Middleware in Next.js?

    Middleware executes before a request is finished, so you can change the response, redirect users, or deny access based on conditions.

    2. Setting Up Middleware in Next.js

    To use middleware, create a middleware.ts file inside the root of your Next.js project:

    // middleware.tsimport { 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 tokenif (!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};

    3. Middleware for Role-Based Access Control

    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 tokenif (!token) {return NextResponse.redirect(new URL("/login", req.url));}// Block non-admins from admin routesif (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*"]};

    Blocking Suspicious Requests

    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

    Enforcing HTTPS

    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();}

    Conclusion

    Next.js Middleware is a game-changer for authentication and security. It lets you:

    • Protect private routes
    • Restrict access based on roles
    • Enhance security by blocking threats
    • Improve performance with Edge execution

    Ready to transform your business with our technology solutions? Contact Us today to Leverage Our ReactJS Expertise. 

    Share

    facebook
    LinkedIn
    Twitter
    Mail
    ReactJS

    Related Center Of Excellence