The `strict-transport-security` package provides Node.js middleware designed to add the Strict-Transport-Security (HSTS) header to HTTP responses. This header enforces secure (HTTPS) connections, preventing downgrade attacks and cookie hijacking in compliant browsers, as specified by RFC6797. It is built to integrate seamlessly with Express.js and Connect-compatible frameworks, allowing developers to define global or path-specific HSTS policies. The package is currently at version 0.3.0, with its latest notable update introducing support for the `preload` option. Its development cadence suggests a mature and stable, yet likely low-maintenance, library focused on a singular security concern. Its primary differentiator is its dedicated functionality for HSTS, offering a lightweight alternative to larger security middleware suites.
npm install strict-transport-securityVerified import paths — ran on the pinned version, not inferred.
Demonstrates how to initialize and apply Strict-Transport-Security middleware globally across all requests and how to define and apply a path-specific policy that overrides the global one within an Express.js application.
Thoroughly test HSTS policies in development before deploying to production. Start with a short `max-age` for testing and gradually increase. Always ensure your server enforces HTTPS redirects *before* HSTS headers are applied.
Only enable `preload` and submit to HSTS preload lists if you are absolutely confident in your long-term HTTPS strategy and infrastructure. Any HTTPS outage or misconfiguration after preloading will render your site unusable for a significant portion of users.
Configure your web server (e.g., Nginx, Apache) or your application's entry point to perform a 301 (Permanent) redirect from HTTP to HTTPS for all incoming requests before this middleware is executed.
Ensure you have an Express or Connect application instance (e.g., `const app = express();`) before calling `app.use()`.
Verify that `strict-transport-security` is correctly installed (`npm install strict-transport-security --save`) and that the `require()` path is accurate. Ensure you are calling `getSTS` on the correct `sts` module object.
The `max-age` option expects an object with a duration property (e.g., `days`, `seconds`), for example: `{'max-age': {'days': 30}}`.