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

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:




Creator of \n Follow me @mishkaorakzai on Twitter. I write at

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

How to handle HTTP reponse using axios

Hi Gatsby. We’re Jetveo.

Our next gen app—from ‘Plush Barbers’ to useful toolkit

How do you copy by value a composite data type?

Build your own COVID 19 live stats dashboard with influxdb 2.0 and nodejs with minimal code

Most Useful Features of JavaScript ES6

Use hooks in class component

Hoc with hook

How to insert Dynamic Data using Express.js and Handlebars

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


Creator of \n Follow me @mishkaorakzai on Twitter. I write at

More from Medium


Our Mistakes are Divine

Day 31: Losing “The Boyfriend” I’ve Never Had