Middleware.ts: Route Protection, Redirects, Cookies & Geolocation0%
Authentication with NextAuth / Auth.js & JWT Session Management

Middleware.ts: Route Protection, Redirects, Cookies & Geolocation

Beginner12 min read•Updated: Jul 11, 2026
Study MaterialsCheatsheet

Middleware.ts: Route Protection, Redirects, Cookies & Geolocation

Next.js Middleware enables running code on the edge before a request is completed. Located at the root of the project as middleware.ts, it allows intercepting incoming HTTP traffic to perform route authentication protection, URL redirects/rewrites, header manipulation, and geolocation routing.


1. Middleware Execution Model

Middleware runs on the lightweight Vercel Edge Runtime before cached content or route handlers execute:

Visual Architecture & Process Flow

How data and code flow step-by-step

Flowchart
Step 1
Client Request -
Step 2
[ Middleware.ts ] -
Step 3
(Redirect? Rewrite? Set Cookie?) -
Step 4
Target Page / Route

2. Basic Middleware and Route Matching

Create middleware.ts in your project root (or inside src/):

TypeScript
// 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;
const { pathname } = request.nextUrl;
 
// 1. Protect all /admin routes
if (pathname.startsWith('/admin')) {
if (!token) {
// Redirect unauthenticated user to login page with return URL
const loginUrl = new URL('/login', request.url);
loginUrl.searchParams.set('callbackUrl', pathname);
return NextResponse.redirect(loginUrl);
}
}
 
// 2. Add custom response header for tracking
const response = NextResponse.next();
response.headers.set('x-msk-trace-id', crypto.randomUUID());
 
return response;
}
 
// MATCHING CONFIGURATION: Specify exactly which paths trigger middleware
export const config = {
matcher: [
/*
* Match all request paths except for:
* - _next/static (static files)
* - _next/image (image optimization files)
* - favicon.ico, images, robots.txt
*/
'/((?!_next/static|_next/image|favicon.ico|images|robots.txt).*)',
],
};

3. URL Rewrites vs Redirects

  • Redirect (NextResponse.redirect(url)): Returns an HTTP 307/308 status code, updating the user's browser address bar to the new URL.
  • Rewrite (NextResponse.rewrite(url)): Serves content from a different destination URL while preserving the original URL in the user's browser address bar (useful for multi-tenant subdomains or A/B testing).

Interactive Quiz

Multiple Choice Questions

Question 1
Where must the middleware.ts file be located in a Next.js application?
Question 2
What is the fundamental difference between NextResponse.redirect() and NextResponse.rewrite()?
Question 3
Why is defining a matcher array in export const config recommended for Middleware?
Question 4
How can you inspect cookies sent by the client inside middleware.ts?
Question 5
On which runtime environment does Next.js Middleware execute by default?

Next Lesson

Authentication with NextAuth / Auth.js & JWT Session Management

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

PrevNext