How to redirect to WWW using JavaScript?

Redirecting to a sub-domain, like “WWW” or another one, can be a choice or a way to solve a problem. Below is a way to do so using vanilla JavaScript, but before just performing a redirect we need to factor in items like protocol, navigation path, query strings, anchors (hash), and site environment.

Let’s look at each of those.

  • Protocol – we want to make sure that we are always using a secure connection. This we will always have as a static value.
  • Navigation path – this is the current page and the path to it. We want to include this in our target URL, if the redirect is taking place somewhere other than the home page.
  • Query string – these are arguments after the “?” at the end of the navigation path. These can be either data being passed, or values used to trigger certain behaviors on the page.
  • Anchor tags – they are generally used to auto-scroll to a specific place on the page.
  • Site environment – this is beyond the scope of a URL’s structure and more to the benefit of developers and testers. More specifically, we want the redirect to take place for environments where custom domains are supported, e.g. production. The target sub-domain might not be available for temporary staging or testing environments. For example – the Microsoft Azure Static Web App service will provision a temporary environment for pull requests and git branch updates. For those sub-domains like “WWW” are not supported.

Knowing all of the above, we are going to step through as follow: get the current hostname; verify that the hostname is missing the “WWW” sub-domain and we are on the correct environment hostname; construct the URL; try to redirect. Below are these steps implemented in code.

const current_page_url = window.location;
const current_hostname = current_page_url.hostname;
const target_hostname  = "abcxyz";

if (!current_hostname.includes("www") && current_hostname.includes(target_hostname)) {
	const redirect_target = `https://www.${ + current_page_url.pathname + + current_page_url.hash}`;

	try {
	} catch(error) {
		console.error('Unable to redirect to WWW.');

The following resources are on the Mozilla Developer Network and go in more detail about how JavaScript handles URLs.

Discover more from Titan Fusion

Subscribe now to keep reading and get access to the full archive.

Continue reading