How to enforce HTTPS on Heroku deployed apps i.e. React

Plain JavaScript with some React magic solves this!

Uros Randelovic
Nov 26, 2020 · 2 min read
Image for post
Image for post
Photo V School

This issue bothered me for a while and I did not like any of the solutions I found on the web and then the light turned on in my head!

React now offers us React Hooks, The 7th World Wonder of modern web development. How does this solve our problem?

We can write a custom hook that will trigger every time we render one of our pages. Assuming you already have your React app running go ahead and create a folder for your custom hook and a file called useRedirectToHttps.js

Inside of useRedirectToHttps.js we will create a hook called useRedirectToHttps and invoke a useEffect() on every render. The useEffect’s job is pretty simple, get the current URL, checks if it’s HTTPS and redirects to the page with the HTTPS

In any of your React components you can call:

Et voila! Your app will redirect the users to the HTTPS website every single time 🎉

PS. A couple of notes regarding the JavaScript properties we’re using here

window.location.protocol — returns the string representation of the prtocol you’re currently using to access the website — note that it has a colon too, not just the protocol.

window.location.replace(“https://…”) — redirects the user to the HTTPS and removes the possibility of the user going back to the HTTP by removing the entry from the browser history.

location.pathname — is a react-router goodie that allows us to check where we are at the moment, alternatively, you can also parse the string returned from the window.location.href if you don’t use react-router.

JavaScript In Plain English

New JavaScript + Web Development articles every day.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

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