Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

helmet-csp

Package Overview
Dependencies
Maintainers
1
Versions
42
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

helmet-csp

Content Security Policy middleware

  • 3.2.0
  • Source
  • npm
  • Socket score

Version published
Maintainers
1
Created
Source

Content Security Policy middleware

Content Security Policy helps prevent unwanted content being injected into your webpages. This can mitigate cross-site scripting (XSS) vulnerabilities, malicious frames, unwanted trackers, and much more.

If you want to learn how CSP works, check out the fantastic HTML5 Rocks guide, the Content Security Policy Reference, and the Content Security Policy specification.

This middleware helps set Content Security Policies.

Basic usage:

const contentSecurityPolicy = require("helmet-csp");

app.use(
  contentSecurityPolicy({
    directives: {
      defaultSrc: ["'self'", "default.example"],
      scriptSrc: ["'self'", "'unsafe-inline'"],
      objectSrc: ["'none'"],
      upgradeInsecureRequests: [],
    },
    reportOnly: false,
  })
);

To get the defaults, use contentSecurityPolicy.getDefaultDirectives().

You can set any directives you wish. defaultSrc is required. Directives can be kebab-cased (like script-src) or camel-cased (like scriptSrc). They are equivalent, but duplicates are not allowed.

The reportOnly option, if set to true, sets the Content-Security-Policy-Report-Only header instead.

This middleware does minimal validation. You should use a more sophisticated CSP validator, like Google's CSP Evaluator, to make sure your CSP looks good.

Recipe: generating nonces

You can dynamically generate nonces to allow inline <script> tags to be safely evaluated. Here's a simple example:

const crypto = require("crypto");

app.use((req, res, next) => {
  res.locals.nonce = crypto.randomBytes(16).toString("hex");
  next();
});

app.use((req, res, next) => {
  csp({
    directives: {
      defaultSrc: ["'self'"],
      scriptSrc: ["'self'", `'nonce-${res.locals.nonce}'`],
    },
  })(req, res, next);
});

app.use((req, res) => {
  res.end(`<script nonce="${res.locals.nonce}">alert(1 + 1);</script>`);
});

See also

Keywords

FAQs

Package last updated on 01 Nov 2020

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc