How to redirect to another page
Short answer
Assigning an address to location.href opens it, like clicking a link:
window.location.href = '/thank-you';Without a history entry
location.replace() replaces the current page in history, so the Back button does not return to it. That is useful after a login or a form submission:
window.location.replace('/dashboard');A new tab and reloading
window.open() opens a new tab, location.reload() reloads the current page:
window.open('https://example.com', '_blank', 'noopener');
location.reload();Common mistake
If the address comes from a parameter, check it before redirecting. Otherwise anyone can make a link to your site that sends users to a fake page:
const next = new URLSearchParams(location.search).get('next') ?? '/';
if (next.startsWith('/') && !next.startsWith('//')) {
location.href = next;
}Functions used in this recipe
- URLSearchParams — Reads and builds URL query parameters (the part after ?).