helmet-csp

raw JSON →
4.0.0 verified Sat Apr 25 auth: no javascript

Content Security Policy middleware for Express and Node.js. Version 4.0.0 requires Node >=18 and ships TypeScript definitions. It sets the Content-Security-Policy header using a directives object with support for camelCase or kebab-case keys, dynamic values via functions, and a default policy that can be overridden or disabled. Unlike generic CSP libraries, it integrates directly with the Helmet ecosystem and provides sensible defaults to prevent common vulnerabilities like XSS, though it performs minimal validation on the policy itself.

error Error: Cannot find module 'helmet-csp'
cause Package not installed or imported incorrectly.
fix
Run npm install helmet-csp and use require('helmet-csp').
error TypeError: contentSecurityPolicy is not a function
cause Wrong import style; must use default export with require.
fix
Use const csp = require('helmet-csp'); and call csp({...}).
error Error: Invalid directive: 'default-src'
cause Mixing camelCase and kebab-case or using unknown directive.
fix
Use valid directive names like defaultSrc (camelCase) or default-src (kebab-case).
breaking In version 4.0.0, the package is no longer a submodule of helmet. It must be installed separately.
fix Install via npm install helmet-csp and import separately from helmet.
breaking TypeScript types are now included but require Node >=18. Older Node versions will not work.
fix Upgrade Node to version 18 or higher.
gotcha The package performs very little validation on CSP directives. Use external tools like CSP Evaluator.
fix Validate your CSP policy with CSP Evaluator or similar before deploying.
gotcha Setting `useDefaults: false` disables the built-in defaults completely, which may create an insecure policy.
fix Ensure you explicitly define all required directives when disabling defaults, specially defaultSrc.
deprecated The `Content-Security-Policy-Report-Only` mode via `reportOnly: true` is deprecated in favor of using separate headers.
fix Use the `report-uri` or `report-to` directives instead, or set the header manually.
npm install helmet-csp
yarn add helmet-csp
pnpm add helmet-csp

Configures Express with Content Security Policy middleware using custom directives and dynamic nonce.

const express = require('express');
const csp = require('helmet-csp');
const app = express();

app.use(
  csp({
    directives: {
      defaultSrc: ["'self"],
      scriptSrc: ["'self'", "'unsafe-inline'", (req, res) => `'nonce-${res.locals.cspNonce}'`],
      styleSrc: ["'self'", "'unsafe-inline'"],
      imgSrc: ["'self'", 'data:', 'https:'],
    },
  })
);

app.get('/', (req, res) => {
  res.locals.cspNonce = require('crypto').randomBytes(16).toString('hex');
  res.send('<h1>Hello World</h1>');
});

app.listen(3000);