'How to enforce SSL on a Node.js app on heroku?

I'm trying to deploy a Node.js app on Heroku using express, and I am struggling to enforce HTTPS on all incoming traffic. I am using the express-sslify library to do this using the code below, which is identical to the express-sslify docs, but the website still accepts non-HTTPS traffic. Any advice on what to correct and/or alternative middleware to use would be greatly appreciated!

server.js file

var history = require('connect-history-api-fallback');
var enforce = require('express-sslify');
var http = require('http');

var express = require('express');
var serveStatic = require("serve-static")
var path = require('path');
var app = express();
app.use(enforce.HTTPS({ trustProtoHeader: true }));
app.use(serveStatic(path.join(__dirname, 'dist')));
app.use(history());
const port = process.env.PORT || 80;
http.createServer(app).listen(port)


Solution 1:[1]

Please read this article for heroku headers https://devcenter.heroku.com/articles/http-routing#heroku-headers

The Below code may help you for force SSL

 var express = require('express'),
   env = process.env.NODE_ENV || 'development';

 var forceSsl = function (req, res, next) {
    if (req.headers['x-forwarded-proto'] !== 'https') {
        return res.redirect(['https://', req.get('Host'), req.url].join(''));
    }
    return next();
 };

 app.configure(function () {      
    if (env === 'production') {
        app.use(forceSsl);
    }

    // other configurations etc for express go here...
 });

Solution 2:[2]

Another way is eg. this package: https://www.npmjs.com/package/express-sslify

You just write import and one line of code.

const enforce = require('express-sslify');

app.use(enforce.HTTPS({ trustProtoHeader: true }));

One important thing, it needs to be put before all custom endpoints, putting this after custom endpoints may block it from working.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dhiraj
Solution 2 blahax2g