How to enforce HTTPS on Heroku deployed apps i.e. React
Plain JavaScript with some React magic solves this!

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:
useRedirectToHttps()
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.