content-security-policy
raw JSON → 0.3.4 verified Sat Apr 25 auth: no javascript maintenance
Express/Connect middleware for setting Content-Security-Policy HTTP headers according to the W3C CSP specification (v0.3.4). This library provides helper constants (SRC_NONE, SRC_SELF, SRC_DATA) and a convenient getCSP() function to generate middleware for global or route-specific policies. It is minimal and focused solely on CSP headers, unlike more comprehensive security packages such as helmet (which includes CSP as one of many middleware). The package requires Node >= 0.4.0 and has no external dependencies, making it lightweight and easy to integrate into existing Express applications. The API is stable but the package has not seen updates since 2018; consider evaluating its suitability for modern CSP requirements.
Common errors
error TypeError: csp.getCSP is not a function ↓
cause Importing default export instead of named function when using ESM syntax.
fix
Use const { getCSP } = require('content-security-policy'); or use dynamic import().
error Error: Cannot find module 'content-security-policy' ↓
cause Package not installed or incorrect import path.
fix
Run
npm install content-security-policy --save and ensure require path is correct. Warnings
gotcha CSP policy values must be strings or arrays of strings; using objects will be ignored. ↓
fix Ensure every directive value is a valid source expression string, e.g., 'self' not SRC_SELF directly.
gotcha The middleware does not set CSP via a meta tag; it only sets the HTTP header. ↓
fix If you need CSP in HTML, consider a different approach or add meta tag manually.
deprecated STARTER_OPTIONS is not documented and may be removed; prefer defining a custom default policy. ↓
fix Define your own baseline policy instead of relying on STARTER_OPTIONS.
Install
npm install content-security-policy yarn add content-security-policy pnpm add content-security-policy Imports
- csp wrong
import csp from 'content-security-policy';correctconst csp = require('content-security-policy'); - SRC_NONE wrong
import { SRC_NONE } from 'content-security-policy';correctconst { SRC_NONE } = require('content-security-policy'); - getCSP wrong
const getCSP = require('content-security-policy').getCSP;correctconst { getCSP } = require('content-security-policy');
Quickstart
const csp = require('content-security-policy');
const express = require('express');
const app = express();
const policy = {
'default-src': csp.SRC_NONE,
'script-src': [csp.SRC_SELF],
'report-uri': '/csp-report'
};
app.use(csp.getCSP(csp.STARTER_OPTIONS));
app.get('/secure', csp.getCSP(policy), (req, res) => {
res.send('This route has CSP enforced.');
});
app.listen(3000);