HTTP security headers are a generic tool that can be employed by any technology at the HTTP medium, including load balancers, API gateways, reverse proxies, and web application frameworks.
Helmet.js is a Node.js module that can be used to secure HTTP headers returned by Express applications. HTTP headers are an essential part of the HTTP protocol but are transparent to the end-user. The headers provide essential metadata about the HTTP request or response so the client and server can send additional information in a transaction.
If we use an Express web application setup, we'll begin by installing the Helmet module:
npm install --save helmet
Then, continue to instantiate an Express application object and set an
application middleware using Helmet. In this example, we put the
X-Frame-Options using Helmet's built-in frameguard
method:
const express = require('express')const helmet = require('helmet')const app = express()app.use(helmet.frameguard({action: 'sameorigin'}))
We can implement the following HTTP headers using Helmet.js :
To use Helmet's npm
package and add it as a package dependency in our Node.js app. After that, set up the hsts
to indicate to a web client that it should send HTTPS requests to our server's hostname for a given period:
const helmet = require("helmet");// Set the expiration time of HTTPS requests to the// server to 1 month, specified in millisecondsconst reqDuration = 2629746000;app.use(helmet.hsts({maxAge: reqDuration,}));
Implementing this header with Helmet is as simple as acquiring the helmet
package and using Express's app
object to instruct Express to use the xframe
middleware provided by Helmet.
const helmet = require("helmet");app.use(helmet.frameguard({action: "deny",}));
To implement this header with Helmet.js, we can use the following code snippet:
const helmet = require("helmet");app.use(helmet.contentSecurityPolicy({directives: {scriptSrc: ["'self'"],styleSrc: ["'self'"],},}));
This header allows us to toggle on or off the Cross-Site-Scripting (XSS) filter capability. We can turn on this protection with Helmet.js by using the following snippet:
const helmet = require("helmet");app.use(helmet.xssFilter());
To implement this header with Helmet.js, we can use the following code snippet:
const helmet = require("helmet");app.use(helmet.noSniff());
We can configure this policy using the following code snippet:
const helmet = require("helmet");app.use(helmet.referrerPolicy({policy: "no-referrer",}));
The implementation of security headers helps us to prevent security vulnerabilities. However, a common mistake is to rely solely on security headers to resolve issues. Effectively responding to a request with a security header depends on the browser to support, implement, and adhere to certain specifications to enforce the header.
Free Resources