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

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

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

Creator of thiscodeworks.com \n Follow me @mishkaorakzai on Twitter. I write at mishka.codes

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store