How do you redirect to a new page in JavaScript?
TL;DR
For a browser navigation, use location.assign(url) (or assign location.href) when Back should return to the current page, and location.replace(url) when the current entry should be replaced, such as after completing a one-time login step. Prefer an HTTP redirect when the server already knows the destination; it works without JavaScript and avoids loading a page only to navigate away.
Validate destinations derived from query parameters against trusted same-origin paths or an explicit origin allowlist to prevent open redirects.
// Using window.location.hrefwindow.location.href = 'https://www.example.com';// Using window.location.replace()window.location.replace('https://www.example.com');
How do you redirect to a new page in JavaScript?
Using window.location.href
The window.location.href property is used to get or set the URL of the current page. When you set this property, the browser will navigate to the new URL, and it will create a new entry in the browser's history.
window.location.href = 'https://www.example.com';
Using window.location.replace()
The window.location.replace() method is similar to window.location.href, but it does not create a new entry in the browser's history. This means that the user cannot use the back button to return to the original page.
window.location.replace('https://www.example.com');
Using window.location.assign()
The window.location.assign() method works similarly to window.location.href and creates a new entry in the browser's history.
window.location.assign('https://www.example.com');
Using window.location.reload()
If you want to reload the current page, you can use the window.location.reload() method. This method can be useful if you want to refresh the page without changing the URL.
window.location.reload();
Using window.history.pushState()
For a single-page application, window.history.pushState() changes the displayed same-origin URL and adds a history entry without loading a new document. It is not a redirect: application code must render the new route and handle popstate for Back and Forward navigation.
window.history.pushState({}, '', '/new-page');
Further reading
- MDN Web Docs: Window.location
- MDN Web Docs: Window.location.href
- MDN Web Docs: Window.location.replace()
- MDN Web Docs: Window.history.pushState()