Skip to content

How to Redirect to Another Page with Parameters in JavaScript

Learn how to programmatically redirect users while passing data via query parameters in JavaScript, including URL encoding best practices for secure navigation.

A common requirement in web development is to programmatically redirect a user to another page while passing data along, for example, sending a search query to a results page or a user ID to a profile page. This is accomplished by constructing a URL with query parameters and setting the window.location.href property.

This guide will teach you how to build a URL with query parameters, the critical importance of URL encoding your values, and how to trigger the redirect from a user action like a button click.

The Core Method: window.location.href

The window.location.href property is the primary way to programmatically navigate the browser to a new URL. When you assign a string containing a URL to this property, the browser immediately initiates a redirect.

For example, you need to trigger a page navigation from a JavaScript function.

Solution:

// This will redirect the user to the specified page.
window.location.href = 'https://example.com/about';

Constructing the URL with Query Parameters

To pass data, you append a query string to the end of the base URL. A query string has a specific format:

  • It starts with a question mark (?).
  • It consists of one or more key=value pairs.
  • Multiple pairs are separated by an ampersand (&).

For example, you want to redirect to a user profile page, passing the userId and a source for tracking.

Solution: You can construct this URL string using a template literal.

const baseUrl = 'https://example.com/profile';
const userId = 12345;
const source = 'dashboard';

// Construct the full URL with query parameters
const finalUrl = `${baseUrl}?userId=${userId}&source=${source}`;

console.log(finalUrl);
// Output: https://example.com/profile?userId=12345&source=dashboard

// To perform the redirect:
window.location.href = finalUrl;

On the receiving page (profile), you can then parse these parameters using the URLSearchParams object:

const urlParams = new URLSearchParams(window.location.search);
const userId = urlParams.get('userId'); // '12345'

Crucial Step: URL Encoding Parameter Values

This is the most critical step for creating robust and secure URLs. If your parameter values contain any special characters (like spaces, &, ?, /, etc.), you must encode them to prevent the URL from breaking.

For example, a value containing a space or an ampersand will corrupt the URL's structure.

// Problem: The space and '&' will break the URL.
const searchTerm = 'laptops & notebooks';
const url = `https://example.com/search?query=${searchTerm}`;
// This becomes: .../search?query=laptops & notebooks
// The '&' will be interpreted as a new, incorrect parameter.

The solution is to always wrap dynamic parameter values in the encodeURIComponent() function. This function converts all special characters into their safe, "percent-encoded" equivalents.

const searchTerm = 'laptops & notebooks';

// Correct: Always encode dynamic values.
const encodedSearchTerm = encodeURIComponent(searchTerm);
// console.log(encodedSearchTerm); // Output: 'laptops%20%26%20notebooks'

const url = `https://example.com/search?query=${encodedSearchTerm}`;

console.log(url);
// Output: https://example.com/search?query=laptops%20%26%20notebooks

Practical Example: Redirecting with Form Data

This example ties everything together. It takes a user's search query from an input field, correctly encodes it, and redirects to a search results page.

HTML:

<form id="search-form">
  <input id="search-input" type="search" placeholder="Enter search term...">
  <button type="submit">Search</button>
</form>

JavaScript:

const searchForm = document.getElementById('search-form');
const searchInput = document.getElementById('search-input');

searchForm.addEventListener('submit', function(event) {
  event.preventDefault(); // Prevent the default form submission

  const searchTerm = searchInput.value;
  
  // Return early if the input is empty
  if (!searchTerm.trim()) {
    alert('Please enter a search term.');
    return;
  }
  
  // 1. Encode the user's input to make it URL-safe.
  const encodedSearchTerm = encodeURIComponent(searchTerm);
  
  // 2. Construct the final URL.
  const finalUrl = `https://example.com/search?query=${encodedSearchTerm}`;
  
  // 3. Perform the redirect.
  console.log('Redirecting to:', finalUrl);
  window.location.href = finalUrl;
});

Conclusion

Redirecting a user to a new page with parameters is a simple process in JavaScript if you follow the correct steps.

  • Use window.location.href to trigger the navigation.
  • Construct a query string at the end of your URL, starting with ? and separating key-value pairs with &.
  • Always use the encodeURIComponent() function on any dynamic values (especially user input) before adding them to the URL. This is a critical step for both functionality and security.
Navigation