# Middleware

> Intercepting requests at the network edge.

Subject: Next.js | Lesson 58 of 65 | 4 min read
Interactive lesson: https://codewithanimation.in/nextjs/middleware
Previous: [Image Metadata Files](https://codewithanimation.in/nextjs/image-metadata-files.md) | Next: [Middleware Capabilities](https://codewithanimation.in/nextjs/middleware-capabilities.md)

## 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*'],
};
```

## Common mistake: The Edge Runtime Trap

Because Middleware is designed to execute globally in milliseconds across the CDN edge, it does **NOT** run on a standard Node.js server.

It runs on the strict 'Edge Runtime'. This means you cannot use standard Node.js APIs (like `fs` or `crypto`), and you cannot import heavy libraries like `bcrypt` or full database ORMs.

If you try to do heavy database queries inside Middleware, your app will crash. You must use lightweight Web APIs.

## Try it: The Edge Network Cop

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

The animation is on the lesson page and is not part of this text version: https://codewithanimation.in/nextjs/middleware

## Check yourself

### Question 1

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

- A. Because middleware can only handle routing, not authentication.
- B. Because `middleware.ts` runs on the client-side.
- C. Because middleware runs on the Edge Runtime, which does not support full Node.js APIs.
- D. Because Next.js automatically bans third-party libraries in the root folder.

Correct answer: C

To achieve sub-millisecond boot times globally, Edge functions omit the heavy Node.js environment. Libraries that rely on native Node modules or C++ bindings (like bcrypt) will fail.

- Why not A: Authentication routing is the primary use case for middleware.
- Why not B: It runs on the server, but on a specific, lightweight architecture.
- Why not D: Third-party libraries are allowed, provided they are compatible with the Edge Runtime.

## 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.
