Skip to content
Tutorials Center
My learning

Topics

Lesson 89 of 133 ยท Frameworks and Ecosystem

Everyday Middleware - cors, helmet, morgan, compression and Body Parsers

Learn what the five middleware packages almost every Express app installs actually do, run hand-written equivalents of each, and see why their order in the chain matters.

Open almost any Express project and the top of app.js looks the same: a handful of app.use(...) lines for packages with short names. cors, helmet, morgan, compression and a body parser are so common that they feel like part of the framework. They are not. Each one is an ordinary middleware function that reads the request, maybe changes a header or a stream, and calls next().

Our editor cannot install npm packages, so the real packages are shown read-only. What you can run is a hand-written version of each one on a tiny framework core. That is the best way to learn them: once you have seen that cors() is about fifteen lines, the package stops being magic and its options stop being a mystery.

The five at a glance

Package Problem it solves What it touches
cors Browsers block cross-origin calls unless the server opts in Access-Control-* response headers, OPTIONS preflight
helmet Default headers are not security-friendly A group of security response headers
morgan You want one log line per request Hooks the response finish event
compression Text responses are big Pipes the body through gzip or brotli
express.json() / body-parser Request bodies arrive as raw bytes Fills req.body

In a real project the setup reads like this:

JavaScript
import express from 'express';
import cors from 'cors';
import helmet from 'helmet';
import morgan from 'morgan';
import compression from 'compression';

const app = express();

app.use(helmet());                                  // security headers first
app.use(cors({ origin: ['https://app.example.com'] }));
app.use(morgan('combined'));                        // log every request
app.use(compression());                             // compress what comes next
app.use(express.json({ limit: '100kb' }));          // parse JSON bodies
app.use(express.urlencoded({ extended: false }));   // parse HTML form bodies

app.use('/api', apiRouter);

Every line is a function call that returns a middleware. Let us build three of them.

CORS: asking permission across origins

A page served from https://app.example.com that calls https://api.example.com is making a cross-origin request. The browser lets the request go out, but it hides the response from your JavaScript unless the server says that origin is welcome. Your server does that with response headers. For requests that could change things (a PUT, or a POST with a JSON content type, or custom headers), the browser first sends a preflight: an OPTIONS request asking "would you accept this?". The server answers with 204 and the permitted methods and headers.

Important: CORS is enforced by browsers, not by your server. curl and other servers ignore it, so it is not an access control mechanism. It only tells browsers which web pages may read your API's responses. Authentication still has to happen separately.

Node.js A hand-written cors() and helmet() on a tiny framework

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Look at the "other origin" case. The server still answers 200 and even sends the data. What is missing is the Access-Control-Allow-Origin header, so a browser would refuse to hand the response to the page's script. The Vary: Origin header matters whenever the allowed value depends on the request: it tells caches not to serve a response made for one origin to another.

Never combine Access-Control-Allow-Origin: * with cookies or credentials. Browsers reject it, and echoing back any origin together with Access-Control-Allow-Credentials: true is a serious vulnerability, because any website could then call your API as the logged-in user. Keep an explicit allow-list.

helmet: security headers in one line

Out of the box, a Node response carries almost no defensive headers. helmet sets a bundle of them. The five in the example are the ones to know:

  • X-Content-Type-Options: nosniff stops browsers from guessing that a file is a script when you said it was something else.
  • X-Frame-Options (and the newer frame-ancestors directive of CSP) controls who may put your page in an <iframe>, which prevents clickjacking.
  • Strict-Transport-Security tells browsers to use HTTPS only for the site from now on.
  • Referrer-Policy limits how much of your URL is sent to other sites.
  • Content-Security-Policy lists where scripts, styles and images may load from. It is the strongest and also the one most likely to break pages, so test it. See Web Application Security for the reasoning.

The real helmet sets more headers, removes X-Powered-By, and lets you customize each directive with options. Treat it as a good starting point, not a finished security review.

