helmet

repository·main·Indexed 27 days ago

https://github.com/helmetjs/helmet

A middleware for Node.js Express applications that secures them by setting various HTTP response headers. Version 8.3.0 includes middlewares for Content Security Policy (CSP), Cross-Origin-Resource-Policy, Referrer-Policy, HTTP Strict Transport Security (HSTS), X-Content-Type-Options, X-DNS-Prefetch-Control, X-Download-Options, X-Frame-Options, X-Permitted-Cross-Domain-Policies, and X-XSS-Protection.

Tokens
9.8K
Snippets
37
Records
70
Agent score
90%

What's inside helmet

  1. Use X-Download-Options middleware to prevent IE execution

    main

    Use the X-Download-Options middleware to set the X-Download-Options header to noopen. This prevents Internet Explorer users from executing downloaded HTML files in the context of your site, which mitigates risks when serving untrusted HTML. Note that this is a specific fix for Internet Explorer and has negligible performance/bandwidth impact.

    const ienoopen = require("ienoopen");
    app.use(ienoopen());
  2. Configure HTTP Strict Transport Security (HSTS) middleware

    main

    The HSTS middleware adds the Strict-Transport-Security header to responses, instructing browsers to only interact with your site using HTTPS for a specified duration.

    Important Notes:

    • The maxAge value must be provided in seconds.
    • This header does not redirect HTTP users to HTTPS; it only ensures that users already on HTTPS stay on HTTPS. To enforce HTTPS redirection, use a module like express-enforces-ssl.
    • The header is ignored by browsers over insecure HTTP, making it safe to use in development environments.
    const strictTransportSecurity = require("hsts");
    
    // Sets "Strict-Transport-Security: max-age=31536000; includeSubDomains"
    app.use(
      strictTransportSecurity({
        maxAge: 31536000, // 365 days in seconds
      }),
    );
  3. Disable specific HTTP headers in Helmet

    main

    If you need to opt-out of certain security headers provided by Helmet, pass an options object to helmet() and set the corresponding header key to false.

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

    main

    To allow your site to be included in browser HSTS preload lists, add the preload directive.

    Requirements for hstspreload.org eligibility:

    • maxAge must be at least 1 year (31536000 seconds).
    • includeSubDomains must be set to true.
    • preload must be set to true.
    app.use(
      strictTransportSecurity({
        maxAge: 31536000, // Must be at least 1 year to be approved
        includeSubDomains: true, // Must be enabled to be approved
        preload: true,
      }),
    );
  5. Disable upgrade-insecure-requests in development

    main

    The upgrade-insecure-requests directive is enabled by default. This can cause issues in local development environments that do not use HTTPS (e.g., Safari upgrading http://localhost to https://localhost). You can disable it conditionally based on your environment.

    const isDevelopment = app.get("env") === "development";
    
    app.use(
      contentSecurityPolicy({
        directives: {
          // Disable upgrade-insecure-requests in development.
          "upgrade-insecure-requests": isDevelopment ? null : [],
        },
      }),
    );
  6. Configure specific HTTP headers in Helmet

    main

    To customize the behavior of a security header instead of using the defaults, pass a configuration object for that header to the helmet() middleware. For example, you can define specific directives for the contentSecurityPolicy header.

    // Configure the Content-Security-Policy header.
    app.use(
      helmet({
        contentSecurityPolicy: {
          directives: {
            "script-src": ["'self'", "example.com"],
          },
        },
      }),
    );
  7. Use X-DNS-Prefetch-Control middleware

    main

    The dns-prefetch-control middleware allows you to set the X-DNS-Prefetch-Control HTTP header to manage how browsers handle DNS prefetching. You can use it to either disable prefetching or explicitly allow it.

    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 }));
  8. Use X-Content-Type-Options middleware to prevent MIME type sniffing

    main

    The X-Content-Type-Options middleware prevents browsers (such as Chrome, Opera 13+, IE 8+, and Firefox 50+) from attempting to 'sniff' the MIME type of a resource. This helps mitigate vulnerabilities where a browser might execute a file (like a .txt file) as a different type (like a <script>) based on its content rather than the Content-Type header provided by the server. Setting this header to nosniff also assists browsers like Chrome in performing better memory isolation.

    const dontSniffMimetype = require("dont-sniff-mimetype");
    app.use(dontSniffMimetype());
  9. Use X-Frame-Options middleware to prevent clickjacking

    main

    The X-Frame-Options HTTP header restricts which sites can embed your content in a <frame>, <iframe>, <embed>, or <object>. This helps mitigate clickjacking attacks.

    Note: This header is superseded by the frame-ancestors Content Security Policy (CSP) directive, but remains useful for supporting older browsers.

    Supported modes:

    • DENY: Prevents the site from being framed by any site, including your own.
    • SAMEORIGIN: Allows the site to be framed only by pages sharing the same origin.
  10. Use Cross-Origin-Resource-Policy middleware

    main

    The cross-origin-resource-policy middleware sets the Cross-Origin-Resource-Policy HTTP header to control which origins are allowed to load your resources.

    You can configure the policy option with the following values:

    • same-origin: Only allows resources to be loaded by the same origin.
    • same-site: Allows resources to be loaded by any site within the same site (same registrable domain).

    Refer to the Fetch spec for detailed specification information.

    const crossOriginResourcePolicy = require("cross-origin-resource-policy");
    
    // Sets "Cross-Origin-Resource-Policy: same-origin"
    app.use(crossOriginResourcePolicy({ policy: "same-origin" }));
    
    // Sets "Cross-Origin-Resource-Policy: same-site"
    app.use(crossOriginResourcePolicy({ policy: "same-site" }));
  11. Use X-Permitted-Cross-Domain-Policies middleware

    main

    The X-Permitted-Cross-Domain-Policies header informs web clients like Adobe Flash or Adobe Acrobat about your domain's policy for loading cross-domain content. Adding this header provides a security benefit if you do not expect Adobe products to load data from your site.

    To use it, import helmet-crossdomain and add it as middleware to your application. By default, calling crossdomain() without arguments sets the header to none.

    const crossdomain = require("helmet-crossdomain");
    
    // Sets X-Permitted-Cross-Domain-Policies: none
    app.use(crossdomain());