Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 43 ยท Middleware

Common Third-Party Middleware

A tour of the middleware most Express apps install: morgan for logs, cors, helmet for security headers, compression and cookie-parser, with when to use each.

Express stays small on purpose, so common jobs are handled by packages from npm. A handful of them appear in almost every production app: a request logger, CORS headers, security headers, response compression and cookie parsing. They all work the same way you already know from How Middleware Works: you install the package, call it to get a (req, res, next) function and register it with app.use.

On this site npm packages cannot be installed, so the real code below is read-only. After each package you will find a small runnable idea of what it does inside, built on our stand-in framework. The stand-ins are teaching sketches, not replacements.

The usual five

morgan One log line per request.
cors Lets browsers on other origins call your API.
helmet Safer default response headers.
compression Gzips response bodies.

Add cookie-parser when you read cookies.

1 / 2

A typical setup

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

const app = express();

app.use(helmet());
app.use(cors({ origin: 'https://app.example.com' }));
app.use(compression());
app.use(morgan('combined'));
app.use(express.json());
app.use(cookieParser());

// routes go below

Order is a design choice, not decoration. Helmet and CORS go first so even error and 404 responses carry their headers. Compression goes before the routes that produce large bodies. The logger goes early so it sees every request. Body and cookie parsers sit just above the routes that read req.body and req.cookies.

morgan: request logging

morgan writes one line per request after the response finishes. You choose a format:

JavaScript
app.use(morgan('dev'));      // colored: GET /users 200 4.123 ms - 52
app.use(morgan('combined')); // Apache-style, with user agent and referrer
app.use(morgan(':method :url :status :response-time ms')); // your own

Use dev while developing and combined (or a structured logger, see Logging and Debugging) in production. The key trick is that morgan needs to know the status code, which is only known after your handler ran, so it listens for the response's finish event instead of logging immediately. Here is that idea:

Node.js A morgan-style logger using the finish event

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 logger runs first, but the log line appears only when each response has finished, with the final status. The timing text is only "fast" or "slow" so the output is stable; real morgan prints the actual milliseconds.

cors: cross-origin requests

Browsers block a page on https://app.example.com from reading responses from https://api.example.com unless the API opts in with CORS headers. The cors package adds them:

JavaScript
app.use(cors());                                    // any origin: fine for public APIs only
app.use(cors({
  origin: ['https://app.example.com'],              // allow list
  methods: ['GET', 'POST', 'PUT', 'DELETE'],
  credentials: true,                                // allow cookies
}));

It also answers the browser's automatic OPTIONS preflight request. CORS is enforced by the browser only: tools like curl ignore it, so it is not an access-control system. Never combine credentials: true with a wildcard origin; browsers reject that, and the safe fix is an explicit allow list. Security Best Practices returns to this.

The mechanism is small enough to write by hand:

Node.js What cors does: add headers, answer preflight

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.

Notice the other origin still gets a 200 and the data: only the missing header makes the browser refuse to hand the response to the page. That is why CORS never replaces authentication.

helmet: security headers

helmet() sets a bundle of response headers that make common attacks harder: Content-Security-Policy, Strict-Transport-Security, X-Content-Type-Options: nosniff, Referrer-Policy and others, and it removes X-Powered-By. It is one line:

JavaScript
app.use(helmet());
// tune a single policy if the defaults break something
app.use(helmet({ contentSecurityPolicy: { directives: { 'img-src': ["'self'", 'data:'] } } }));

If you do not use Helmet, at least call app.disable('x-powered-by') so you do not advertise the framework. Helmet is a good default, not a complete defense; the policies, especially CSP, must match what your pages actually load.

compression: smaller responses

compression() gzips (or uses Brotli or deflate when the client prefers it) any response worth compressing, which can shrink JSON and HTML to a fraction of their size. In production this is often done by the reverse proxy (nginx, a CDN) instead, so you do not compress twice. The idea:

Node.js The idea behind compression()

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 server wraps res.end, compresses the body and sets Content-Encoding; fetch decompresses it automatically, which is why the printed body looks normal. Real compression streams the data, skips tiny and already compressed responses, and negotiates the best algorithm.

Cookies arrive as one Cookie header string. cookie-parser splits it into req.cookies, and into req.signedCookies if you give it a secret:

JavaScript
app.use(cookieParser('a-long-random-secret'));

app.get('/me', (req, res) => {
  res.json({ plain: req.cookies.theme, signed: req.signedCookies.userId });
});

Setting cookies with the right flags is covered in Cookies and Headers.

Choosing wisely

Every package is code you must keep updated and trust. Install a middleware when it solves a problem you actually have, read what it does by default, and check that it is still maintained. A few tiny middleware you write yourself (next lesson) are often better than a dependency you barely understand.

All five packages above are real and widely used with Express 5. The runnable code is our own teaching sketch of each idea, not the package itself, and it skips many options and edge cases.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does a request logger like morgan listen for the response's finish event?

    The final status and timing are known once the response is done, so morgan logs then.
  2. 2. Which statement about CORS is true?

    CORS headers tell browsers whether a page may read a response. Other clients ignore them, so you still need real access control.
  3. 3. What does helmet() mainly do?

    Helmet adds headers such as CSP, HSTS and X-Content-Type-Options and removes X-Powered-By.
  4. 4. Where should helmet and cors usually be registered?

    Registering them early means every response, including errors and 404s, carries their headers.

Summary

  • Third-party middleware is installed from npm, called to get a function, and registered with app.use.
  • morgan logs requests, cors adds cross-origin headers, helmet adds security headers, compression gzips responses and cookie-parser fills req.cookies.
  • Registration order matters: security and logging first, parsers just above the routes.
  • CORS is a browser rule, not access control.
  • Compression is often better done by a reverse proxy or CDN.
  • Add packages for real needs, and keep them updated.

Next: Writing Your Own Middleware.