0

I have an angular 5 app which is hosted on heroku. Currently the users can access the HTTP version of the app.

How can I force the users to be redirected to HTTPS version even if they access HTTP?

What I have tried:

app.use(function (req, res, next) {
let sslUrl;

if (process.env.NODE_ENV === 'production' &&
    req.headers['x-forwarded-proto'] !== 'https') {

    sslUrl = ['https://myapp.herokuapp.com', req.url].join('');
    return res.redirect(sslUrl);
}

return next();
});

I have placed the above code in my node.js server but it has not worked.

The users are unable to use the app over HTTP as they get a 403 ERROR

Skywalker
  • 4,984
  • 16
  • 57
  • 122
  • A quick google search would have returned **[this answer](https://stackoverflow.com/questions/8605720/how-to-force-ssl-https-in-express-js)** –  Mar 13 '18 at 09:15
  • 1
    @trichetriche I have tried what they have suggested in that answer and it does not work. – Skywalker Mar 13 '18 at 09:25

1 Answers1

5

I used the "force-ssl-heroku" package at https://github.com/rangle/force-ssl-heroku, works like magic and very easy integrated.

Just require inside your start entry point script:

var forceSsl = require('force-ssl-heroku');

and use it like that:

app.use(forceSsl);

Deploy and enjoy.

Sagi Tsofan
  • 247
  • 2
  • 7
  • 2
    And make sure your NODE_ENV are set to "production" in Heruko. – Sagi Tsofan Mar 13 '18 at 09:29
  • Does this also redirect if the user specifically types in `http://myapp.herokuapp.com` in the browser? – Skywalker Mar 13 '18 at 09:29
  • Sure. when you hit "myapp.herokuapp.com" in your browser it is translated into http://myapp.herokuapp.com (with http) and then the "force ssl" package identify that the "x-forwarded-proto" header is not "https" and then redirected the request to https://myapp.herokuapp.com (with https). You can check your status codes response at https://httpstatus.io, just put your http url and you will see the status codes. – Sagi Tsofan Mar 13 '18 at 09:31