express-csp-header vs helmet-csp
Implementing Content Security Policy Headers in Express Applications
express-csp-headerhelmet-csp

Implementing Content Security Policy Headers in Express Applications

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.

Npm Package Weekly Downloads Trend

3 Years

Github Stars Ranking

Stat Detail

Package
Downloads
Stars
Size
Issues
Publish
License
express-csp-header02530.8 kB12 months agoWTFPL
helmet-csp010,74418.8 kB44 months agoMIT

Express CSP Header vs Helmet: Choosing the Right Security Strategy

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.

🚨 Critical Status Update: The Deprecation of helmet-csp

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).

πŸ› οΈ Implementation Style: Dedicated vs. Suite

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.

Using express-csp-header

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.

Using helmet (The Successor to helmet-csp)

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.

πŸ” Handling Nonces and Dynamic Values

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).

βš–οΈ Trade-offs: Control vs. Convenience

When to Choose express-csp-header

Select express-csp-header if:

  • You already have a mature security strategy with custom middleware for other headers.
  • You need to support very specific, non-standard CSP directives that might not be abstracted by helmet yet.
  • You are working in a constrained environment where importing a larger library like helmet is undesirable (though the size difference is usually negligible).
  • You want to avoid the "magic" of defaults and prefer to explicitly declare every single header your app sends.

When to Choose helmet

Select helmet if:

  • You are starting a new project and want strong security defaults immediately.
  • You want to reduce the number of dependencies by using one package for all HTTP security headers.
  • You prefer a "batteries-included" approach where common vulnerabilities are mitigated by default.
  • You want to ensure your CSP is part of a broader security context (e.g., ensuring HSTS is always set when CSP is set).

πŸ“Š Feature Comparison at a Glance

Featureexpress-csp-headerhelmet (includes CSP)
Primary FocusCSP onlyFull suite of HTTP security headers
Maintenance Statusβœ… Activeβœ… Active (helmet-csp sub-package is ❌ Deprecated)
Default DirectivesNone (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 StyleExplicit policy objectOptions object with defaults
Best ForCustom, granular controlRapid, comprehensive hardening

πŸ’‘ The Verdict for Modern Architectures

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.

Migration Path for Legacy Users

If you are currently using helmet-csp, migration is simple:

  1. Uninstall the old package: npm uninstall helmet-csp
  2. Install the main package: npm install helmet
  3. Update your import: change import csp from 'helmet-csp' to import helmet from 'helmet'
  4. Adjust the usage to match the new API (usually wrapping CSP config inside the main 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.

How to Choose: express-csp-header vs helmet-csp

  • express-csp-header:

    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.

  • helmet-csp:

    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.

README for express-csp-header

Content-Security-Policy middleware for Express

NPM version NPM downloads Dependency Status

Middleware wrapper for csp-header, so for more information read its documentation.

Usage

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;'

nonce parameter

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=='
})

Auto tld

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

TLD parsing options

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

Custom processing

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');
    }
}));

CSP violation report

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"
*/

Presets

Read about preset in csp-header docs

Content-Security-Policy-Report-Only mode

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';"

report-uri parameter

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;"

Links