HTTP Strict Transport Security (HSTS) Middleware

2.2.0 · active · verified Tue Apr 21

The `hsts` package provides HTTP Strict Transport Security (HSTS) middleware for Node.js applications, primarily for use with Express or Connect. It adds the `Strict-Transport-Security` header to HTTP responses, instructing browsers to interact with the site exclusively over HTTPS for a specified duration. Key features include configurable `maxAge` (in seconds), `includeSubDomains`, and `preload` directives for HSTS preloading services. This package is part of the Helmet.js suite, a collection of security middleware. The current stable version is 2.2.0, which has been stable for some time, indicating a mature, maintenance-oriented release cadence rather than frequent updates unless security vulnerabilities or major breaking changes in web standards require it. Its primary differentiator is its simplicity and integration within the widely adopted Helmet.js ecosystem, ensuring robust and standard-compliant HSTS implementation.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates basic and conditional HSTS middleware setup for an Express application, including options for preloading.

import express from 'express';
import hsts from 'hsts';

const app = express();
const port = process.env.PORT || 3000;

// Basic HSTS configuration for 180 days, including subdomains
app.use(hsts({
  maxAge: 15552000, // 180 days in seconds
  includeSubDomains: true
}));

// Advanced configuration with preload for HSTS preloading services
// Requires maxAge to be at least 1 year (31536000 seconds) and includeSubDomains to be true.
const preloadHstsMiddleware = hsts({
  maxAge: 31536000, // 1 year
  includeSubDomains: true,
  preload: true
});

// Conditionally apply HSTS middleware only on secure requests
app.use((req, res, next) => {
  if (req.secure) {
    preloadHstsMiddleware(req, res, next);
  } else {
    next();
  }
});

app.get('/', (req, res) => {
  res.send('Hello HSTS World!');
});

app.listen(port, () => {
  console.log(`Server listening on port ${port}. Ensure you access via HTTPS to see HSTS headers.`);
});

view raw JSON →