0

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)

2 Answers 2

0

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.

-1

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

Git URL: https://github.com/cmdr-dhiraj-laddha/heroku_force_ssl

The Below code may help you force SSL

const express = require('express')
const app = express()
const port = process.env.PORT || 5003;

const 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();
};

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

app.get('/', (req, res) => {
  res.send('Hello World! - '+env)
})

app.listen(port, () => {
  console.log(`Example app listening on port ${port}`)
})
2
  • Thanks for this! I'm following the suggested heroku approach which is to use a library/middleware to do this (help.heroku.com/J2R1S4T8/…) - effectively sslify is very similar to the function you have provided here. However, even writing my own middleware like you suggested does not enforce SSL so I'm not sure where I'm going wrong
    – raafi15
    May 13, 2021 at 9:54
  • Made demo code for testing this SSL update at this git repo github.com/cmdr-dhiraj-laddha/heroku_force_ssl also confirmed by deploy at heroku app.
    – Dhiraj
    Sep 9, 2022 at 3:37

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.