enable http strict transport security policy

How to Enable HTTP Strict Transport Policy in NodeJS

HTTP Strict Transport Security Policy (HSTS) protects your websites and applications from man-in-the-middle attacks, cookie hijacking and protocol downgrades. However, it is disabled by default in NodeJS. Here is how to enable HTTP Strict Transport Security Policy in NodeJS.


How to Enable HTTP Strict Transport Policy in NodeJS

Here are the steps to enable HSTS in NodeJS. If you have not installed NodeJS on your Linux, run the following commands to install it as per your Linux system.

Ubuntu/Debian
$ sudo apt install nodejs

Redhat/CentOS/Fedora
$ sudo yum install nodejs

Also read : How to Enable HTTP Strict Transport Security Policy in Apache


1. Create/Open NodeJS file

If you have already created a NodeJS file then just open it. Otherwise, open terminal and run the following command to create server.js file for server-related code.

$ sudo vi server.js

Also read : How Does RewriteBase Work With Example


2. Add header

HSTS is enabled by simply adding a server response in your NodeJS file’s code. For example, if you have the following code in it.

var http = require('http');

//create a server object:
http.createServer(function (req, res) {
  res.write('Hello World!'); //write a response to the client
  res.end(); //end the response
}).listen(80); //the server object listens on port 80

Then add the following line before you send the server response.

res.setHeader('Strict-Transport-Security', 'max-age=31536000; includeSubDomains');

In the above line,

  • max-age – Number of seconds HSTS needs to be enforced. We have specified it as 1 year
  • includeSubDomains – Include subdomains to enforce HTTPS

So your server code will look like,

var http = require('http');

//create a server object:
http.createServer(function (req, res) {
  res.write('Hello World!'); //write a response to the client
  res.setHeader('Strict-Transport-Security', 'max-age=31536000; includeSubDomains');
  res.end(); //end the response
}).listen(80); //the server object listens on port 80

You may add this to all URLs processed by NodeJS, or just specific URL routes, depending on your requirement.

Also read : Setup Rsync Between Two Servers Without Password


3. Run NodeJS Server

Run the following command to start your server

$ sudo node server.js

Also read : How to Run NodeJS on Port 80


Leave a Reply

Your email address will not be published. Required fields are marked *