Helmet

Help secure Express apps with various HTTP headers

README

Helmet

npm version FOSSA Status

Helmet helps you secure your Express apps by setting various HTTP headers. _It's not a silver bullet_, but it can help!

Quick start


First, run npm install helmet for your app. Then, in an Express app:

  1. ``` js
  2. const express = require("express");
  3. const helmet = require("helmet");

  4. const app = express();

  5. app.use(helmet());

  6. // ...
  7. ```

You can also use ECMAScript modules if you prefer.

  1. ``` js
  2. import helmet from "helmet";

  3. const app = express();

  4. app.use(helmet());
  5. ```

By default, Helmet sets the following headers:

  1. ```http
  2. Content-Security-Policy: default-src 'self';base-uri 'self';font-src 'self' https: data:;form-action 'self';frame-ancestors 'self';img-src 'self' data:;object-src 'none';script-src 'self';script-src-attr 'none';style-src 'self' https: 'unsafe-inline';upgrade-insecure-requests
  3. Cross-Origin-Embedder-Policy: require-corp
  4. Cross-Origin-Opener-Policy: same-origin
  5. Cross-Origin-Resource-Policy: same-origin
  6. Origin-Agent-Cluster: ?1
  7. Referrer-Policy: no-referrer
  8. Strict-Transport-Security: max-age=15552000; includeSubDomains
  9. X-Content-Type-Options: nosniff
  10. X-DNS-Prefetch-Control: off
  11. X-Download-Options: noopen
  12. X-Frame-Options: SAMEORIGIN
  13. X-Permitted-Cross-Domain-Policies: none
  14. X-XSS-Protection: 0
  15. ```

To set custom options for a header, add options like this:

  1. ``` js
  2. // This sets custom options for the `referrerPolicy` middleware.
  3. app.use(
  4.   helmet({
  5.     referrerPolicy: { policy: "no-referrer" },
  6.   })
  7. );
  8. ```

You can also disable a middleware:

  1. ``` js
  2. // This disables the `contentSecurityPolicy` middleware but keeps the rest.
  3. app.use(
  4.   helmet({
  5.     contentSecurityPolicy: false,
  6.   })
  7. );
  8. ```

How it works


Helmet is Express middleware. (It also works with Connect or no library at all! If you need support for other frameworks or languages, see this list.)

The top-level helmet function is a wrapper around 15 smaller middlewares.

In other words, these two code snippets are equivalent:

  1. ``` js
  2. import helmet from "helmet";

  3. // ...

  4. app.use(helmet());
  5. ```

  1. ``` js
  2. import * as helmet from "helmet";

  3. // ...

  4. app.use(helmet.contentSecurityPolicy());
  5. app.use(helmet.crossOriginEmbedderPolicy());
  6. app.use(helmet.crossOriginOpenerPolicy());
  7. app.use(helmet.crossOriginResourcePolicy());
  8. app.use(helmet.dnsPrefetchControl());
  9. app.use(helmet.expectCt());
  10. app.use(helmet.frameguard());
  11. app.use(helmet.hidePoweredBy());
  12. app.use(helmet.hsts());
  13. app.use(helmet.ieNoOpen());
  14. app.use(helmet.noSniff());
  15. app.use(helmet.originAgentCluster());
  16. app.use(helmet.permittedCrossDomainPolicies());
  17. app.use(helmet.referrerPolicy());
  18. app.use(helmet.xssFilter());
  19. ```

Reference


helmet(options)

Helmet is the top-level middleware for this module, including all 15 others.

  1. ``` js
  2. // Includes all 15 middlewares
  3. app.use(helmet());
  4. ```

If you want to disable one, pass options to helmet. For example, to disable frameguard:

  1. ``` js
  2. // Includes 14 out of 15 middlewares, skipping `helmet.frameguard`
  3. app.use(
  4.   helmet({
  5.     frameguard: false,
  6.   })
  7. );
  8. ```

Most of the middlewares have options, which are documented in more detail below. For example, to pass { action: "deny" } to frameguard:

  1. ``` js
  2. // Includes all 15 middlewares, setting an option for `helmet.frameguard`
  3. app.use(
  4.   helmet({
  5.     frameguard: {
  6.       action: "deny",
  7.     },
  8.   })
  9. );
  10. ```

Each middleware's name is listed below.

