Middleware

Intercepting requests at the network edge.

Next.js4 min readConcept 59 of 66

The Traffic Cop

Middleware is a special file (middleware.ts) that sits between the user and your application.

Every time a user makes a request to a route, the Middleware function executes first. It can inspect the request (like checking cookies or geolocation), and decide whether to let the request through, redirect it, rewrite it, or block it entirely.

Global Protection

Imagine you have a /dashboard with 20 sub-pages. You could write an authentication check inside every single page component.

However, this is repetitive, and worse, the user's request still has to hit your main server just to be rejected.

Middleware runs at the 'Edge' (servers geographically closest to the user). It can instantly reject unauthenticated users and redirect them to /login before your main server is even contacted, saving resources and speeding up response times.

Implementation

typescript

// middleware.ts (Root level, not in /app)

import { NextResponse } from 'next/server';

import type { NextRequest } from 'next/server';

export function middleware(request: NextRequest) {

const session = request.cookies.get('session');

if (!session) {

return NextResponse.redirect(new URL('/login', request.url));

}

return NextResponse.next();

}

// Only run on specific paths

export const config = {

matcher: ['/dashboard/:path*'],

};

The Edge Network Cop

Send requests to the secure dashboard and watch the Edge Middleware intercept and redirect unauthenticated traffic.

Auth State:
GET /dashboard
ClientBrowser
EDGE NETWORK
middleware.ts
Origin Serverpage.tsx (DB Query)
> Waiting for request...

Check yourself

Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.

  1. 1Why will importing a library like `bcrypt` into `middleware.ts` cause an error?

Remember this

  • Middleware intercepts requests *before* they reach your route handlers or pages.
  • It is perfect for authentication redirects, A/B testing, and localization.
  • You use a matcher array to limit which routes the middleware runs on.
  • It runs on the Edge Runtime. Do not import heavy Node.js libraries.

Done with this concept?

Mark it complete to track your progress. No login needed.