When you redirect a user in JavaScript, the new page is usually added to the browser’s history — which means the user can click the Back button to return. But sometimes, you don’t want that — for example, after logout or form submission. In such cases, you can use window.location.replace()
to redirect without storing the current page in history.
This article explains how to use location.replace()
with examples and common use cases.
What is window.location.replace()
?
window.location.replace()
is a JavaScript method that redirects the user to a new URL, without leaving the current page in the browser’s history.
Syntax:
What it does:
Navigates to the given URL and replaces the current page in history, so pressing "Back" will not return to it.
Example: Redirect Without Back Option
What happens:
The user is redirected to the homepage, but cannot press "Back" to return to the logout page.
When to Use location.replace()
-
After user logout
-
After form submission to prevent resubmission on refresh
-
To bypass a page users shouldn’t return to (e.g. a loading screen or checkout success page)
-
When using OAuth redirects or single-use pages
Difference Between location.replace()
and location.href
Feature | location.href | location.replace() |
---|---|---|
Adds to history? | ? Yes | ? No |
Can go back? | ? Yes | ? No |
Reload page? | ? On redirect | ? On redirect |
Use case | Normal navigation | Secure/controlled redirection |
-
The user cannot go back to the previous page using the Back button after a
replace()
redirect. -
location.replace()
behaves like changinghref
, but without leaving a trace in browser history. -
It's supported in all modern browsers.
Summary
Use window.location.replace()
in JavaScript when you want to redirect a user without keeping the current page in the browser history. It’s ideal for logout flows, payment redirects, and one-time screens.
Key Takeaways:
-
Redirects the user without saving current page in history
-
Prevents users from returning using the Back button
-
Best used for secure, one-way flows like logout or success pages