helmet.contentSecurityPolicy(options)

Default:

  1. ```http
  2. Content-Security-Policy: default-src 'self';base-uri 'self';font-src 'self' https: data:;form-action 'self';frame-ancestors 'self';img-src 'self' data:;object-src 'none';script-src 'self';script-src-attr 'none';style-src 'self' https: 'unsafe-inline';upgrade-insecure-requests
  3. ```

helmet.contentSecurityPolicy sets the Content-Security-Policy header which helps mitigate cross-site scripting attacks, among other things. See MDN's introductory article on Content Security Policy.

This middleware performs very little validation. You should rely on CSP checkers like CSP Evaluator instead.

options.directives is an object. Each key is a directive name in camel case (such as defaultSrc) or kebab case (such as default-src). Each value is an iterable (usually an array) of strings or functions for that directive. If a function appears in the iterable, it will be called with the request and response. The default-src can be explicitly disabled by setting its value to helmet.contentSecurityPolicy.dangerouslyDisableDefaultSrc.

These directives are merged into a default policy, which you can disable by setting options.useDefaults to false. Here is the default policy (whitespace added for readability):

    default-src 'self';
    base-uri 'self';
    font-src 'self' https: data:;
    form-action 'self';
    frame-ancestors 'self';
    img-src 'self' data:;
    object-src 'none';
    script-src 'self';
    script-src-attr 'none';
    style-src 'self' https: 'unsafe-inline';
    upgrade-insecure-requests

options.reportOnly is a boolean, defaulting to false. If true, [the Content-Security-Policy-Report-Only header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy-Report-Only) will be set instead. If you want to set _both_ the normal and Report-Only headers, see this code snippet.

You can also get the default directives object with helmet.contentSecurityPolicy.getDefaultDirectives().

Examples:

  1. ``` js
  2. // Sets all of the defaults, but overrides `script-src` and disables the default `style-src`
  3. app.use(
  4.   helmet.contentSecurityPolicy({
  5.     directives: {
  6.       "script-src": ["'self'", "example.com"],
  7.       "style-src": null,
  8.     },
  9.   })
  10. );

  11. // Sets "Content-Security-Policy: default-src 'self';script-src 'self' example.com;object-src 'none';upgrade-insecure-requests"
  12. app.use(
  13.   helmet.contentSecurityPolicy({
  14.     useDefaults: false,
  15.     directives: {
  16.       defaultSrc: ["'self'"],
  17.       scriptSrc: ["'self'", "example.com"],
  18.       objectSrc: ["'none'"],
  19.       upgradeInsecureRequests: [],
  20.     },
  21.   })
  22. );

  23. // Sets the "Content-Security-Policy-Report-Only" header instead
  24. app.use(
  25.   helmet.contentSecurityPolicy({
  26.     directives: {
  27.       /* ... */
  28.     },
  29.     reportOnly: true,
  30.   })
  31. );

  32. // Sets the `script-src` directive to "'self' 'nonce-e33ccde670f149c1789b1e1e113b0916'" (or similar)
  33. app.use((req, res, next) => {
  34.   res.locals.cspNonce = crypto.randomBytes(16).toString("hex");
  35.   next();
  36. });
  37. app.use(
  38.   helmet.contentSecurityPolicy({
  39.     directives: {
  40.       scriptSrc: ["'self'", (req, res) => `'nonce-${res.locals.cspNonce}'`],
  41.     },
  42.   })
  43. );

  44. // Sets "Content-Security-Policy: script-src 'self'"
  45. app.use(
  46.   helmet.contentSecurityPolicy({
  47.     useDefaults: false,
  48.     directives: {
  49.       "default-src": helmet.contentSecurityPolicy.dangerouslyDisableDefaultSrc,
  50.       "script-src": ["'self'"],
  51.     },
  52.   })
  53. );

  54. // Sets the `frame-ancestors` directive to "'none'"
  55. // See also: `helmet.frameguard`
  56. app.use(
  57.   helmet.contentSecurityPolicy({
  58.     directives: {
  59.       frameAncestors: ["'none'"],
  60.     },
  61.   })
  62. );
  63. ```

You can install this module separately as helmet-csp.

helmet.crossOriginEmbedderPolicy(options)

Default:

  1. ```http
  2. Cross-Origin-Embedder-Policy: require-corp
  3. ```

