The Standard Stack — cors, helmet, morgan, compression
Third-Party Middleware
The handful of middleware packages most production Express apps add on day one.
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.
cookie-parser
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:
helmet— security headers should be on every responsecors— needs to set headers before any responsesmorgan— logs everything that flows pastcompression— apply to all responsescookieParser— before anything that reads cookiesexpress.json/express.urlencoded— before routes that read body- Authentication, custom middleware
- Routes
- 404 catch-all
- 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.