Explain Codes LogoExplain Codes Logo

How do I redirect with JavaScript?

javascript
redirect
promises
callbacks
Alex KataevbyAlex Kataev·Jan 3, 2025
TLDR

Swiftly redirect in JavaScript with:

window.location = 'https://www.example.com';

Simply set window.location to your desired URL for an instant page transition—simple yet effective.

Essential redirection elements

Error coverage: be prepared

It's fundamental to manage errors in regards to redirection. Implement try...catch structures to catch any redirection issues, allowing an uninterrupted experience for your users:

try { window.location.href = 'https://www.example.com'; } catch (e) { console.error('Redirection failed but we\'ll try harder', e); // Whoopsie daisy }

The no return journey: window.location.replace()

The window.location.replace() method performs an HTTP-like redirect and makes sure the current page won't hang around in the session history, eliminating the possibility for the user to steer back to it:

window.location.replace('https://www.example.com'); // No breadcrumbs behind

Defense first: security enhancements

Unfiltered user input can induce vulnerabilities such as open redirects. Always sanitize and validate input prior to integrating it into any sort of redirection:

// Pseudo-code to depict user input validation if (isValidUrl(userInput)) { window.location = userInput; } // Jedi approved. May the force be with you!

Every browser is a different beast

It's key to make sure your code behaves well across multiple browsers. Even though window.location is a standard, some quirky behaviors might show across diverse browsers. Hence, it's good practice to cross-verify your solution in the prominent four (Chrome, Firefox, Safari, Edge).

UX at heart: Principal considerations

Take into account the user's experience when choosing between replace() and href. When you aim to provide the user with the option to travel back to the preceding page, href would be your friend. On the contrary, replace() is what you need if you prioritise avoiding backward navigation.

Deep dive into nuances: Expanding redirection techniques

Communication through redirection: State and function parameters

In certain cases, you might find it imperative to pass along state or invoke functions post redirection, especially in Single Page Applications (SPA). This has been made possible by either using the URL hash or the sessionStorage/localStorage:

window.location = 'https://www.example.com/#interstellar';

A pause before the leap: Timer based redirection

A delayed redirection can be employed to afford some time (e.g., to showcase a message before the page rids itself). The setTimeout function is tailor-made for this purpose:

setTimeout(function() { window.location = 'https://www.example.com'; }, 2000); // 2 seconds to say your prayers!

Invoking functions: Advanced redirectional capabilities

In a scenario where you wish to redirect to a function rather than a URL, event-driven or state-based redirects are your allies. These enable you to trigger functions once the new page loads:

document.addEventListener('DOMContentLoaded', secretFunctionPostRedirect); // Wakey wakey eggs and bakey!