Skip to main content
Back to Blog
Next.jsMiddlewareAuthentication

Next.js Middleware Guide: Authentication, Redirects, and Edge Functions

7 min read

Master Next.js middleware — protecting routes, handling authentication redirects, A/B testing, geolocation logic, and writing efficient edge functions for your Next.js app.

Next.js middleware runs at the edge before a request reaches your pages or API routes, making it the ideal place for authentication, redirects, A/B testing, geolocation logic, and request transformation. Muhammad Sufyan of Sufyan Frontend shares this complete 2026 guide to writing effective, efficient Next.js middleware.

Creating Middleware in Next.js

Middleware lives in a single middleware.ts file at the root of your project. The exported function receives a NextRequest and returns a NextResponse. The matcher config exported from the file controls which routes the middleware runs on — scoping it correctly is critical for performance, since unnecessary middleware execution adds latency.

// middleware.ts
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";

export function middleware(request: NextRequest) {
  const token = request.cookies.get("auth-token")?.value;

  if (!token && request.nextUrl.pathname.startsWith("/dashboard")) {
    return NextResponse.redirect(new URL("/login", request.url));
  }

  return NextResponse.next();
}

export const config = {
  matcher: ["/dashboard/:path*", "/admin/:path*"],
};

Authentication and Protected Routes

Authentication redirects are the most common use case for Next.js middleware. By checking for a valid session token or cookie at the middleware layer, you can redirect unauthenticated users to a login page before they ever reach the protected page component. This is more efficient than checking authentication inside individual pages and provides a consistent protection layer across your entire app.

Geolocation and Internationalisation

  • Read request.geo for country, region, and city of the incoming request
  • Redirect users to localised routes based on their detected country
  • Set custom headers to pass geolocation data to downstream page components
  • Use the NextResponse.rewrite() method to serve different content at the same URL

Conclusion

Next.js middleware is a powerful tool that, used correctly, can dramatically simplify authentication flows, enable personalisation, and improve the performance of route-level logic in your application. Muhammad Sufyan applies middleware for authentication protection on production projects. For more Next.js guides from Sufyan Frontend Developer based in Lahore, Pakistan, visit https://sufyan-frontend.vercel.app.