How to redirect to new URL in JavaScript

Dec 13, 2023#javascript#webdev

Redirecting to a new URL using JavaScript directly or using a JavaScript framework often achieves the same end result, but there are differences in terms of simplicity, functionality, and the overall development approach.

For simple redirections without the need for advanced routing features, using window.location object is often sufficient. If your application has a complex navigation structure, dynamic routing requirements, or involves a single-page application (SPA), using a JavaScript framework with a routing library is more appropriate.

Here’s an expanded look at your options for redirecting in vanilla JavaScript:

  1. Using window.location.href property

This property is a way to get or set the URL of the current web page in JavaScript. It can be used to navigate to a new web page, reload the current web page, or send data to the server by modifying the search property.

To navigate to a new web page, you can assign a new URL to this property. This will also add an entry to the browser history, so the user can go back to the previous page by clicking the back button.

const currentUrl = window.location.href;
console.log(currentUrl); 
// Outputs the full URL of the current page

// Redirects to the specified URL
window.location.href = "https://www.example.com"; 

// Change the protocol
window.location.href = window.location.href.replace("http", "https");

// Add a query parameter
window.location.href += "?new_param=value";

Remember window.location property also has various other properties and methods to manipulate the URL, such as hostname, pathname, protocol, port, host, assign, and reload.

  1. Using window.location.replace() method

This method swaps the current page with the new one, effectively burning the bridge back. Use it for one-way journeys, like confirming an order or logging out, where returning would be undesirable or illogical.

Let’s imagine you have a login form and you want to redirect the user to their dashboard after successful login. Here’s how you can use window.location.replace():

function login() {
  const username = document.getElementById("username").value;
  const password = document.getElementById("password").value;

  // Simulate login logic (replace with your actual authentication)
  if (username === "admin" && password === "secret") {
    window.location.replace("https://yourwebsite.com/dashboard");
  } else {
    alert("Invalid username or password!");
  }
}

The user cannot go back to the login page using the back button, preventing accidental logout or re-login attempts.

Suppose you have a page where users can delete their account. You might want to confirm their decision before permanently deleting the account and redirecting them to another page.

function deleteAccount() {
  if (confirm("Are you sure you want to delete your account?")) {
    // Perform account deletion logic (replace with your actual code)
    fetch("/api/delete-account").then(() => {
      window.location.replace("https://yourwebsite.com/goodbye");
    });
  }
}

If the user confirms, it sends a request to the server to delete the account and then uses window.location.replace() to redirect them to a dedicated “goodbye” page, again preventing them from coming back to the deleted account page.

Remember to always consider the user experience when using window.location.replace(), making sure it aligns with your website’s functionality and avoids confusing users.

  1. Using window.location.assign() method

This is your “history-aware” redirect. It updates the browser history, allowing users to return with the back button. Useful for multi-step workflows or forms where users might need to retrace their steps.

It works similar to window.location.href. The primary difference between the two is that window.location.assign() is a method designed specifically for navigation, while window.location.href is a property that can be used for navigation among other things.

Imagine you have a multi-step checkout process where users go through different pages (cart, shipping, payment). After completing each step, you want to redirect them to the next page, but still allow them to navigate back if needed. Here’s how you can use window.location.assign():

function goToShipping() {
  // Validate cart items and perform any necessary logic
  if (validateCart()) {
    window.location.assign("/checkout/shipping");
  } else {
    // Show error message or redirect to cart page
  }
}

function goToPayment() {
  // Validate shipping information and perform any necessary logic
  if (validateShipping()) {
    window.location.assign("/checkout/payment");
  } else {
    // Show error message or redirect to shipping page
  }
}

function submitOrder() {
  // Submit order details and handle payment
  // After successful submission, redirect to confirmation page
  window.location.assign("/checkout/confirmation");
}

Better using a routing library

While using window.location to redirect to a URL is a common practice and works well in many scenarios, there are some limitations and considerations to keep in mind:

  • Not providing any built-in functionality for handling routes, parameters, or transitions.
  • Not supporting features like lazy loading, guards, resolvers, or animations.
  • Not integrating well with single-page applications or frameworks that rely on virtual DOM.
  • Requiring manual management of the browser history and state.
  • Potentially causing unwanted page reloads or flickers.

For more complex applications with SPAs or advanced routing needs, consider using a dedicated routing library to address some of these limitations and provide additional features.

  • Simplifying the definition and management of routes and their corresponding components.
  • Enabling dynamic and nested routing, parameter passing, and route transitions.
  • Supporting features like lazy loading, guards, resolvers, and animations.
  • Integrating well with popular frameworks like React, Vue, Angular, or Svelte.
  • Improving the user experience and performance of single-page applications.

Popular examples of routing libraries for various JavaScript frameworks include: