Security Headers with koa-helmet

Mount koa-helmet Early to Set CSP, HSTS, and More

Security Headers with koa-helmet

koa-helmet is a thin Koa wrapper around the helmet package that sets a suite of security-focused HTTP response headers in one middleware call.

3 min read Level 2/5 #koa#helmet#security
What you'll learn
  • Mount koa-helmet as the first middleware in the stack
  • Understand what each header does and why it matters
  • Customize Content-Security-Policy for your application

HTTP response headers are your first line of defense against a wide class of browser-based attacks. koa-helmet wraps the battle-tested helmet package so you get sane defaults with a single app.use call.

Installation

npm install koa-helmet

Basic Usage

Mount it before all other middleware so every response is protected.

import Koa from "koa";
import helmet from "koa-helmet";

const app = new Koa();

app.use(helmet()); // applies all default headers

Headers Applied by Default

HeaderProtection
Content-Security-PolicyLimits sources for scripts, styles, images — blocks XSS
Strict-Transport-SecurityForces HTTPS for subsequent visits (HSTS)
X-Content-Type-Options: nosniffPrevents MIME-type sniffing
X-Frame-Options: SAMEORIGINBlocks clickjacking via iframes
X-DNS-Prefetch-Control: offReduces cross-origin DNS leakage
Referrer-Policy: no-referrerLimits referrer information sent to third parties
Cross-Origin-Opener-PolicyIsolates the browser context (Spectre mitigation)

Customising Content-Security-Policy

The default CSP is strict and will break inline scripts/styles. Tailor it to your app’s actual needs:

app.use(
  helmet({
    contentSecurityPolicy: {
      directives: {
        defaultSrc: ["'self'"],
        scriptSrc: ["'self'", "https://cdn.jsdelivr.net"],
        styleSrc: ["'self'", "'unsafe-inline'"], // only if truly needed
        imgSrc: ["'self'", "data:", "https:"],
        connectSrc: ["'self'", "https://api.yourservice.com"],
        upgradeInsecureRequests: [],
      },
    },
  })
);

Avoid 'unsafe-inline' and 'unsafe-eval' in scriptSrc — they largely defeat CSP.

Disabling a Specific Header

Pass false to turn off any individual header:

app.use(
  helmet({
    xFrameOptions: false, // you manage this yourself
  })
);

CORS and helmet

koa-helmet does not set Access-Control-Allow-Origin. CORS is a separate concern — use @koa/cors alongside helmet for cross-origin API access.

Up Next

Add CSRF protection to session-based routes using the SameSite flag and the koa-csrf package.

CSRF Protection →