KoderSolutionKoderSolution LogoKoderSolution Logo
HomeArticlesTutorialsToolsRun CodeForumAI Lab
▲

Next.js

Topic Hub & Articles

Next.js Intro

10 min

Next.js Installation

10 min

Next.js Routing

10 min

Next.js Pages

10 min

Next.js App Router

10 min

Recap Quiz

Gated

Milestone Assessment

Next.js Layouts

10 min

Next.js Linking and Navigating

10 min

Next.js Loading UI and Streaming

10 min

Next.js Error Handling

10 min

Next.js Data Fetching

10 min

Recap Quiz

Gated

Milestone Assessment

Next.js Server Actions

10 min

Next.js Rendering

10 min

Next.js CSS Modules

10 min

Next.js Image Optimization

10 min

Next.js Font Optimization

10 min

Recap Quiz

Gated

Milestone Assessment

Next.js Script Optimization

10 min

Next.js Static File Serving

10 min

Next.js Metadata

10 min

Next.js API Routes

10 min

Next.js Middleware

10 min

Recap Quiz

Gated

Milestone Assessment

Next.js Authentication

10 min

Next.js Deployment

10 min

Next.js Internationalization

10 min

Next.js Security

10 min

Next.js Performance

10 min

Recap Quiz

Gated

Milestone Assessment

Progress
0%

0 / 25 Lessons

KoderSolutionKoderSolution LogoKoderSolution Logo

The world’s most advanced technical ecosystem for modern software engineers. Learn, build, and grow with next-generation developer tools and resources.

Facebook PageX (Twitter) ProfileYouTube ChannelContact Support

Engineering Newsletter

Subscribe for weekly software engineering tutorials, architecture guides, and developer tool updates.

Platforms

  • Technical Articles
  • Interactive Tutorials
  • AI Coding Lab
  • Developer Forum
  • Developer Tools

Pages

  • About Us
  • Contact Us
  • Privacy Policy
  • Terms of Service
  • Refund Policy
  • Disclaimer
  • Advertisement

Popular Topics

  • PHP
  • Laravel
  • Python
  • React.Js
  • MySQL
© 2026 KoderSolutionAll Rights Reserved
Developed Bymaksudur.dev
Next.jsNext.js Tutorial
Lesson

Next.js Middleware

10 min reading
Free Course

Next.js Middleware: Request Interception at the Edge

Next.js middleware runs before a matched route completes, letting you redirect requests, rewrite URLs, or modify headers. You define it in a single middleware.ts file at the root of your project (or inside src/ if used).

Because middleware runs before pages and API handlers execute, it is ideal for fast session cookie checks, localization redirects, and response headers.

flowchart TD
    A["Incoming Request"] --> B["middleware.ts"]
    B --> C{"Session Cookie Present?"}
    C -- "No" --> D["Redirect to /login"]
    C -- "Yes" --> E["NextResponse.next()"]
    E --> F["Render Page or Route Handler"]

Writing a Route Guard in middleware.ts

Export a middleware function and a config.matcher array so the middleware runs only on targeted paths.

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

export function middleware(request: NextRequest) {
  const token = request.cookies.get('session_token')?.value;
  const { pathname } = request.nextUrl;

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

  if (pathname === '/login' && token) {
    return NextResponse.redirect(new URL('/dashboard', request.url));
  }

  return NextResponse.next();
}

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

Adding Custom Request and Response Headers

Attach headers on NextResponse.next() to pass trace IDs downstream or apply security headers across matching routes.

// middleware.ts header snippet
const requestHeaders = new Headers(request.headers);
requestHeaders.set('x-request-id', crypto.randomUUID());

const response = NextResponse.next({
  request: { headers: requestHeaders },
});
response.headers.set('x-frame-options', 'DENY');
return response;

Scoping Execution with matcher

Always specify a matcher filter. Without one, middleware intercepts every image, font, and _next/static chunk request, adding unnecessary latency.

Common Mistakes

  • Running heavy database queries inside middleware: Middleware should stay fast and lightweight; verify signed JWT cookies or edge tokens instead of querying SQL databases directly.
  • Trusting middleware alone for authorization: Always re-verify permissions inside Server Components and Server Actions as defense in depth.
  • Creating infinite redirect loops: Check pathname carefully before redirecting so /login does not redirect back to /login.

Frequently Asked Questions

Where should middleware.ts be placed?

Place middleware.ts at the project root next to package.json, or inside src/middleware.ts if your app/ folder lives inside src/.

Can I have multiple middleware.ts files inside nested folders?

No, Next.js allows only one root middleware.ts file; use pathname.startsWith(...) checks inside it to route logic by path.

What is the difference between NextResponse.redirect() and NextResponse.rewrite()?

redirect() sends the user to a new URL visible in the browser bar, while rewrite() keeps the original URL and serves content from another path.

Save Your Progress

Unlock Your
Full Potential.

Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.

Quick Access With

Enterprise-Grade Security Protocol
Lesson Recap Quiz Available

Test Your Knowledge

You've completed this section! Take a quick 5-question quiz to check your understanding.

Related Developer Tools & Topic Hub

Next.js Topic Hub
JSON Formatter
Validate and format JSON payloads
HTML Formatter
Format HTML markup
CSS Formatter
Clean and format stylesheets
All Next.js Articles
Deep-dive guides, tips & discussions
PreviousNext.js API Routes
Continue JourneyTake Recap Quiz

Stuck on this lesson?

Join our community of senior developers.

Ask in Forum