Script Valley
Authentication From Scratch
Security HardeningLesson 5.4

Setting security headers with Helmet.js

Helmet.js, Content-Security-Policy, X-Frame-Options, X-Content-Type-Options, HSTS, Referrer-Policy, Permissions-Policy, security header defaults

HTTP Security Headers

Security headers tell the browser to enforce additional protections that your server-side code cannot control. Helmet.js sets sensible defaults for all of them in one line.

npm install helmet
const helmet = require('helmet');
app.use(helmet());

This single call sets: Content-Security-Policy (restricts what resources the page can load, defeating many XSS attacks), HSTS (forces HTTPS for a period), X-Frame-Options: DENY (prevents clickjacking), X-Content-Type-Options: nosniff (prevents MIME sniffing), and several others.

Customizing CSP for Auth Pages

app.use(helmet.contentSecurityPolicy({
  directives: {
    defaultSrc: ["'self'"],
    scriptSrc: ["'self'"],  // no inline scripts
    styleSrc: ["'self'", "'unsafe-inline'"],
    formAction: ["'self'"] // forms can only submit to your own origin
  }
}));

A CSP that blocks inline scripts eliminates a large class of XSS attacks. For auth pages specifically, formAction: ["'self'"] ensures your login forms cannot be hijacked to submit to a third-party origin via DOM manipulation.

Up next

How to implement email verification for new accounts

Sign in to track progress

Setting security headers with Helmet.js โ€” Security Hardening โ€” Authentication From Scratch โ€” Script Valley โ€” Script Valley