How to do JavaScript Redirect for SEO
JavaScript redirects are one of the methods available to webmasters for informing both users and search engines that the requested URL is temporarily or permanently unavailable. The URL served to you should be regarded as an alternative or new permanent. Typically, best practice suggests using server-side 301s, 302s, or 307s. Nginx servers are typically used to host JavaScript (JS) applications, with configuration files that allow for server-side redirects, which Google recommends. However, let’s take a look at the increasingly popular headless website architectures. We’ve noticed that not all headless builds support server-side redirects and instead rely on client-side implementation – specifically, JavaScript redirects.
One benefit of switching to a headless design is that you are no longer running a monolith but a microservices model, even if certain headless CMS solutions allow you to configure redirects at the server or application level. As a result, developers will seek to reduce dependencies and increase stack flexibility.
JavaScript redirects are typically implemented using the window. location. replace function, and they work well for users. However, how well search engines interpret them is debatable.
JAVASCRIPT REDIRECTIONS, AND HOW TO USE THEM
JavaScript redirections are a method of automatically redirecting users from one webpage to another. This technique is commonly used for various purposes, such as redirecting to a different page after a form submission, handling outdated URLs, or navigating based on user interactions. This guide will cover the basics of JavaScript redirections, including different methods and practical examples.
Methods for JavaScript Redirections
1. Using window.location
window.location.href
This method sets the URL of the current window to the specified URL, effectively redirecting the user to a new page.
window.location.href = "https://www.example.com";
window.location.replace
This method is similar to window.location.href
, but it does not keep the originating page in the session history, which means the user cannot navigate back to it using the browser’s back button.
window.location.replace("https://www.example.com");
window.location.assign
This method also changes the current URL to a new one but keeps the originating page in the session history, allowing the user to navigate back.
window.location.assign("https://www.example.com");
2. Using window.location.pathname
This method redirects to a new path on the same domain.
window.location.pathname = "/newpage";
3. Using window.location.search
This method changes the query string of the current URL.
window.location.search = "?newquery=example";
4. Using window.location.hash
This method changes the anchor part of the URL (everything after the #
symbol).
window.location.hash = "#newsection";
5. Using window.history
window.history.pushState
This method changes the URL without reloading the page. It is often used in single-page applications (SPAs) to manage navigation.
window.history.pushState({}, "", "/newpage");
window.history.replaceState
This method works like pushState
, but it replaces the current history entry instead of adding a new one.
window.history.replaceState({}, "", "/newpage");
Practical Examples
Example 1: Simple Redirection
Redirect users to another website after a certain period (e.g., 3 seconds).
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Redirect Example</title>
<script>
function redirect() {
window.location.href = "https://www.example.com";
} setTimeout(redirect, 3000); // Redirect after 3 seconds
</script>
</head>
<body>
<p>You will be redirected in 3 seconds...</p>
</body>
</html>
Example 2: Conditional Redirection
Redirect users based on a condition (e.g., user login status).
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Conditional Redirect Example</title>
<script>
function checkLogin() {
var isLoggedIn = false; // This would typically come from your app logic if (isLoggedIn) {
window.location.href = "/dashboard";
} else {
window.location.href = "/login";
}
}
window.onload = checkLogin;
</script>
</head>
<body>
<p>Checking login status...</p>
</body>
</html>
Example 3: Redirection After Form Submission
Redirect users to a thank-you page after submitting a form.
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Form Submission Redirect</title>
<script>
function submitForm(event) {
event.preventDefault(); // Prevent the default form submission
// Form submission logic goes here
window.location.href = "/thank-you";
}
</script>
</head>
<body>
<form onsubmit="submitForm(event)">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
<button type="submit">Submit</button>
</form>
</body>
</html>
Example 4: SPA Navigation
Use history.pushState
for navigating within a single-page application without reloading the page.
<html lang="en">
<head>
<meta charset="UTF-8">
<title>SPA Navigation Example</title>
<script>
function navigate(path) {
window.history.pushState({}, "", path);
document.getElementById("content").innerHTML = "You are now at " + path;
} window.onpopstate = function() {
document.getElementById("content").innerHTML = "You are now at " + window.location.pathname;
}
</script>
</head>
<body>
<button onclick="navigate('/home')">Home</button>
<button onclick="navigate('/about')">About</button>
<button onclick="navigate('/contact')">Contact</button>
<div id="content">You are now at /</div>
</body>
</html>
JavaScript provides many features that transform the web into a powerful application platform, JavaScript is an important component of the web platform. Making your JavaScript-powered web applications searchable via Google Search can help you find new users and re-engage existing users who are looking for the content your web app provides. While Google Search uses an evergreen version of Chromium to run JavaScript, there are a few things you can optimize.
This guide describes how Google Search processes JavaScript and best practices for improving Google Search JavaScript web apps.
How Google handles JavaScript web apps in three stages:
- Crawling
- Rendering
- Indexing
Googlebot queues pages for crawling as well as rendering. It is not always clear when a page is awaiting crawling and when it is awaiting rendering. When Googlebot requests an HTTP to retrieve a URL from the crawling queue, it first checks to see if you allow crawling. Googlebot reads the robots.txt file. If it marks the URL as disallowed, Googlebot will skip making an HTTP request to this URL and will skip the URL. Googlebot then parses the response for other URLs in HTML links’ href attribute and adds them to the crawl queue. Use the no follow mechanism to prevent link discovery.
Crawling a URL and parsing the HTML response works well for traditional websites or server-side rendered pages where the HTML in the HTTP response contains all content. Some JavaScript sites may use the app shell model, in which the initial HTML does not contain the actual content and Google must execute JavaScript before seeing the actual page content that JavaScript generates.
Googlebot queues all pages for rendering unless a robot meta tag or header instructs Google not to index the page. The carrier may remain in this queue for a few seconds, but it may take longer. When Google’s resources permit, a headless Chromium renders the page and executes the JavaScript. Googlebot parses the rendered HTML for links once more and queues the URLs discovered for crawling. Google indexes the page using the rendered HTML as well. Remember that server-side or pre-rendering is still a good idea because it speeds up your website for users and crawlers alike, and not all bots can run JavaScript.
HOW TO DO JAVASCRIPT REDIRECT
JavaScript redirection is a common technique used to automatically redirect users from one webpage to another. This can be useful in various scenarios, such as redirecting users after a form submission, handling outdated URLs, or navigating based on user interactions. Here’s a comprehensive guide on how to implement JavaScript redirects using different methods.
Methods for JavaScript Redirections
1. Using window.location.href
The window.location.href
property sets the URL of the current window to the specified URL, effectively redirecting the user to a new page.
Example:
window.location.href = "https://www.example.com";
2. Using window.location.replace
The window.location.replace
method replaces the current document with a new one. Unlike window.location.href
, this does not keep the originating page in the session history, meaning the user cannot navigate back to it using the browser’s back button.
Example:
window.location.replace("https://www.example.com");
3. Using window.location.assign
The window.location.assign
method loads a new document, similar to window.location.href
, but keeps the current page in the session history.
Example:
window.location.assign("https://www.example.com");
4. Using window.location.pathname
The window.location.pathname
property sets the path of the current URL, effectively redirecting to a new path on the same domain.
Example:
window.location.pathname = "/newpage";
5. Using window.location.search
The window.location.search
property sets the query string of the current URL, which can be used to redirect to a URL with specific query parameters.
Example:
window.location.search = "?newquery=example";
6. Using window.location.hash
The window.location.hash
property sets the anchor part of the URL (everything after the #
symbol).
Example:
window.location.hash = "#newsection";
7. Using window.history.pushState
The window.history.pushState
method adds an entry to the browser’s session history stack, changing the URL without reloading the page. This is useful for single-page applications (SPAs).
Example:
window.history.pushState({}, "", "/newpage");
8. Using window.history.replaceState
The window.history.replaceState
method works like pushState
, but it replaces the current history entry instead of adding a new one.
Example:
window.history.replaceState({}, "", "/newpage");
Practical Examples
Example 1: Simple Redirection
Redirect users to another website after 3 seconds.
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Redirect Example</title>
<script>
function redirect() {
window.location.href = "https://www.example.com";
} setTimeout(redirect, 3000); // Redirect after 3 seconds
</script>
</head>
<body>
<p>You will be redirected in 3 seconds...</p>
</body>
</html>
Example 2: Conditional Redirection
Redirect users based on a condition (e.g., user login status).
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Conditional Redirect Example</title>
<script>
function checkLogin() {
var isLoggedIn = false; // This would typically come from your app logic if (isLoggedIn) {
window.location.href = "/dashboard";
} else {
window.location.href = "/login";
}
}
window.onload = checkLogin;
</script>
</head>
<body>
<p>Checking login status...</p>
</body>
</html>
Example 3: Redirection After Form Submission
Redirect users to a thank-you page after submitting a form.
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Form Submission Redirect</title>
<script>
function submitForm(event) {
event.preventDefault(); // Prevent the default form submission
// Form submission logic goes here
window.location.href = "/thank-you";
}
</script>
</head>
<body>
<form onsubmit="submitForm(event)">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
<button type="submit">Submit</button>
</form>
</body>
</html>
Example 4: SPA Navigation
Use history.pushState
for navigating within a single-page application without reloading the page.
<html lang="en">
<head>
<meta charset="UTF-8">
<title>SPA Navigation Example</title>
<script>
function navigate(path) {
window.history.pushState({}, "", path);
document.getElementById("content").innerHTML = "You are now at " + path;
} window.onpopstate = function() {
document.getElementById("content").innerHTML = "You are now at " + window.location.pathname;
}
</script>
</head>
<body>
<button onclick="navigate('/home')">Home</button>
<button onclick="navigate('/about')">About</button>
<button onclick="navigate('/contact')">Contact</button>
<div id="content">You are now at /</div>
</body>
</html>
Conclusion
JavaScript redirections are a versatile tool for managing navigation and enhancing user experience on websites. By using methods such as window.location.href
, window.location.replace
, window.history.pushState
, and others, you can effectively control how and when users are redirected. Whether you need to redirect after form submission, based on conditions, or within a single-page application, understanding these techniques will help you implement smooth and efficient redirections.
- Use unique titles and snippets to describe your page
Unique, descriptive title> elements and helpful meta descriptions assist users in quickly identifying the best result for their goal, and our guidelines explain what makes a good title> element and meta description. JavaScript can be used to set or change the meta description as well as the title> element.
Depending on the user’s query, Google Search may display a different title link. This occurs when the title or description is irrelevant to the page content or when we discover alternatives on the page that better match the search query. Learn why the title of a search result may differ from the title of the page.
- Create code that is compatible
Browsers provide numerous APIs, and JavaScript is a rapidly evolving language. Google has some restrictions on the APIs and JavaScript features that it supports. Follow our JavaScript troubleshooting guidelines to ensure your code is Google-compatible. If you feature-detect a missing browser API, we recommend using differential serving and polyfills. We recommend you check the polyfill documentation for potential limitations because some browser features cannot be polyfilled.
- Make use of meaningful HTTP status codes
Googlebot uses HTTP status codes to determine whether or not something went wrong while crawling the page. Use a meaningful status code to tell Googlebot if a page can’t be crawled or indexed, such as 404 for a page that couldn’t be found or 401 for pages that require a login. HTTP status codes can be used to notify Googlebot when a page has moved to a new URL, allowing the index to be updated accordingly.
Here is a list of HTTP status codes and their impact on Google Search. Soft 404 errors should be avoided in single-page apps.
Client-side routing is commonly used in client-side rendered single-page apps. Using meaningful HTTP status codes may be impossible or impractical in this case. Use one of the following strategies to avoid soft 404 errors when using client-side rendering and routing:
- Instead of fragments, use the History API
When Googlebot searches your pages for links, it only considers URLs in the href attribute of HTML links. Use the History API to implement routing between different views of your web app in single-page applications with client-side routing. Avoid using fragments to load different page content to ensure that Googlebot can find links.
- Inject the rel=”canonical” link tag correctly
While we do not recommend using JavaScript for this, a rel=”canonical” link tag can be injected with JavaScript. When rendering the page, Google Search will use the injected canonical URL.
- Use meta robots tags with caution
The meta robots tag can be used to prevent Google from indexing a page or following links. JavaScript can be used to add a meta robot tag to a page or change its content. When Google encounters noindex in the robots meta tag prior to running JavaScript, the page is not rendered or indexed.
- Use long-lasting caching
Googlebot caches aggressively to reduce network requests and resource consumption. WRS may disregard caching headers. As a result, WRS may use out-of-date JavaScript or CSS resources. Content fingerprinting solves this problem by creating a fingerprint of the filename’s content, such as main.2bb85551.js. Because the fingerprint is determined by the content of the file, each update generates a unique filename.
- Make use of structured data
You can create the necessary JSON-LD and inject it into the page using JavaScript if you use structured data on your pages. Make sure to test your implementation to prevent issues.
- Adhere to best practices for web components
Google provides support for web components. When Google renders a page, it flattens the content of the shadow DOM and light DOM. This means that Google can only see the content visible in the rendered HTML. Use the Mobile-Friendly Test or the URL Inspection Tool to inspect the rendered HTML to ensure that Google can still see your content after it has been rendered. After rendering, Google will index. Google will not be able to index the content if it is not visible in the rendered HTML.
The example below shows how to create a web component that displays its light DOM content inside its shadow DOM. A Slot element can be used to ensure that both light and shadow DOM content is displayed in the rendered HTML.
- Image and lazy-loaded content should be fixed
Images can be quite expensive in terms of bandwidth and performance. Lazy-loading images only when the user is about to see them is a good strategy. Follow our lazy-loading guidelines to ensure you’re implementing lazy-loading in a search-friendly manner.
- Design for usability
Make pages for people, not just search engines. Consider your customers’ needs when designing your website. Google will not be able to index the content if it is not visible in the rendered HTML.
CONCLUSION
Window. location. replace is the most commonly used method for implementing JavaScript redirects,
for example,window. location.replace(“https://dantaylor.online”); You can get to my website’s homepage by opening Dev Tools (CTRL + SHIFT + I) and entering the above line in Console.
Another approach is to use window.location.href, but this can cause issues for users.When a user clicks back with the replace method, the browser loads the previous page; however, with the href method, the browser loads and redirects the user back to the page they were just trying to leave (because it’s saved in the navigation history).This results in a UX redirect loop/trap, which causes the user to close the tab and have a bad experience with the website.There are pre-built redirect handling and implementation methods for many popular headless platforms, such as Gatsby. You can use Gatsby to implement 1:1 redirects, wildcard redirects, and “splat” redirects by installing the gatsby-plugin-gatsby-cloud.Similarly, popular headless CMSs such as Jekyll and Strapi include prebuilt modules and plugins to make redirects easier to implement.
Avoid infinite redirect loops
When window.location.replace is used on a specific page, that page is not saved in the session history. So, if you enter a page and are redirected, you cannot return to that page by clicking the back button. You’ll be taken to a previous page.
That is not the case with a window.location.href. When you click back, the same page unloads again, your current URL location is overwritten, and you are redirected to the page you just wanted to leave. This is a never-ending loop. Keep that in mind if you intend to use this redirect method.