Secure Express JS with Helmet Middleware

Securing HTTP headers is a critical step in protecting Node.js applications from common web vulnerabilities. This article provides a quick and practical guide on how to install, configure, and customize the Helmet middleware in an Express-based application to automatically set secure HTTP response headers.

What is Helmet?

Helmet is a security-focused middleware collection for Express.js applications. By setting appropriate HTTP headers, Helmet helps protect your application from well-known web vulnerabilities, including Cross-Site Scripting (XSS), clickjacking, click-sniffing, and directory traversal.

Step 1: Install Helmet

To get started, install the Helmet package via npm or yarn in your project directory:

npm install helmet

or

yarn add helmet

Step 2: Basic Configuration

To apply the default security headers, import Helmet and load it as a middleware using app.use() early in your Express application setup.

const express = require('express');
const helmet = require('helmet');

const app = express();

// Enable Helmet middleware
app.use(helmet());

app.get('/', (req, res) => {
    res.send('Secure Express Application');
});

app.listen(3000, () => {
    console.log('Server running on port 3000');
});

By default, calling helmet() enables 15 different middlewares that set headers such as X-Content-Type-Options, Strict-Transport-Security, and X-Frame-Options.

Step 3: Customizing Helmet Middleware

While the default settings provide robust security, you may need to disable or configure specific headers to fit your application’s requirements.

You can customize Helmet by passing a configuration object to the helmet() function.

Disabling a Specific Header

If a default header conflicts with your application (for example, if you do not want to use the Content Security Policy middleware), you can disable it explicitly:

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

Configuring a Specific Header

You can pass options to individual middlewares within Helmet. A common use case is customizing the Content-Security-Policy (CSP) to allow external scripts or styles:

app.use(
  helmet({
    contentSecurityPolicy: {
      directives: {
        defaultSrc: ["'self'"],
        scriptSrc: ["'self'", "https://trustedscripts.com"],
        styleSrc: ["'self'", "https://trustedstyles.com"],
      },
    },
  })
);

Individual Middleware Usage

If you prefer not to use the main helmet() wrapper, you can import and apply individual middlewares independently:

// Only apply Content-Security-Policy and Frameguard (X-Frame-Options)
app.use(helmet.contentSecurityPolicy());
app.use(helmet.frameguard({ action: 'deny' }));