helmet.crossOriginEmbedderPolicy sets the Cross-Origin-Embedder-Policy header to require-corp. See MDN's article on this header for more.

Standalone example:

  1. ``` js
  2. // Sets "Cross-Origin-Embedder-Policy: require-corp"
  3. app.use(helmet.crossOriginEmbedderPolicy());

  4. // Sets "Cross-Origin-Embedder-Policy: credentialless"
  5. app.use(helmet.crossOriginEmbedderPolicy({ policy: "credentialless" }));
  6. ```

You can't install this module separately.

helmet.crossOriginOpenerPolicy()

  1. ```http
  2. Cross-Origin-Opener-Policy: same-origin
  3. ```

helmet.crossOriginOpenerPolicy sets the Cross-Origin-Opener-Policy header. For more, see MDN's article on this header.

Example usage with Helmet:

  1. ``` js
  2. // Uses the default Helmet options and adds the `crossOriginOpenerPolicy` middleware.

  3. // Sets "Cross-Origin-Opener-Policy: same-origin"
  4. app.use(helmet({ crossOriginOpenerPolicy: true }));

  5. // Sets "Cross-Origin-Opener-Policy: same-origin-allow-popups"
  6. app.use(
  7.   helmet({ crossOriginOpenerPolicy: { policy: "same-origin-allow-popups" } })
  8. );
  9. ```

Standalone example:

  1. ``` js
  2. // Sets "Cross-Origin-Opener-Policy: same-origin"
  3. app.use(helmet.crossOriginOpenerPolicy());

  4. // Sets "Cross-Origin-Opener-Policy: same-origin-allow-popups"
  5. app.use(helmet.crossOriginOpenerPolicy({ policy: "same-origin-allow-popups" }));

  6. // Sets "unsafe-none-Opener-Policy: unsafe-none"
  7. app.use(helmet.crossOriginOpenerPolicy({ policy: "unsafe-none" }));
  8. ```

You can't install this module separately.

helmet.crossOriginResourcePolicy()

Default:

  1. ```http
  2. Cross-Origin-Resource-Policy: same-origin
  3. ```

helmet.crossOriginResourcePolicy sets the Cross-Origin-Resource-Policy header. For more, see "Consider deploying Cross-Origin Resource Policy and MDN's article on this header.

Example usage with Helmet:

  1. ``` js
  2. // Uses the default Helmet options and adds the `crossOriginResourcePolicy` middleware.

  3. // Sets "Cross-Origin-Resource-Policy: same-origin"
  4. app.use(helmet({ crossOriginResourcePolicy: true }));

  5. // Sets "Cross-Origin-Resource-Policy: same-site"
  6. app.use(helmet({ crossOriginResourcePolicy: { policy: "same-site" } }));
  7. ```

Standalone example:

  1. ``` js
  2. // Sets "Cross-Origin-Resource-Policy: same-origin"
  3. app.use(helmet.crossOriginResourcePolicy());

  4. // Sets "Cross-Origin-Resource-Policy: same-site"
  5. app.use(helmet.crossOriginResourcePolicy({ policy: "same-site" }));

  6. // Sets "Cross-Origin-Resource-Policy: cross-origin"
  7. app.use(helmet.crossOriginResourcePolicy({ policy: "cross-origin" }));
  8. ```

You can install this module separately as cross-origin-resource-policy.

helmet.expectCt(options)

Default:

  1. ```http
  2. Expect-CT: max-age=0
  3. ```

helmet.expectCt sets the Expect-CT header which helps mitigate misissued SSL certificates. See MDN's article on Certificate Transparency and the [Expect-CT header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Expect-CT) for more.

Expect-CT is no longer useful for new browsers in 2022. Therefore, helmet.expectCt is deprecated and will be removed in the next major version of Helmet. However, it can still be used in this version of Helmet.

options.maxAge is the number of seconds to expect Certificate Transparency. It defaults to 0.

options.enforce is a boolean. If true, the user agent (usually a browser) should refuse future connections that violate its Certificate Transparency policy. Defaults to false.

options.reportUri is a string. If set, complying user agents will report Certificate Transparency failures to this URL. Unset by default.

Examples:

  1. ``` js
  2. // Sets "Expect-CT: max-age=86400"
  3. app.use(
  4.   helmet.expectCt({
  5.     maxAge: 86400,
  6.   })
  7. );

  8. // Sets "Expect-CT: max-age=86400, enforce, report-uri="https://example.com/report"
  9. app.use(
  10.   helmet.expectCt({
  11.     maxAge: 86400,
  12.     enforce: true,
  13.     reportUri: "https://example.com/report",
  14.   })
  15. );
  16. ```

You can install this module separately as expect-ct.

helmet.referrerPolicy(options)

Default:

  1. ```http
  2. Referrer-Policy: no-referrer
  3. ```

helmet.referrerPolicy sets the Referrer-Policy header which controls what information is set in [the Referer header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referer). See "Referer header: privacy and security concerns" and the header's documentation on MDN for more.

options.policy is a string or array of strings representing the policy. If passed as an array, it will be joined with commas, which is useful when setting a fallback policy. It defaults tono-referrer.

Examples:

  1. ``` js
  2. // Sets "Referrer-Policy: no-referrer"
  3. app.use(
  4.   helmet.referrerPolicy({
  5.     policy: "no-referrer",
  6.   })
  7. );

  8. // Sets "Referrer-Policy: origin,unsafe-url"
  9. app.use(
  10.   helmet.referrerPolicy({
  11.     policy: ["origin", "unsafe-url"],
  12.   })
  13. );
  14. ```

You can install this module separately as referrer-policy.

helmet.hsts(options)

Default:

  1. ```http
  2. Strict-Transport-Security: max-age=15552000; includeSubDomains
  3. ```

helmet.hsts sets the Strict-Transport-Security header which tells browsers to prefer HTTPS over insecure HTTP. See the documentation on MDN for more.

options.maxAge is the number of seconds browsers should remember to prefer HTTPS. If passed a non-integer, the value is rounded down. It defaults to 15552000, which is 180 days.

options.includeSubDomains is a boolean which dictates whether to include the includeSubDomains directive, which makes this policy extend to subdomains. It defaults to true.

options.preload is a boolean. If true, it adds the preload directive, expressing intent to add your HSTS policy to browsers. See the "Preloading Strict Transport Security" section on MDN for more. It defaults tofalse.

Examples:

  1. ``` js
  2. // Sets "Strict-Transport-Security: max-age=123456; includeSubDomains"
  3. app.use(
  4.   helmet.hsts({
  5.     maxAge: 123456,
  6.   })
  7. );

  8. // Sets "Strict-Transport-Security: max-age=123456"
  9. app.use(
  10.   helmet.hsts({
  11.     maxAge: 123456,
  12.     includeSubDomains: false,
  13.   })
  14. );

  15. // Sets "Strict-Transport-Security: max-age=123456; includeSubDomains; preload"
  16. app.use(
  17.   helmet.hsts({
  18.     maxAge: 63072000,
  19.     preload: true,
  20.   })
  21. );
  22. ```

You can install this module separately as hsts.

helmet.noSniff()

Default:

  1. ```http
  2. X-Content-Type-Options: nosniff
  3. ```

helmet.noSniff sets the X-Content-Type-Options header to nosniff. This mitigates MIME type sniffing which can cause security vulnerabilities. See documentation for this header on MDN for more.

This middleware takes no options.

Example:

  1. ``` js
  2. // Sets "X-Content-Type-Options: nosniff"
  3. app.use(helmet.noSniff());
  4. ```

You can install this module separately as dont-sniff-mimetype.

helmet.originAgentCluster()

Default:

  1. ```http
  2. Origin-Agent-Cluster: ?1
  3. ```

helmet.originAgentCluster sets the Origin-Agent-Cluster header, which provides a mechanism to allow web applications to isolate their origins. Read more about it in the spec.

Standalone example:

  1. ``` js
  2. // Sets "Origin-Agent-Cluster: ?1"
  3. app.use(helmet.originAgentCluster());
  4. ```

You can't install this module separately.

helmet.dnsPrefetchControl(options)

Default:

  1. ```http
  2. X-DNS-Prefetch-Control: off
  3. ```

helmet.dnsPrefetchControl sets the X-DNS-Prefetch-Control header to help control DNS prefetching, which can improve user privacy at the expense of performance. See documentation on MDN for more.

options.allow is a boolean dictating whether to enable DNS prefetching. It defaults to false.

