express-csp-header and helmet-csp are both middleware solutions for setting Content Security Policy (CSP) headers in Node.js Express applications, but they serve different architectural needs. express-csp-header is a lightweight, standalone package focused exclusively on generating CSP header strings with support for nonces and strict-dynamic patterns. It provides fine-grained control over policy construction without imposing other security headers. helmet-csp was historically the CSP module within the broader helmet security suite, designed to apply a set of secure defaults alongside other HTTP security headers. However, helmet-csp as a standalone package is deprecated; CSP functionality has been fully integrated into the main helmet package since version 4. Developers today should choose between using the dedicated express-csp-header for custom CSP logic or the unified helmet package (which includes CSP) for comprehensive security hardening.
When securing an Express application, setting a Content Security Policy (CSP) header is one of the most effective ways to prevent cross-site scripting (XSS) and data injection attacks. Two common names appear in this space: express-csp-header and helmet-csp. However, the landscape has shifted significantly in recent years. Let's cut through the confusion and look at how these tools actually work, their current status, and which one fits your architecture.
Before diving into code, there is a vital fact every architect must know: helmet-csp as a standalone package is deprecated.
Prior to version 4, the helmet library was split into many small sub-packages like helmet-csp, helmet-xss-filter, and helmet-frameguard. This allowed developers to pick and choose specific headers. However, starting with helmet v4 (released in 2020), all these sub-modules were merged back into the main helmet package.
The standalone helmet-csp package is no longer maintained. Installing it today will trigger deprecation warnings, and it will not receive security updates or feature improvements. If your project currently uses npm install helmet-csp, you should migrate to the main helmet package immediately.
# β Deprecated - Do not use in new projects
npm install helmet-csp
# β
Current Standard - Includes CSP and other headers
npm install helmet
Therefore, the real comparison for modern development is between express-csp-header (a dedicated, single-purpose tool) and helmet (the comprehensive security suite that now contains CSP logic).
The core difference lies in philosophy. express-csp-header does one thing and does it deeply: it builds CSP strings. helmet takes a holistic approach, setting CSP along with 10+ other critical security headers like Strict-Transport-Security, X-Content-Type-Options, and Referrer-Policy in a single call.
With express-csp-header, you manually construct the policy object. This gives you explicit visibility into every directive. It is particularly powerful when you need to generate nonces (random tokens) for inline scripts on every request, a common requirement in server-side rendered (SSR) applications.
import express from 'express';
import { CSP } from 'express-csp-header';
const app = express();
app.use((req, res, next) => {
// Generate a unique nonce for this request
const nonce = Buffer.from(Math.random().toString(36)).toString('base64');
// Attach nonce to locals for use in templates
res.locals.nonce = nonce;
// Apply CSP middleware with custom policy
CSP.middleware({
directives: {
'default-src': [CSP.SELF],
'script-src': [CSP.SELF, (req, res) => `'nonce-${res.locals.nonce}'`],
'style-src': [CSP.SELF, 'unsafe-inline'],
'img-src': [CSP.SELF, 'data:', 'https://cdn.example.com']
}
})(req, res, next);
});
Notice how you define the policy explicitly. There are no hidden defaults. If you don't specify a directive, it isn't set (unless the browser applies its own fallback). This is great for fine-tuning but requires you to know exactly what you need.
helmet simplifies the process by applying a set of secure defaults immediately. You can still customize the CSP, but the starting point is much more restrictive and secure out of the box.
import express from 'express';
import helmet from 'helmet';
const app = express();
// Enables all standard security headers including CSP
app.use(helmet());
// OR: Customize only the CSP part while keeping other defaults
app.use(
helmet({
contentSecurityPolicy: {
directives: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'", "'unsafe-inline'"], // Less secure, but sometimes needed
styleSrc: ["'self'", "'unsafe-inline'"],
imgSrc: ["'self'", "data:", "https://cdn.example.com"]
}
}
})
);
In this example, helmet() automatically sets headers like X-DNS-Prefetch-Control, X-Frame-Options, and Strict-Transport-Security without extra code. If you used express-csp-header, you would need separate packages or manual code to set those.
Dynamic values like nonces are essential for allowing specific inline scripts while blocking others. Both libraries support this, but the syntax differs slightly.
express-csp-header passes the req and res objects directly to the directive value function, making it very straightforward to access response locals.
// express-csp-header approach
const directives = {
'script-src': [
CSP.SELF,
(req, res) => `'nonce-${res.locals.nonce}'`
]
};
helmet uses a similar function-based approach within its configuration object. The function receives the request and response, allowing you to inject dynamic values seamlessly.
// helmet approach
app.use(
helmet({
contentSecurityPolicy: {
directives: {
scriptSrc: [
"'self'",
(req, res) => `'nonce-${res.locals.nonce}'`
]
}
}
})
);
Both achieve the same result. The choice here is less about capability and more about whether you want the CSP logic isolated (express-csp-header) or bundled with other protections (helmet).
Select express-csp-header if:
helmet yet.helmet is undesirable (though the size difference is usually negligible).Select helmet if:
| Feature | express-csp-header | helmet (includes CSP) |
|---|---|---|
| Primary Focus | CSP only | Full suite of HTTP security headers |
| Maintenance Status | β Active | β Active (helmet-csp sub-package is β Deprecated) |
| Default Directives | None (Opt-in) | Secure defaults provided |
| Nonce Support | β Yes (via functions) | β Yes (via functions) |
| Other Headers | β No (Need separate libs) | β Yes (HSTS, X-Frame, etc.) |
| Configuration Style | Explicit policy object | Options object with defaults |
| Best For | Custom, granular control | Rapid, comprehensive hardening |
For the vast majority of professional Express applications, helmet is the correct choice.
Security is rarely just about CSP. An application with a perfect CSP but missing X-Content-Type-Options or Strict-Transport-Security is still vulnerable to other classes of attacks. helmet ensures these protections are applied consistently. The deprecation of the standalone helmet-csp package signals a clear direction from the maintainers: security headers work best when managed as a unified system.
Use express-csp-header only if you have a specific architectural requirement that prevents you from using helmet's defaults or if you are maintaining a legacy system where introducing helmet would cause breaking changes with existing header logic.
If you are currently using helmet-csp, migration is simple:
npm uninstall helmet-cspnpm install helmetimport csp from 'helmet-csp' to import helmet from 'helmet'helmet() call).// Old way (Deprecated)
import csp from 'helmet-csp';
app.use(csp({ directives: { ... } }));
// New way (Recommended)
import helmet from 'helmet';
app.use(helmet({
contentSecurityPolicy: {
directives: { ... }
}
}));
By consolidating your security headers under helmet, you simplify your dependency tree and align with current best practices in the Node.js ecosystem.
Choose express-csp-header if you need precise control over your Content Security Policy without the overhead of other security headers. It is ideal for applications that already handle security headers manually or use other specialized libraries for HSTS, X-Frame-Options, etc. This package shines when you need to generate nonces dynamically for inline scripts or implement strict-dynamic policies in complex server-side rendering setups. It is also the right choice if you want to avoid the opinionated defaults that come with larger security suites.
Do not choose helmet-csp as a standalone package for new projects because it is officially deprecated. The CSP functionality previously found in helmet-csp has been merged into the main helmet package. If you want the convenience of automatically setting multiple security headers (including CSP) with secure defaults, use helmet directly. This approach reduces dependency count and ensures all security headers work together cohesively. Only consider the old helmet-csp if you are maintaining a legacy codebase that has not yet migrated to helmet v4 or higher.
Middleware wrapper for csp-header, so for more information read its documentation.
ES modules:
import { expressCspHeader, INLINE, NONE, SELF } from 'express-csp-header';
CommonJS:
const { expressCspHeader, INLINE, NONE, SELF } = require('express-csp-header');
app.use(expressCspHeader({
directives: {
'default-src': [SELF],
'script-src': [SELF, INLINE, 'somehost.com'],
'style-src': [SELF, 'mystyles.net'],
'img-src': ['data:', 'images.com'],
'worker-src': [NONE],
'block-all-mixed-content': true
}
}));
// express will send header "Content-Security-Policy: default-src 'self'; script-src 'self' 'unsafe-inline' somehost.com; style-src 'self' mystyles.net; img-src data: images.com; workers-src 'none'; block-all-mixed-content; report-uri https://cspreport.com/send;'
If you want to use nonce parameter you should use NONCE constant. Nonce key will be generated automatically. Also generated nonce key will be stored in req.nonce:
const { expressCspHeader, NONCE } = require('express-csp-header');
app.use(expressCspHeader({
directives: {
'script-src': [NONCE]
}
}));
// express will send header with a random nonce key "Content-Security-Policy: script-src 'nonce-pSQ9TwXOMI+HezKshnuRaw==';"
app.use((req, res) => {
console.log(req.nonce); // 'pSQ9TwXOMI+HezKshnuRaw=='
})
If you have more than one tlds you may want to have only current tld in your security policy. You can do this by replacing tld by TLD constant:
const { expressCspHeader, TLD } = require('express-csp-header');
app.use(expressCspHeader({
directives: {
'script-src': [`mystatic.${TLD}`]
}
}));
// for myhost.com it will send: "Content-Security-Policy: script-src mystatic.com;"
// for myhost.net it will send: "Content-Security-Policy: script-src mystatic.net;"
// etc
express-csp-header uses psl package to parse tld for auto-tld feature. If you have a custom tld you can specify it as an array or a regexp.
const { expressCspHeader, TLD } = require('express-csp-header');
app.use(expressCspHeader({
directives: {
'script-src': [`mystatic.${TLD}`]
},
domainOptions: {
customTlds: ['example.com']
}
}));
// for myhost.com it will send: "Content-Security-Policy: script-src mystatic.com;"
// for myhost.example.com it will send: "Content-Security-Policy: script-src mystatic.example.com;"
// etc
const { expressCspHeader } = require('express-csp-header');
app.use(expressCspHeader({
directives: {
'default-src': ["#someString#"],
'script-src': ["#someOtherString#"],
},
processCspString: (cspString, req, res) => {
// here you can process final cspString
return cspString.replaceAll('#someString#', 'https://example.com').replaceAll('#someOtherString#', 'https://example2.com');
}
}));
For more information read csp-header documentation. express-csp-header helps you manage both Content-Security-Policy and Reporting-Endpoints headers. Report-to headers is no longer recommended to use
const { expressCspHeader, INLINE, NONE, SELF } = require('express-csp-header');
app.use(expressCspHeader({
directives: {
'default-src': [SELF],
'report-to': 'csp-default'
},
reportUri: 'https://cspreport.com/send',
reportingEndpoints: [
{'csp-default': 'https://cspreport.com/send'}
]
}));
/* express will send two headers
1. Content-Security-Policy: default-src 'self'; report-to csp-default; report-uri https://cspreport.com/send;
2. Reporting-Endpoints: csp-default="https://cspreport.com/send"
*/
Read about preset in csp-header docs
To switch on Report-Only mode just specify reportOnly param:
const { expressCspHeader, SELF } = require('express-csp-header');
app.use(expressCspHeader({
directives: {
'script-src': [SELF]
},
reportOnly: true
}));
// it will send: "Content-Security-Policy-Report-Only: script-src 'self';"
const { expressCspHeader, SELF } = require('express-csp-header');
app.use(expressCspHeader({
directives: {
'script-src': [SELF]
},
reportUri: 'https://cspreport.com/send'
}));
// express will send header "Content-Security-Policy: script-src 'self'; report-uri https://cspreport.com/send;"
If you want to pass some params to the report uri just pass function instead of string:
const { expressCspHeader, SELF } = require('express-csp-header');
app.use(expressCspHeader({
directives: {
'script-src': [SELF]
},
reportUri: (req, res) => {
return `https://cspreport.com/send?time=${Number(new Date())}`;
}
}));
// express will send header "Content-Security-Policy: script-src 'self'; report-uri https://cspreport.com/send?time=1460467355592;"