Stop 12 · Authentication & SecurityTopics · 12/12

Helmet.js

Part of the MERN Stack Roadmap

In short

Express ships with almost no security headers. Helmet adds a sensible set in one line, so the browser itself starts defending your users.

Helmet is Express middleware that sets secure HTTP headers, such as Content-Security-Policy and X-Content-Type-Options, with one line of code.

The blob straps on a shiny scooter helmet, already wearing gloves and knee pads, next to a scooter.

Think of it like this

Gearing up before the scooter ride

You could think about every possible fall before riding to college, or you could put on a helmet, gloves and knee pads in one go. Helmet.js is that kit for Express: a bundle of protective headers you put on before the first request.

Watch it happen

What helmet() does to every response

Request
helmet()
Your route
Response
Browser

1/5A request for GET /dashboard arrives at Express.

The big ideas

What you need to know

Middleware of many headers

Helmet is a group of small middlewares, each setting one header. helmet() turns on the default set.

Hides X-Powered-By

Express announces itself by default. Removing that header gives attackers one less clue about your stack.

Tune, don't disable

If CSP blocks your CDN images, add that CDN to img-src. Turning the whole policy off throws away the main protection.

Not a firewall

Helmet only sets response headers. It won't stop SQL injection, bad auth or missing validation.

See it in code

Walk through the code

ts
1import express from "express";2import helmet from "helmet";3 4const app = express();5 6// Sensible defaults, plus one custom CSP rule7app.use(8  helmet({9    contentSecurityPolicy: {10      directives: { "img-src": ["'self'", "https://cdn.example.com"] },11    },12  })13);

1/3Install with npm i helmet, import it and create the app as usual.

Your directives are merged with Helmet's default CSP. Put app.use(helmet()) near the top so every route, including errors, gets the headers.

Save yourself the pain

Common mistakes

Oops

Adding helmet() after your routes.

Do this instead

Middleware runs in order. Put Helmet before routes, or those responses go out without headers.

Oops

Setting contentSecurityPolicy: false the moment something breaks.

Do this instead

Open the browser console, read which directive blocked what, and allow just that source.

Your mission

Before and after Helmet

~15 min

Quick check

After adding Helmet, your page's images from a CDN stop loading. What's the right fix?

Go deeper

  1. 1Add app.use(helmet()) near the top of your middleware.
  2. 2Check your response headers in DevTools before and after.
  3. 3Add express-rate-limit on login routes to slow down password guessing.

Also part of these roadmaps

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge