helmet Documentation

Help secure Express apps with various HTTP headers

10,714 stars TypeScript TypeScript 1 file Β· ~7,164 tokens #helmet#http-headers#javascript#middleware#security
RAW Doc

File: README.md

Helmet

Helmet helps secure Node/Express apps. It sets HTTP response headers such as Content-Security-Policy and Strict-Transport-Security. It aims to be quick to integrate and be low maintenance afterward.

Quick start

javascript
import helmet from "helmet";

const app = express();

app.use(helmet());

This will set 13 HTTP response headers in your app.

See the docs for more info, including the FAQ.

Configuration

Each header can be disabled. To disable a header:

js
// Disable the Content-Security-Policy and X-Download-Options headers
app.use(
  helmet({
    contentSecurityPolicy: false,
    xDownloadOptions: false,
  }),
);

To configure a header, pass header-specific options:

js
// Configure the Content-Security-Policy header.
app.use(
  helmet({
    contentSecurityPolicy: {
      directives: {
        "script-src": ["'self'", "example.com"],
      },
    },
  }),
);

HTTP header reference

Content-Security-Policy

Default (formatted for readability):

text
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

The Content-Security-Policy header mitigates a large number of attacks, such as cross-site scripting. See MDN's introductory article on Content Security Policy.

This header is powerful but likely requires some configuration for your specific app.

To configure this header, pass an object with a nested directives object. Each key is a directive name in camel case (such as defaultSrc) or kebab case (such as default-src). Each value is an array (or other iterable) of strings or functions for that directive. If a function appears in the array, it will be called with the request and response objects.

javascript
// Sets all of the defaults, but overrides `script-src`
// and disables the default `style-src`.
app.use(
  helmet({
    contentSecurityPolicy: {
      directives: {
        "script-src": ["'self'", "example.com"],
        "style-src": null,
      },
    },
  }),
);
js
// Sets the `script-src` directive to
// "'self' 'nonce-e33cc...'"
// (or similar)
app.use((req, res, next) => {
  res.locals.cspNonce = crypto.randomBytes(32).toString("hex");
  next();
});
app.use(
  helmet({
    contentSecurityPolicy: {
      directives: {
        scriptSrc: ["'self'", (req, res) => `'nonce-${res.locals.cspNonce}'`],
      },
    },
  }),
);

These directives are merged into a default policy, which you can disable by setting useDefaults to false.

javascript
// Sets "Content-Security-Policy: default-src 'self';
// script-src 'self' example.com;object-src 'none';
// upgrade-insecure-requests"
app.use(
  helmet({
    contentSecurityPolicy: {
      useDefaults: false,
      directives: {
        defaultSrc: ["'self'"],
        scriptSrc: ["'self'", "example.com"],
        objectSrc: ["'none'"],
        upgradeInsecureRequests: [],
      },
    },
  }),
);

You can get the default directives object with helmet.contentSecurityPolicy.getDefaultDirectives(). Here is the default policy (formatted for readability):

text
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

The default-src directive can be explicitly disabled by setting its value to helmet.contentSecurityPolicy.dangerouslyDisableDefaultSrc, but this is not recommended.

You can set the Content-Security-Policy-Report-Only instead:

javascript
// Sets the Content-Security-Policy-Report-Only header
app.use(
  helmet({
    contentSecurityPolicy: {
      directives: {/* ... */},
      reportOnly: true,
    },
  }),
);

upgrade-insecure-requests, a directive that causes browsers to upgrade HTTP to HTTPS, is set by default. You may wish to avoid this in development, as you may not be developing with HTTPS. Notably, Safari will upgrade http://localhost to https://localhost, which can cause problems. To work around this, you may wish to disable the upgrade-insecure-requests directive in development. For example:

js
const isDevelopment = app.get("env") === "development";

app.use(
  helmet({
    contentSecurityPolicy: {
      directives: {
        // Disable upgrade-insecure-requests in development.
        "upgrade-insecure-requests": isDevelopment ? null : [],
      },
    },
  }),
);

Helmet performs very little validation on your CSP. You should rely on CSP checkers like CSP Evaluator instead.

To disable the Content-Security-Policy header:

js
app.use(
  helmet({
    contentSecurityPolicy: false,
  }),
);

You can use this as standalone middleware with app.use(helmet.contentSecurityPolicy()).

Cross-Origin-Embedder-Policy

This header is not set by default.

The Cross-Origin-Embedder-Policy header helps control what resources can be loaded cross-origin. See MDN's article on this header for more.

js
// Helmet does not set Cross-Origin-Embedder-Policy
// by default.
app.use(helmet());

// Sets "Cross-Origin-Embedder-Policy: require-corp"
app.use(helmet({ crossOriginEmbedderPolicy: true }));

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

You can use this as standalone middleware with app.use(helmet.crossOriginEmbedderPolicy()).

Cross-Origin-Opener-Policy

Default:

http
Cross-Origin-Opener-Policy: same-origin

The Cross-Origin-Opener-Policy header helps process-isolate your page. For more, see MDN's article on this header.

js
// Sets "Cross-Origin-Opener-Policy: same-origin"
app.use(helmet());

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

To disable the Cross-Origin-Opener-Policy header:

js
app.use(
  helmet({
    crossOriginOpenerPolicy: false,
  }),
);

You can use this as standalone middleware with app.use(helmet.crossOriginOpenerPolicy()).

Cross-Origin-Resource-Policy

Default:

http
Cross-Origin-Resource-Policy: same-origin

The Cross-Origin-Resource-Policy header blocks others from loading your resources cross-origin in some cases. For more, see "Consider deploying Cross-Origin Resource Policy" and MDN's article on this header.

js
// Sets "Cross-Origin-Resource-Policy: same-origin"
app.use(helmet());

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

To disable the Cross-Origin-Resource-Policy header:

js
app.use(
  helmet({
    crossOriginResourcePolicy: false,
  }),
);

You can use this as standalone middleware with app.use(helmet.crossOriginResourcePolicy()).

Origin-Agent-Cluster

Default:

http
Origin-Agent-Cluster: ?1

The Origin-Agent-Cluster header provides a mechanism to allow web applications to isolate their origins from other processes. Read more about it in the spec.

This header takes no options and is set by default.

js
// Sets "Origin-Agent-Cluster: ?1"
app.use(helmet());

To disable the Origin-Agent-Cluster header:

js
app.use(
  helmet({
    originAgentCluster: false,
  }),
);

You can use this as standalone middleware with app.use(helmet.originAgentCluster()).

Referrer-Policy

Default:

http
Referrer-Policy: no-referrer

The Referrer-Policy header which controls what information is set in the Referer request header. See "Referer header: privacy and security concerns" and the header's documentation on MDN for more.

js
// Sets "Referrer-Policy: no-referrer"
app.use(helmet());

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 to no-referrer.

js
// Sets "Referrer-Policy: no-referrer"
app.use(
  helmet({
    referrerPolicy: {
      policy: "no-referrer",
    },
  }),
);

// Sets "Referrer-Policy: origin,unsafe-url"
app.use(
  helmet({
    referrerPolicy: {
      policy: ["origin", "unsafe-url"],
    },
  }),
);

To disable the Referrer-Policy header:

js
app.use(
  helmet({
    referrerPolicy: false,
  }),
);

You can use this as standalone middleware with app.use(helmet.referrerPolicy()).

Strict-Transport-Security

Default:

http
Strict-Transport-Security: max-age=31536000; includeSubDomains

The Strict-Transport-Security header tells browsers to prefer HTTPS instead of insecure HTTP. See the documentation on MDN for more.

js
// Sets "Strict-Transport-Security: max-age=31536000; includeSubDomains"
app.use(helmet());

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 365 days.

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

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 to false.

js
// Sets "Strict-Transport-Security: max-age=123456; includeSubDomains"
app.use(
  helmet({
    strictTransportSecurity: {
      maxAge: 123456,
    },
  }),
);

// Sets "Strict-Transport-Security: max-age=123456"
app.use(
  helmet({
    strictTransportSecurity: {
      maxAge: 123456,
      includeSubDomains: false,
    },
  }),
);

// Sets "Strict-Transport-Security: max-age=123456; includeSubDomains; preload"
app.use(
  helmet({
    strictTransportSecurity: {
      maxAge: 63072000,
      preload: true,
    },
  }),
);

To disable the Strict-Transport-Security header:

js
app.use(
  helmet({
    strictTransportSecurity: false,
  }),
);

You may wish to disable this header for local development, as it can make your browser force redirects from http://localhost to https://localhost, which may not be desirable if you develop multiple apps using localhost. See this issue for more discussion.

You can use this as standalone middleware with app.use(helmet.strictTransportSecurity()).

X-Content-Type-Options

Default:

http
X-Content-Type-Options: nosniff

The X-Content-Type-Options mitigates MIME type sniffing which can cause security issues. See documentation for this header on MDN for more.

This header takes no options and is set by default.

js
// Sets "X-Content-Type-Options: nosniff"
app.use(helmet());

To disable the X-Content-Type-Options header:

js
app.use(
  helmet({
    xContentTypeOptions: false,
  }),
);

You can use this as standalone middleware with app.use(helmet.xContentTypeOptions()).

X-DNS-Prefetch-Control

Default:

http
X-DNS-Prefetch-Control: off

The X-DNS-Prefetch-Control header helps control DNS prefetching, which can improve user privacy at the expense of performance. See documentation on MDN for more.

js
// Sets "X-DNS-Prefetch-Control: off"
app.use(helmet());

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

Examples:

js
// Sets "X-DNS-Prefetch-Control: off"
app.use(
  helmet({
    xDnsPrefetchControl: { allow: false },
  }),
);

// Sets "X-DNS-Prefetch-Control: on"
app.use(
  helmet({
    xDnsPrefetchControl: { allow: true },
  }),
);

To disable the X-DNS-Prefetch-Control header and use the browser's default value:

js
app.use(
  helmet({
    xDnsPrefetchControl: false,
  }),
);

You can use this as standalone middleware with app.use(helmet.xDnsPrefetchControl()).

X-Download-Options

Default:

http
X-Download-Options: noopen

The X-Download-Options header 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 header takes no options and is set by default.

js
// Sets "X-Download-Options: noopen"
app.use(helmet());

To disable the X-Download-Options header:

js
app.use(
  helmet({
    xDownloadOptions: false,
  }),
);

You can use this as standalone middleware with app.use(helmet.xDownloadOptions()).

X-Frame-Options

Default:

http
X-Frame-Options: SAMEORIGIN

The legacy X-Frame-Options header to help you mitigate clickjacking attacks. This header is superseded by the frame-ancestors Content Security Policy directive but is still useful on old browsers or if no CSP is used. For more, see the documentation on MDN.

js
// Sets "X-Frame-Options: SAMEORIGIN"
app.use(helmet());

action is a string that specifies which directive to useβ€”either DENY or SAMEORIGIN. (A legacy directive, ALLOW-FROM, is not supported by Helmet. Read more here.) It defaults to SAMEORIGIN.

Examples:

js
// Sets "X-Frame-Options: DENY"
app.use(
  helmet({
    xFrameOptions: { action: "deny" },
  }),
);

// Sets "X-Frame-Options: SAMEORIGIN"
app.use(
  helmet({
    xFrameOptions: { action: "sameorigin" },
  }),
);

To disable the X-Frame-Options header:

js
app.use(
  helmet({
    xFrameOptions: false,
  }),
);

You can use this as standalone middleware with app.use(helmet.xFrameOptions()).

X-Permitted-Cross-Domain-Policies

Default:

http
X-Permitted-Cross-Domain-Policies: none

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

js
// Sets "X-Permitted-Cross-Domain-Policies: none"
app.use(helmet());

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

Examples:

js
// Sets "X-Permitted-Cross-Domain-Policies: none"
app.use(
  helmet({
    xPermittedCrossDomainPolicies: {
      permittedPolicies: "none",
    },
  }),
);

// Sets "X-Permitted-Cross-Domain-Policies: by-content-type"
app.use(
  helmet({
    xPermittedCrossDomainPolicies: {
      permittedPolicies: "by-content-type",
    },
  }),
);

To disable the X-Permitted-Cross-Domain-Policies header:

js
app.use(
  helmet({
    xPermittedCrossDomainPolicies: false,
  }),
);

You can use this as standalone middleware with app.use(helmet.xPermittedCrossDomainPolicies()).

X-Powered-By

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

Helmet removes the X-Powered-By header, which is set by default in Express and some other frameworks. Removing the header offers very limited security benefits (see this discussion) and is mostly removed to save bandwidth, but may thwart simplistic attackers.

Note: Express has a built-in way to disable the X-Powered-By header, which you may wish to use instead.

The removal of this header takes no options. The header is removed by default.

To disable this behavior:

js
// Not required, but recommended for Express users:
app.disable("x-powered-by");

// Ask Helmet to ignore the X-Powered-By header.
app.use(
  helmet({
    xPoweredBy: false,
  }),
);

You can use this as standalone middleware with app.use(helmet.xPoweredBy()).

X-XSS-Protection

Default:

http
X-XSS-Protection: 0

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

This header takes no options and is set by default.

To disable the X-XSS-Protection header:

js
// This is not recommended.
app.use(
  helmet({
    xXssProtection: false,
  }),
);

You can use this as standalone middleware with app.use(helmet.xXssProtection()).


File: middlewares/x-xss-protection/README.md

X-XSS-Protection middleware

The X-XSS-Protection HTTP header aimed to offer a basic protection against cross-site scripting (XSS) attacks. However, you probably should disable it, which is what this middleware does.

Many browsers have chosen to remove it because of the unintended security issues it creates. Generally, you should protect against XSS with sanitization and a Content Security Policy. For more, read this GitHub issue.

This middleware sets the X-XSS-Protection header to 0. For example:

javascript
const xXssProtection = require("x-xss-protection");

// Set "X-XSS-Protection: 0"
app.use(xXssProtection());

If you truly need the legacy behavior, you can write your own simple middleware and avoid installing this module. For example:

javascript
// NOTE: This is probably insecure!
app.use((req, res, next) => {
  res.setHeader("X-XSS-Protection", "1; mode=block");
  next();
});

File: middlewares/x-powered-by/README.md

X-Powered-By middleware

Simple middleware to remove the X-Powered-By HTTP header if it's set.

Hackers can exploit known vulnerabilities in Express/Node if they see that your site is powered by Express (or whichever framework you use). For example, X-Powered-By: Express is sent in every HTTP request coming from Express, by default. This won't provide much security benefit (as discussed here), but might help a tiny bit. It will also improve performance by reducing the number of bytes sent.

javascript
const hidePoweredBy = require("hide-powered-by");
app.use(hidePoweredBy());

Note: if you're using Express, you don't need this middleware and can just do this:

javascript
app.disable("x-powered-by");

File: middlewares/x-permitted-cross-domain-policies/README.md

X-Permitted-Cross-Domain-Policies middleware

The X-Permitted-Cross-Domain-Policies header tells some web clients (like Adobe Flash or Adobe Acrobat) your domain's policy for loading cross-domain content. See the description on OWASP for more.

Usage:

javascript
const crossdomain = require("helmet-crossdomain");

// Sets X-Permitted-Cross-Domain-Policies: none
app.use(crossdomain());

// You can use any of the following values:
app.use(crossdomain({ permittedPolicies: "none" }));
app.use(crossdomain({ permittedPolicies: "master-only" }));
app.use(crossdomain({ permittedPolicies: "by-content-type" }));
app.use(crossdomain({ permittedPolicies: "all" }));

The by-ftp-type is not currently supported. Please open an issue or pull request if you desire this feature!

If you don't expect Adobe products to load data from your site, you get a minor security benefit by adding this header.


File: middlewares/x-frame-options/README.md

X-Frame-Options middleware

The X-Frame-Options HTTP header restricts who can put your site in a frame which can help mitigate things like clickjacking attacks. The header has two modes: DENY and SAMEORIGIN.

This header is superseded by the frame-ancestors Content Security Policy directive but is still useful on old browsers.

If your app does not need to be framed (and most don't) you can use DENY. If your site can be in frames from the same origin, you can set it to SAMEORIGIN.

Usage:

javascript
const frameguard = require("frameguard");

// Don't allow me to be in ANY frames:
app.use(frameguard({ action: "deny" }));

// Only let me be framed by people of the same origin:
app.use(frameguard({ action: "sameorigin" }));
app.use(frameguard()); // defaults to sameorigin

A legacy action, ALLOW-FROM, is not supported by this middleware. Read more here.


File: middlewares/x-download-options/README.md

X-Download-Options middleware

This middleware sets the X-Download-Options header to noopen to prevent Internet Explorer users from executing downloads in your site's context.

javascript
const ienoopen = require("ienoopen");
app.use(ienoopen());

Some web applications will serve untrusted HTML for download. By default, some versions of IE will allow you to open those HTML files in the context of your site, which means that an untrusted HTML page could start doing bad things in the context of your pages. For more, see this MSDN blog post.

This is pretty obscure, fixing a small bug on IE only. No real drawbacks other than performance/bandwidth of setting the headers, though.


File: middlewares/x-dns-prefetch-control/README.md

X-DNS-Prefetch-Control middleware

This middleware lets you set the X-DNS-Prefetch-Control to control browsers' DNS prefetching. Read more about it on MDN and on Chromium's docs.

Usage:

js
const dnsPrefetchControl = require("dns-prefetch-control");

// Set X-DNS-Prefetch-Control: off
app.use(dnsPrefetchControl());

// Set X-DNS-Prefetch-Control: off
app.use(dnsPrefetchControl({ allow: false }));

// Set X-DNS-Prefetch-Control: on
app.use(dnsPrefetchControl({ allow: true }));

File: middlewares/x-content-type-options/README.md

X-Content-Type-Options middleware

Some browsers will try to "sniff" mimetypes. For example, if my server serves file.txt with a text/plain content-type, some browsers can still run that file with <script src="file.txt"></script>. Many browsers will allow file.js to be run even if the content-type isn't for JavaScript.

Browsers' same-origin policies generally prevent remote resources from being loaded dangerously, but vulnerabilities in web browsers can cause this to be abused. Some browsers, like Chrome, will further isolate memory if the X-Content-Type-Options header is seen.

There are some other vulnerabilities, too.

This middleware prevents Chrome, Opera 13+, IE 8+ and Firefox 50+ from doing this sniffing. The following example sets the X-Content-Type-Options header to its only option, nosniff:

javascript
const dontSniffMimetype = require("dont-sniff-mimetype");
app.use(dontSniffMimetype());

MSDN has a good description of how browsers behave when this header is sent.


File: middlewares/strict-transport-security/README.md

HTTP Strict Transport Security middleware

This middleware adds the Strict-Transport-Security header to the response. This tells browsers, "hey, only use HTTPS for the next period of time". (See the spec for more.) Note that the header won't tell users on HTTP to switch to HTTPS, it will just tell HTTPS users to stick around. You can enforce HTTPS with the express-enforces-ssl module.

This will set the Strict Transport Security header, telling browsers to visit by HTTPS for the next 365 days:

javascript
const strictTransportSecurity = require("hsts");

// Sets "Strict-Transport-Security: max-age=31536000; includeSubDomains"
app.use(
  strictTransportSecurity({
    maxAge: 31536000, // 365 days in seconds
  }),
);

Note that the max age must be in seconds.

The includeSubDomains directive is present by default. If this header is set on example.com, supported browsers will also use HTTPS on my-subdomain.example.com. You can disable this:

javascript
app.use(
  strictTransportSecurity({
    maxAge: 31536000,
    includeSubDomains: false,
  }),
);

Some browsers let you submit your site's HSTS to be baked into the browser. You can add preload to the header with the following code. You can check your eligibility and submit your site at hstspreload.org.

javascript
app.use(
  strictTransportSecurity({
    maxAge: 31536000, // Must be at least 1 year to be approved
    includeSubDomains: true, // Must be enabled to be approved
    preload: true,
  }),
);

The header is ignored in insecure HTTP, so it's safe to set in development.

This header is somewhat well-supported by browsers.


File: middlewares/referrer-policy/README.md

Referrer-Policy middleware

The Referer HTTP header is typically set by web browsers to tell the server where it's coming from. For example, if you click a link on example.com/index.html that takes you to wikipedia.org, Wikipedia's servers will see Referer: example.com. This can have privacy implicationsβ€”websites can see where you are coming from. The new Referrer-Policy HTTP header lets authors control how browsers set the Referer header.

Read the spec to see the options you can provide.

Usage:

javascript
const referrerPolicy = require("referrer-policy");

app.use(referrerPolicy({ policy: "same-origin" }));
// Referrer-Policy: same-origin

app.use(referrerPolicy({ policy: "unsafe-url" }));
// Referrer-Policy: unsafe-url

app.use(
  referrerPolicy({
    policy: ["no-referrer", "unsafe-url"],
  }),
);
// Referrer-Policy: no-referrer,unsafe-url

app.use(referrerPolicy());
// Referrer-Policy: no-referrer