How to detect HTTP & HTTPS requests in a Heroku Node.js app

And block http requests if you don’t want to redirect them

Mishka
2 min readSep 26, 2020

I had figured out automatic SSL Redirects from HTTP to HTTPS for Heroku before. That was where all HTTP requests in the browser would redirect to HTTPS. But when I started experimenting with API’s, I found out that didn’t work.

And I didn’t even want all the HTTP requests to get redirected/blocked either. Just some routes with sensitive data. So once again I went down a rabbit hole, one that didn’t have much info online. And now that I’ve figure it out, thought to share any poor soul who was in the same place I was 20 mins ago :D

Basically, it requires two steps:

1. Detecting Heroku protocol inside an Express app

Add the following line of code at the top of your app.js file:

app.enable(‘trust proxy’);

Now anywhere underneath this line of code if you request the headers you can detect whether the protocol is HTTP or HTTPS.

app.use('/what-is-protocol', function (req, res, next{       console.log(req.headers['x-forwarded-proto'] )
return next();
})

Now block HTTP requests

Add an if-else statement inside the specific router you want to use this for or for the entire app. Below is an example of what it looks like for block HTTP requests for the entire app.

Note: This method does not redirect HTTP to HTTPS on Heroku. I’ve written another blog on that.

If you’re using SSL redirect in this app but want specific requests (like a subdomain or a particular router) to not be redirected and only blocked, be sure to declare all sslRedirect functions below the ones you’ve blocked.

Are you coding today? Save code snippets that work like the ones in this blog or your code editor with just one-click.

Check out my web app, Chrome & VS Code extensions to help you at: https://www.thiscodeworks.com

--

--