Helmet

8.1.0 · active · verified Wed Apr 22

Helmet is a popular middleware package for Express and Connect applications, designed to enhance web security by automatically setting various HTTP response headers. The current stable version is 8.1.0, compatible with Node.js 18 and later. Helmet typically releases major versions at a moderate pace, incorporating updates to security best practices and deprecating outdated headers. Its key differentiator is its ease of use, providing a sensible default set of 12 security headers out-of-the-box, including `Content-Security-Policy`, `Cross-Origin-Opener-Policy`, and `Strict-Transport-Security`. While providing robust defaults, Helmet is highly configurable, allowing developers to fine-tune individual header directives or disable specific headers entirely to suit their application's needs, making it a go-to solution for foundational web security in Node.js environments.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize Helmet with default security headers in an Express application and provides an example of custom Content Security Policy (CSP) configuration.

import express from 'express';
import helmet from 'helmet';

const app = express();
const PORT = process.env.PORT || 3000;

// Apply Helmet with default security headers
app.use(helmet());

// Example: Customize Content Security Policy (CSP)
// This CSP allows scripts only from 'self' (your domain) and 'cdn.example.com'
// and disallows inline scripts unless explicitly whitelisted with a nonce.
app.use(
  helmet({
    contentSecurityPolicy: {
      directives: {
        defaultSrc: ["'self'"],
        scriptSrc: ["'self'", 'cdn.example.com'],
        styleSrc: ["'self'", "'unsafe-inline'"], // 'unsafe-inline' often needed for CSS frameworks
        imgSrc: ["'self'", 'data:'],
        connectSrc: ["'self'"],
        fontSrc: ["'self'", 'https:', 'data:'],
        objectSrc: ["'none'"],
        upgradeInsecureRequests: true,
      },
    },
  }),
);

// Route to demonstrate the application
app.get('/', (req, res) => {
  res.send(`
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Secure App</title>
    </head>
    <body>
        <h1>Hello, secure world with Helmet!</h1>
        <script src="/test-script.js"></nscript>
    </body>
    </html>
  `);
});

// Simple static file for script-src testing
app.get('/test-script.js', (req, res) => {
  res.set('Content-Type', 'application/javascript');
  res.send('console.log("Script loaded securely!");');
});

app.listen(PORT, () => {
  console.log(`Server running on http://localhost:${PORT}`);
  console.log('Open your browser to see security headers in action.');
});

view raw JSON →