DEV Community

Ashfiquzzaman Sajal
Ashfiquzzaman Sajal

Posted on • Edited on

Don't Be The Next Victim! This Library Will Keep You Safe!

Helmet.js is a powerful middleware for Express.js that helps secure your web applications by setting various security-related HTTP response headers. This guide will provide a detailed overview of Helmet's capabilities, its default settings, and how to customize its behavior to meet your specific security requirements.

Getting Started

Here's a simple example of using Helmet in your Express.js application:

import express from "express";
import helmet from "helmet";

const app = express();

// Use Helmet!
app.use(helmet());

app.get("/", (req, res) => {
  res.send("Hello world!");
});

app.listen(8000);
Enter fullscreen mode Exit fullscreen mode

Default Headers

By default, Helmet sets the following headers:

  • Content-Security-Policy: Mitigates XSS attacks by defining a whitelist of allowed resources (scripts, images, stylesheets).
  • Cross-Origin-Opener-Policy: Helps process-isolate your web page.
  • Cross-Origin-Resource-Policy: Blocks others from loading your resources cross-origin.
  • Origin-Agent-Cluster: Changes process isolation to be origin-based.
  • Referrer-Policy: Controls the Referer header, which can be used to track user behavior.
  • Strict-Transport-Security: Tells browsers to prefer HTTPS over HTTP.
  • X-Content-Type-Options: Avoids MIME sniffing attacks.
  • X-DNS-Prefetch-Control: Controls DNS prefetching.
  • X-Download-Options: Forces downloads to be saved (Internet Explorer only).
  • X-Frame-Options: Legacy header that mitigates clickjacking attacks.
  • X-Permitted-Cross-Domain-Policies: Controls cross-domain behavior for Adobe products.
  • X-Powered-By: Info about the web server. Removed by Helmet because it could be used in simple attacks.
  • X-XSS-Protection: Legacy header that tries to mitigate XSS attacks, but Helmet disables it by default as it can cause issues.

Configuring Headers

Each header can be customized. For example, here's how you configure the Content-Security-Policy header:

// This sets custom options for the
// Content-Security-Policy header.
app.use(
  helmet({
    contentSecurityPolicy: {
      directives: {
        "script-src": ["'self'", "example.com"],
      },
    },
  })
);
Enter fullscreen mode Exit fullscreen mode

Disabling Headers

You can also disable specific headers. For example, here's how to disable the Content-Security-Policy and X-Download-Options headers:

// This disables the Content-Security-Policy
// and X-Download-Options headers.
app.use(
  helmet({
    contentSecurityPolicy: false,
    xDownloadOptions: false,
  })
);
Enter fullscreen mode Exit fullscreen mode

Detailed Header Configuration

Let's delve into the configuration options for each header:

Content-Security-Policy

  • Directives: A nested object containing directives for the Content-Security-Policy header. Each key represents a directive name in camel case (e.g., defaultSrc) or kebab case (e.g., default-src). Each value is an array (or iterable) of strings or functions for that directive.
  • Use Defaults: A boolean value (defaults to true) that determines whether to use the default directives.
  • Report Only: A boolean value (defaults to false) that sets the Content-Security-Policy-Report-Only header instead of the standard Content-Security-Policy header. This allows you to test your CSP configuration without blocking resources.

Cross-Origin-Embedder-Policy

  • Policy: A string representing the policy. Options include:
    • require-corp: Requires the embedder to have the same origin as the embedded content.
    • credentialless: Allows embedding only if the embedder is not sending credentials.

Cross-Origin-Opener-Policy

  • Policy: A string representing the policy. Options include:
    • same-origin: Allows embedding only if the embedder has the same origin as the embedded content.
    • same-origin-allow-popups: Allows embedding only if the embedder has the same origin as the embedded content and allows popups.

Cross-Origin-Resource-Policy

  • Policy: A string representing the policy. Options include:
    • same-origin: Blocks cross-origin requests.
    • same-site: Allows requests only from the same site.

Origin-Agent-Cluster

This header takes no options and is set by default.

Referrer-Policy

  • Policy: A string or array of strings representing the policy. Options include:
    • no-referrer: Sends no Referer header.
    • origin: Sends the origin of the request.
    • unsafe-url: Sends the full URL.

Strict-Transport-Security

  • Max Age: The number of seconds browsers should remember to prefer HTTPS.
  • Include Subdomains: A boolean value (defaults to true) that dictates whether to include the includeSubDomains directive, extending the policy to subdomains.
  • Preload: A boolean value (defaults to false) that adds the preload directive, expressing intent to add your HSTS policy to browsers.

X-Content-Type-Options

This header takes no options and is set by default.

X-DNS-Prefetch-Control

  • Allow: A boolean value (defaults to false) that dictates whether to enable DNS prefetching.

X-Download-Options

This header takes no options and is set by default.

X-Frame-Options

  • Action: A string that specifies which directive to use: DENY or SAMEORIGIN.

X-Permitted-Cross-Domain-Policies

  • Permitted Policies: A string that must be "none", "master-only", "by-content-type", or "all".

X-Powered-By

This header is removed by default.

X-XSS-Protection

This header is disabled by default.

Standalone Middleware

Helmet provides standalone middleware for each header, allowing you to use them individually. For example:

app.use(helmet.contentSecurityPolicy());
Enter fullscreen mode Exit fullscreen mode

Helmet.js Reference

Official Documentation:

Additional Resources:

Conclusion

Helmet.js is an essential tool for securing your Express.js applications. By setting security-related HTTP response headers, it helps protect your website from common attacks. Remember to carefully configure Helmet to meet your specific security needs and to keep your application up-to-date with the latest security patches.

Follow me in X/Twitter

Top comments (1)

Collapse
 
ashsajal profile image
Ashfiquzzaman Sajal

What are your favorite security tools?