Third-Party Middleware

The Standard Stack — cors, helmet, morgan, compression

Third-Party Middleware

The handful of middleware packages most production Express apps add on day one.

4 min read Level 1/5 #express#middleware#ecosystem
What you'll learn
  • Install the production starter pack
  • Know what each one does
  • Mount in the right order

A handful of packages are in nearly every production Express app. Here’s the starter pack.

Install

npm install cors helmet morgan compression cookie-parser

A Production Setup

import express from "express";
import helmet from "helmet";
import cors from "cors";
import morgan from "morgan";
import compression from "compression";
import cookieParser from "cookie-parser";

const app = express();

app.use(helmet());                                         // security headers
app.use(cors({ origin: "https://app.example.com" }));      // CORS
app.use(morgan("combined"));                                // logs
app.use(compression());                                     // gzip / brotli
app.use(cookieParser());                                    // parse cookies
app.use(express.json({ limit: "100kb" }));                  // JSON body
app.use(express.urlencoded({ extended: true }));            // form body

// ... routes

What Each One Does

helmet

Sets ~12 security headers: CSP, HSTS, X-Content-Type-Options, Referrer-Policy, etc. One line, big security win.

cors

CORS headers, so browsers from other origins can call your API.

app.use(cors({
  origin: ["https://app.example.com"],
  credentials: true,
}));

morgan

Request logger. Outputs Apache-style or custom format:

app.use(morgan("combined"));   // Apache combined log format
app.use(morgan("dev"));         // colored, concise

For production with structured logging, prefer pino-http (covered in the production chapter).

compression

Compresses responses (gzip / brotli). One line, ~70% smaller responses for text content.

Parses the Cookie header into req.cookies. Supports signed cookies via a secret. Express doesn’t parse cookies by default.

Order Matters

A reasonable order:

  1. helmet — security headers should be on every response
  2. cors — needs to set headers before any responses
  3. morgan — logs everything that flows past
  4. compression — apply to all responses
  5. cookieParser — before anything that reads cookies
  6. express.json / express.urlencoded — before routes that read body
  7. Authentication, custom middleware
  8. Routes
  9. 404 catch-all
  10. Error handler

The Almost-Standard

npm install express-rate-limit

express-rate-limit — throttle abusive clients. Often the 6th package after the starter pack. Covered in the security chapter.

Error Middleware →