Examples:

  1. ``` js
  2. // Sets "X-DNS-Prefetch-Control: off"
  3. app.use(
  4.   helmet.dnsPrefetchControl({
  5.     allow: false,
  6.   })
  7. );

  8. // Sets "X-DNS-Prefetch-Control: on"
  9. app.use(
  10.   helmet.dnsPrefetchControl({
  11.     allow: true,
  12.   })
  13. );
  14. ```

You can install this module separately as dns-prefetch-control.

helmet.ieNoOpen()

Default:

  1. ```http
  2. X-Download-Options: noopen
  3. ```

helmet.ieNoOpen sets the X-Download-Options header, which is specific to Internet Explorer 8. It forces potentially-unsafe downloads to be saved, mitigating execution of HTML in your site's context. For more, see this old post on MSDN.

This middleware takes no options.

Examples:

  1. ``` js
  2. // Sets "X-Download-Options: noopen"
  3. app.use(helmet.ieNoOpen());
  4. ```

You can install this module separately as ienoopen.

helmet.frameguard(options)

Default:

  1. ```http
  2. X-Frame-Options: SAMEORIGIN
  3. ```

helmet.frameguard sets the X-Frame-Options header to help you mitigate clickjacking attacks. This header is superseded by [theframe-ancestors Content Security Policy directive](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/frame-ancestors) but is still useful on old browsers. For more, see helmet.contentSecurityPolicy, as well as the documentation on MDN.

options.action is a string that specifies which directive to use—either DENY or SAMEORIGIN. (A legacy directive, ALLOW-FROM, is not supported by this middleware. Read more here.) It defaults toSAMEORIGIN.

Examples:

  1. ``` js
  2. // Sets "X-Frame-Options: DENY"
  3. app.use(
  4.   helmet.frameguard({
  5.     action: "deny",
  6.   })
  7. );

  8. // Sets "X-Frame-Options: SAMEORIGIN"
  9. app.use(
  10.   helmet.frameguard({
  11.     action: "sameorigin",
  12.   })
  13. );
  14. ```

You can install this module separately as frameguard.

helmet.permittedCrossDomainPolicies(options)

Default:

  1. ```http
  2. X-Permitted-Cross-Domain-Policies: none
  3. ```

helmet.permittedCrossDomainPolicies sets the X-Permitted-Cross-Domain-Policies header, which tells some clients (mostly Adobe products) your domain's policy for loading cross-domain content. See the description on OWASP for more.

options.permittedPolicies is a string that must be "none", "master-only", "by-content-type", or "all". It defaults to "none".

Examples:

  1. ``` js
  2. // Sets "X-Permitted-Cross-Domain-Policies: none"
  3. app.use(
  4.   helmet.permittedCrossDomainPolicies({
  5.     permittedPolicies: "none",
  6.   })
  7. );

  8. // Sets "X-Permitted-Cross-Domain-Policies: by-content-type"
  9. app.use(
  10.   helmet.permittedCrossDomainPolicies({
  11.     permittedPolicies: "by-content-type",
  12.   })
  13. );
  14. ```

You can install this module separately as helmet-crossdomain.

helmet.hidePoweredBy()

Default: the X-Powered-By header, if present, is omitted.

helmet.hidePoweredBy removes the X-Powered-By header, which is set by default in some frameworks (like Express). Removing the header offers very limited security benefits (see this discussion) and is mostly removed to save bandwidth.

This middleware takes no options.

Note: [Express has a built-in way to disable the X-Powered-By header](https://stackoverflow.com/a/12484642/804100), which you may wish to use instead of this middleware.

Examples:

  1. ``` js
  2. // Removes the X-Powered-By header if it was set.
  3. app.use(helmet.hidePoweredBy());
  4. ```

You can install this module separately as hide-powered-by.

helmet.xssFilter()

Default:

  1. ```http
  2. X-XSS-Protection: 0
  3. ```

helmet.xssFilter disables browsers' buggy cross-site scripting filter by setting the X-XSS-Protection header to 0. See discussion about disabling the header here and documentation on MDN.

This middleware takes no options.

Examples:

  1. ``` js
  2. // Sets "X-XSS-Protection: 0"
  3. app.use(helmet.xssFilter());
  4. ```

You can install this module separately as x-xss-protection.