Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force SSL / https in Express.js

I am trying to create a middleware for Express.js to redirect all non-secure (port 80) traffic to the secured SSL port (443). Unfortunately there is no information in an Express.js request that lets you determine if the request comes over http or https.

One solution would be to redirect every request but this is not an option for me.

Notes:

  1. There is no possibility to handle it with Apache or something else. It has to be done in node.

  2. Only one server can be fired up in the application.

How would you solve that?

like image 343
Elias Avatar asked Dec 22 '11 15:12

Elias


People also ask

How use HTTPS with Express JS?

Go to the terminal and run the following command. After creation adds key & cert file in your code, and pass the options to the server. const express = require('express'); const https = require('https'); const fs = require('fs'); const port = 3000; var key = fs. readFileSync(__dirname + '/../certs/selfsigned.

How do I change from http to HTTPS in Express?

We will perform HTTP to HTTPS redirection by creating an Express middleware function [ 1] and then, inside that function, write the redirection code that will force Express to use HTTPS. The middleware function provides access to the Express req and res objects and next function that we will need.

How do I redirect HTTP request to HTTPS in node JS?

/** * @param req express http request * @returns true if the http request is secure (comes form https) */ function isSecure(req) { if (req. headers['x-forwarded-proto']) { return req. headers['x-forwarded-proto'] === 'https'; } return req. secure; };


1 Answers

Just in case you're hosting on Heroku and just want to redirect to HTTPS regardless of port, here's the middleware solution we're using.

It doesn't bother to redirect if you're developing locally.

function requireHTTPS(req, res, next) {   // The 'x-forwarded-proto' check is for Heroku   if (!req.secure && req.get('x-forwarded-proto') !== 'https' && process.env.NODE_ENV !== "development") {     return res.redirect('https://' + req.get('host') + req.url);   }   next(); } 

You can use it with Express (2.x and 4.x) like so:

app.use(requireHTTPS); 
like image 91
Lavamantis Avatar answered Sep 18 '22 22:09

Lavamantis