On this page
A JavaScript redirect browser back button loop often happens when a page adds its destination to the history stack, then redirects again whenever the user goes back to it. This guide shows a minimal reproduction, how to replace the redirect entry, and when History API methods are appropriate instead.
Key Takeaways
location.assign()andlocation.href = ...normally navigate to a new document while keeping the current entry in session history.location.replace()navigates without keeping the current entry as a separate Back destination. It is often appropriate for an obsolete URL that should always redirect.history.pushState()andhistory.replaceState()update the current document's history state and URL without loading a new document. They are not substitutes for an actual cross-document redirect.- Handle Back and Forward deliberately in client-side routers. Repeated redirects can disorient keyboard and assistive-technology users as well as trap mouse users.
How a redirect creates a Back-button loop
Consider this sequence, assuming normal history behavior:
- A user visits
/start.htmland follows a link to/old.html. /old.htmlimmediately useslocation.assign('/new.html').- The user presses Back from
/new.htmland returns to/old.html. - The redirect runs again, sending the user back to
/new.html.
The browser may apply navigation-intervention heuristics, so behavior can vary. The underlying problem remains: the intermediate page is a Back destination but cannot remain visible when revisited.
Advertisement
Reproduce the loop locally
Create these three files in the same directory. The example uses a local HTTP server so the root-relative paths resolve consistently.
start.html:
<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><title>Start</title></head>
<body>
<h1>Start</h1>
<a href="/old.html">Open the old page</a>
</body>
</html>
old.html:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Old page</title>
<script>
window.location.assign('/new.html');
</script>
</head>
<body>
<p>This page redirects to the new page.</p>
</body>
</html>
new.html:
<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><title>New page</title></head>
<body>
<h1>New page</h1>
<p>Try the browser's Back button.</p>
</body>
</html>
With Python 3 installed, start a server from that directory:
python3 -m http.server 8000
Open http://localhost:8000/start.html, select the link, and then press the browser's Back button. In the usual sequence, Back revisits old.html, whose script sends you to new.html again. Browser history optimizations can affect the observed result.
Fix an unconditional redirect with replace()
In old.html, replace the assign call with:
window.location.replace('/new.html');
Now the navigation to new.html replaces the old.html entry rather than leaving it immediately behind the destination. In the example, Back should return to start.html instead of repeatedly revisiting the redirect page.
Use this pattern when the old page is an intermediate URL the user should not return to, such as a permanently moved client-side route. It changes only the current history entry; it does not erase earlier visits to the old URL elsewhere in the stack. If you control the server, an HTTP redirect may be a better way to move a URL, including for clients that do not execute JavaScript. Check the resulting browser history behavior in your supported browsers.
If the user needs to return to the original page—for example, to edit a form—preserving that entry may be correct. In that case, prevent an automatic redirect from firing again on return, or offer an explicit link rather than redirecting unconditionally.
Advertisement
Choose the right navigation API
| Operation | Document navigation | Effect on history |
|---|---|---|
location.href = '/new.html' | Navigates to the destination | Normally adds a destination entry, leaving the current page behind it. |
location.assign('/new.html') | Navigates to the destination | Normally adds a destination entry, like assigning href. |
location.replace('/new.html') | Navigates to the destination | Replaces the current entry with the destination. |
history.pushState(state, '', '/route') | Does not load a document | Adds an entry for the current document. |
history.replaceState(state, '', '/route') | Does not load a document | Updates the current entry without adding one. |
The History API methods are useful for a single-page application that renders its own routes. Their URL argument must be compatible with the current document's origin, and the state must be serializable. They do not fetch or render a page for you. Configure the server to serve the application for its routes on a direct visit or reload.
For example, an existing router might add a user-initiated route and render it:
// Illustrative integration with an existing application router.
function navigate(path) {
history.pushState(null, '', path);
renderRoute(location.pathname);
}
window.addEventListener('popstate', () => {
renderRoute(location.pathname);
});
Here renderRoute is an application-specific function, not a browser API. The application must also render the initial route on page load. Calling pushState or replaceState does not itself dispatch popstate; the listener handles history traversal, such as Back or Forward, between relevant entries. Do not call pushState again on every popstate, or the router can create another navigation trap. Use replaceState for corrections to the current route that should not create a separate Back step.
Keyboard and assistive-technology considerations
Unexpected navigation can interrupt reading, move focus, and make the current location difficult to understand. A user relying on a keyboard or screen reader needs predictable Back and Forward behavior just as much as a pointer user.
- Prefer a normal link for a user-initiated change of page. It supports native keyboard activation and exposes a destination.
- For a full-document redirect, ensure the destination has a descriptive document title and heading. Avoid chaining redirects unnecessarily.
- For client-side route changes, update the document title and ensure the new content is perceivable. Depending on the application, move focus to a suitable heading or main content area, or use a concise live-region announcement. Avoid redundant announcements and unexpected focus changes during routine updates.
- Check Back and Forward with keyboard navigation and a screen reader. Verify that focus is usable, the destination is identifiable, and repeated traversal does not trigger another redirect.
Common Mistakes
- Using
assign()for an intermediate page that always redirects. Back can revisit that page and trigger the same redirect again. - Using
pushState()as if it loaded the target URL. The address changes, but your application still needs to render the route. - Redirecting on every
popstate. This can undo the user's Back action or grow the history stack. Render the requested history entry instead, unless a clearly defined route rule requires otherwise. - Assuming
replace()clears all history. It replaces the current entry, not every earlier occurrence of a URL. - Redirecting to an unchecked URL parameter. If a destination comes from user input, restrict it to approved destinations to avoid an open redirect.
Best Practices
- Reproduce the sequence from a known starting page and record the expected Back and Forward destinations.
- Use
replace()for a disposable redirect entry; retain history when returning to the prior page is part of the intended workflow. - Test direct visits, reloads, Back, and Forward in supported browsers. Include cases where a page is restored from the back-forward cache rather than freshly loaded.
- For SPA routes, coordinate history updates, rendering, title changes, and accessible focus or announcements. Avoid duplicate entries for the same logical transition.
Conclusion
A redirect loop is usually a mismatch between the history entry your code creates and the entry the user expects to revisit. Replace a disposable redirect entry, or make a preserved page safe to return to. For client-side routing, treat history traversal as a request to restore the route, not automatically as a new navigation.
Research and execution note: MDN's Location and History API documentation could not be retrieved in this environment, and the examples were not executed here. Consult the current MDN pages and test the behavior in your supported browsers before deployment.
What would your domain sell for?
A free TidyURLs account unlocks the Domain Estimator. It prices a name from 191,011 real domain sales.