morgan: one line per request

The request logger has to print the status code, which is not known when the request arrives. The trick, which you saw in Middleware Pattern, is to remember the start time, call next(), and print when the response emits finish. morgan adds format tokens (:method, :url, :status, :response-time) and a few ready-made formats: dev (coloured, short), combined (Apache style, for log files), tiny.

JavaScript
app.use(morgan('dev'));
TEXT
GET /api/books 200 4.213 ms - 118
POST /api/books 201 7.842 ms - 64
GET /api/books/99 404 1.120 ms - 27

For structured JSON logs in production, a logger such as pino with an HTTP plugin is usually a better fit; see Logging.

compression and body parsers

compression checks the request's Accept-Encoding header, picks gzip (or deflate), and pipes the response body through a compressor, adding Content-Encoding and Vary: Accept-Encoding. Skip it for tiny bodies and for already-compressed content such as images, and know that many deployments let the reverse proxy or CDN compress instead, which is cheaper for Node. The zlib lesson covers the compressors themselves.

Body parsers are the other half. A request body is a stream of bytes; express.json() reads it, checks Content-Type, enforces a size limit, parses it, and stores the result in req.body. The size limit is a security feature: without it, one client can make your server buffer gigabytes. express.urlencoded() does the same for HTML form posts. Neither handles file uploads; those need a multipart parser (see File Uploads and Multipart). The package name body-parser is the same code that Express has included since version 4.16, so you no longer need to install it.

Node.js Hand-written compression and a size-limited JSON parser

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The gzipped body is a fraction of the plain one because repeated keys compress extremely well. The three POSTs show the parser's three outcomes: success, 400 for a body that is not JSON, and 413 ("payload too large") as soon as the running total passes the limit, before the rest of the body has been read into memory.

Order matters

Middleware runs in the order you register it, and each of the five has a natural place:

  1. helmet and cors first. Headers should be present on every response, including errors, and a preflight must be answered before authentication runs (preflights carry no credentials, so an auth check would reject them).
  2. morgan early, so even rejected requests are logged.
  3. compression before routes, because it wraps res.end and must be in place before anyone writes the body.
  4. Body parsers before the routes that read req.body, and ideally only on the routes that need them: a global 100 KB limit is fine, but a file-upload route needs its own settings.
  5. Authentication, then routes, then the 404 handler, then the error handler last.

A frequent bug is putting cors() after the router. The route answers first, and the CORS headers never get added. The second frequent bug is the mirror image: forgetting that an error handler registered before the routes never sees their errors.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A browser page on origin A calls your API. Which part of the system actually enforces CORS?

    Your server only sends headers. The browser decides whether the page's script may read the response. curl and server-to-server calls ignore CORS, so it is not authentication.
  2. 2. Why does the cors middleware answer an OPTIONS preflight itself and not call next()?

    A preflight asks whether the real request would be accepted. The middleware replies with 204 and the allowed methods and headers, and the route is never executed.
  3. 3. What is the main purpose of the size limit in a JSON body parser?

    Without a limit one request can consume gigabytes of memory. The parser stops reading and answers 413 as soon as the total passes the limit.
  4. 4. You register app.use(cors()) after app.use('/api', router). What happens to API responses?

    Middleware runs in registration order. A route that ends the response stops the chain, so anything registered later never runs for that request.

Summary

  • cors, helmet, morgan, compression and body parsers are ordinary middleware; each is a short function over req, res and next.
  • CORS is a browser rule: the server adds Access-Control-* headers and answers OPTIONS preflights. Keep an explicit origin allow-list and send Vary: Origin.
  • helmet sets safer default headers; Content-Security-Policy is the powerful and the risky one.
  • morgan logs on the response finish event; production systems often prefer structured logs.
  • Compress text responses once (in Node or in the proxy, not both) and set a size limit on every body parser.
  • Order is behaviour: security and logging first, parsers before routes, the error handler last.

Next: Template Engines: EJS and Views.