MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
Middleware.ts: Route Protection, Redirects, Cookies & Geolocation0%
Study Materials
Next.js 15Progress 0%
1.1Next.js 15 Overview & App Router vs Pages Router Architecture1.2Core File Conventions: page.tsx, layout.tsx, template.tsx & not-found.tsx1.3Dynamic Routes ([id]), Catch-All Routes ([...slug]) & Route Groups ((group))1.4Streaming UI with loading.tsx and Suspense Boundaries
4.1API Route Handlers (route.ts): Building RESTful Microservices4.2Middleware.ts: Route Protection, Redirects, Cookies & Geolocation4.3Authentication with NextAuth / Auth.js & JWT Session Management4.4Metadata API: Dynamic SEO, OpenGraph Tags & Sitemap Generation4.5Production Optimization, Dockerization & Vercel Cloud Deployment
HomeTutorialsNext.js 15Middleware.ts: Route Protection, Redirects, Cookies & Geolocation
Authentication with NextAuth / Auth.js & JWT Session Management

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

Beginner12 min read•Updated: 2026-11-18•By Er. Sumit Kumar (MSK Institute)
Study MaterialsCheatsheet

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/):

1// middleware.ts
2import { NextResponse } from 'next/server';
3import type { NextRequest } from 'next/server';
4 
5export function middleware(request: NextRequest) {
6 const token = request.cookies.get('auth_token')?.value;
7 const { pathname } = request.nextUrl;
8 
9 // 1. Protect all /admin routes
10 if (pathname.startsWith('/admin')) {
11 if (!token) {
12 // Redirect unauthenticated user to login page with return URL
13 const loginUrl = new URL('/login', request.url);
14 loginUrl.searchParams.set('callbackUrl', pathname);
15 return NextResponse.redirect(loginUrl);
16 }
17 }
18 
19 // 2. Add custom response header for tracking
20 const response = NextResponse.next();
21 response.headers.set('x-msk-trace-id', crypto.randomUUID());
22 
23 return response;
24}
25 
26// MATCHING CONFIGURATION: Specify exactly which paths trigger middleware
27export const config = {
28 matcher: [
29 /*
30 * Match all request paths except for:
31 * - _next/static (static files)
32 * - _next/image (image optimization files)
33 * - favicon.ico, images, robots.txt
34 */
35 '/((?!_next/static|_next/image|favicon.ico|images|robots.txt).*)',
36 ],
37};

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• Knowledge Check

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.

Related Lessons

Previous LessonNext Lesson
API Route Handlers (route.ts): Building RESTful MicroservicesAuthentication with NextAuth / Auth.js & JWT Session Management

Practice Quiz

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

Mentor-Led Practical Training

Master Next.js 15 with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext