What is Middleware? Web Development Basics

Share

TL;DR

Middleware is code that runs between receiving a request and executing your route handler. It's used for authentication (check if user is logged in), authorization (check if user can access this resource), logging, rate limiting, and adding headers. Middleware lets you apply logic across multiple routes without repeating code.

The Simple Explanation

A request comes in. Before your route code runs, middleware can check things, modify the request, or reject it entirely. It's like security checkpoints. Each middleware either lets the request through or stops it. This keeps your route code focused on business logic while middleware handles cross-cutting concerns.

Common Middleware Uses

  • Authentication: Check if user is logged in
  • Authorization: Check if user has permission
  • Rate limiting: Limit requests per time period
  • CORS: Handle cross-origin requests
  • Logging: Record request details
  • Body parsing: Parse JSON, form data
  • Security headers: Add CSP, HSTS, etc.

Express Middleware

Express authentication middleware

function authMiddleware(req, res, next) { const token = req.headers.authorization?.split(' ')1;

if (!token) { return res.status(401).json({ error: 'No token' }); }

try { req.user = verifyToken(token); next(); // Continue to route handler } catch { res.status(401).json({ error: 'Invalid token' }); } }

// Apply to all /api routes app.use('/api', authMiddleware);

Next.js Middleware

middleware.ts

import { NextResponse } from 'next/server';

export function middleware(request) { const token = request.cookies.get('session');

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

return NextResponse.next(); }

export const config = { matcher: '/dashboard/:path*' };

Middleware Order Matters

Typical order for security:

  1. Rate limiting (reject abuse early)
  2. CORS (handle cross-origin)
  3. Body parsing (parse request body)
  4. Authentication (identify user)
  5. Authorization (check permissions)
  6. Your route handlers

What is middleware used for in security?

Security middleware commonly handles authentication (checking tokens/sessions), authorization (verifying permissions), rate limiting (preventing abuse), CORS (controlling cross-origin access), and adding security headers. It runs before your route handlers, protecting all routes automatically.

What is the order of middleware execution?

Middleware typically runs in the order you define it. Put security middleware early (authentication, rate limiting), then logging, then route-specific middleware. The request passes through each middleware in order. Response goes back through in reverse for some frameworks.

How is middleware different in Next.js vs Express?

Express middleware is a function that receives (req, res, next) and calls next() to continue. Next.js middleware runs at the edge before rendering, uses Web APIs, and returns Response objects or NextResponse for redirects and rewrites. The concept is similar but the implementation differs.

Check Your Middleware

Scan your app for security middleware issues.

Start Free Scan
Security Glossary

What is Middleware? Web Development Basics