Redirect HTTP to HTTPS in JavaScript

- 1 minute read

Before proceeding, I’d like to mention that this JavaScript snippet is for the browser, not for back-end JavaScript (Node.js).

Anyway, this snippet redirects the user to the HTTPS version of the current page, if they are currently using HTTP:

const upgradeConnection = () => {
    if (window.location.protocol === `http`) {
        window.location.replace(`https://${location.href.split(`//`)[1]}`);
    }
};

It can be used by simply calling the above upgradeConnection function, like this:

upgradeConnection();

Link to this section Conclusion

I’d like to mention that I strongly suggest you handle this from the back-end, and only use this snippet as a last-resort.

There are likely better ways you can redirect the user to HTTPS via your web server configuration or hosting provider, which will vary depending on your setup.