How to Debug JavaScript Redirects That Send Visitors to the Wrong Page

Debug JavaScript redirects to the wrong page by tracing document requests, router rules, base URLs, authentication state, and browser history.

Published
Reading time
9 min read
How to Debug JavaScript Redirects That Send Visitors to the Wrong Page
On this page

A visitor lands on the wrong page, but the redirect code you expected to run never appears in the stack trace. The first task is to determine whether the server redirected the initial document, JavaScript initiated a navigation, or a client-side router changed the displayed route without loading a new document.

This guide walks through a browser-based diagnostic sequence, then examines route rules, base URLs, authentication state, and navigation behavior. Developer tools labels vary by browser, and the examples below have not been executed in this environment.

Key Takeaways

  • Record the navigation with developer tools open and Preserve log enabled. Inspect the initial document request before assuming JavaScript is responsible.
  • A top-level HTTP redirect and a redirect on a background fetch request are different events. A redirect on a background request does not by itself mean the browser redirected the page.
  • For client-side routing, inspect route guards, route matching, URL construction, and the state available when the router runs.
  • Check signed-in and signed-out flows separately. A client-side route guard is not a substitute for server-side authorization.
  • Prefer navigation initiated by a clear user action when possible; choose history behavior deliberately and announce client-side page changes accessibly.

1. Capture the navigation

Reproduce the issue in a controlled session, using an account and environment you are authorized to inspect.

  1. Open browser developer tools before loading the problematic URL.
  2. Open the Network panel and enable Preserve log, so requests remain visible across navigations. Optionally enable Disable cache while developer tools are open; note that this does not necessarily bypass a service worker.
  3. In the Address bar, enter the exact starting URL, then reproduce the same action the visitor took. Record the starting and final URLs and whether the page visibly reloads.
  4. In Network, select the initial request whose type is document. Inspect its status and response headers. Follow any subsequent document requests in order.
  5. Then inspect requests immediately before the wrong destination appeared, including document requests and relevant fetch or XHR requests. Check the initiator or call stack where the browser provides one.

Look at the response headers for redirect statuses such as 301, 302, 303, 307, or 308 and a Location header. A 304 Not Modified response concerns cache validation; it is not a redirect to a new page. A request can also be served from cache or by a service worker, so inspect the response source and service worker configuration if the result differs from a clean session.

Interpret the evidence

ObservationWhat to investigate next
The initial document returns a redirect status and Location points to the wrong URL.Server, CDN, reverse proxy, or service worker redirect rules. Check each hop; JavaScript has not caused that particular HTTP response.
The initial document returns HTML, then a new document request appears.JavaScript, a form submission, a link, or an HTML meta refresh may have initiated a later navigation. Inspect its initiator and the original HTML.
The URL or page content changes without a new document request.Client-side router, history.pushState() or history.replaceState(), or application state. Also check whether the page merely rendered different content at the same URL.
A background request receives a redirect, but the document remains in place.Inspect how the application handles that response. Do not assume the background redirect itself navigated the top-level page.

A page can use more than one mechanism: for example, an HTTP redirect may be followed by a JavaScript navigation. Trace the whole chain rather than stopping at the first hop.

Advertisement

2. Separate server behavior from browser behavior

To inspect the initial server response independently, make a GET request without automatically following redirects:

curl -sS -D - -o /dev/null 'https://example.test/start'

Replace the URL with one in your own test environment. The command prints response headers and discards the body. If the response is a redirect, inspect its Location; request the next URL separately if you need to trace further hops. Avoid using -L for the first check, because it follows redirects and can obscure which hop returned which response.

This is a comparison, not a reproduction of every browser condition. The browser may send different cookies or headers, use a service worker, execute JavaScript, or have cached state. Do not paste production cookies, authorization headers, or sensitive URLs into tickets or shared logs. A HEAD request such as curl -I can also behave differently from the browser's GET request.

If the initial document is HTML, inspect its response body for a meta refresh and examine its loaded scripts. In the Sources panel, enable source maps if they are available, then search your application code for navigation calls and router guards. Useful search terms include:

location.assign
location.replace
location.href
history.pushState
history.replaceState

Also search for your framework's router navigation and redirect APIs. Set breakpoints at likely call sites and reload with developer tools open. Inspect the call stack and the values used to select the destination. If the navigation happens too early to catch, use a breakpoint in the relevant startup or route-guard code rather than relying only on console output after the page has left.

For a client-side transition, compare window.location.href before and after the action. A router can change the URL using the History API without requesting a new document, so an empty document-request list does not prove that no route change occurred.

3. Check route rules and base URLs

Stale or conflicting route rules

Trace the requested path through the rules in the order your router actually applies them. Look for an old alias, wildcard or fallback that matches before a more specific route, a renamed path still used in a redirect, or different route configurations in deployed bundles. Also check server rewrite rules: a correct client route can still fail if a direct request is redirected or not served the application shell.

To isolate the mismatch, record:

  • The exact starting pathname, query string, and fragment.
  • The matching rule and the destination it computes.
  • The deployed asset version or build identifier, if your application exposes one.
  • Whether a hard reload, a client-side link, and a Back/Forward navigation produce the same result.

Do not assume every router uses first-match semantics; verify the matching behavior and configuration for the router version your application uses.

Incorrect base or relative URLs

A missing trailing slash can change how a relative URL resolves. This example uses the browser's URL constructor to make the difference visible:

console.log(new URL('settings', 'https://example.test/app').href);
// https://example.test/settings

console.log(new URL('settings', 'https://example.test/app/').href);
// https://example.test/app/settings

In the first case, app is treated as the final path segment and replaced. In the second, app/ acts as a directory. Inspect document.baseURI, the document's <base> element if present, the current URL, and any router base-path configuration. The correct base depends on the API or router constructing the destination; test the actual navigation path rather than assuming all APIs use the same base.

For an application hosted beneath a prefix such as /app/, verify links, redirects, asset paths, and server rewrites against that deployment prefix. A root-relative path such as /settings starts at the origin's root, not automatically at /app/.

Advertisement

4. Compare signed-in and signed-out flows

Reproduce each state in a separate test session, then compare the document and network sequence:

  1. Start signed out and load the original URL directly.
  2. Sign in with a test account and repeat the same direct load.
  3. Repeat through an in-app link and, if relevant, immediately after a fresh login or logout.
  4. At the route guard or destination-selection code, inspect the authentication state available at that moment and whether it has finished loading.

A common timing problem is treating an unresolved session check as signed out. The guard redirects to login before the session request completes, even though the user has a valid session. Consider an explicit loading state and make the decision only once the application's authentication state is known. Also check whether a stale cookie, cached session result, or outdated client bundle changes the branch taken.

If the application preserves a return destination after login, validate it against allowed local paths or a strict allowlist before navigating. Do not blindly navigate to a URL taken from a query parameter: that can create an open redirect. The server must still authorize access to the destination and its data; hiding a route or redirecting in client code is not an access-control boundary.

5. Check history and accessibility

Use navigation behavior that matches the user's expectation. An ordinary link is often the right choice when a user chooses a destination: it has a meaningful href, works with keyboard and browser features, and permits opening in a new tab. Avoid surprising automatic navigation, particularly while someone is reading, entering data, or using assistive technology. If an automatic transition is necessary for the workflow, explain it and preserve user input where feasible.

History also affects whether users can recover. A normal navigation or pushState() can create a history entry; location.replace() and replaceState() replace the current entry. Replacement can be appropriate for an obsolete intermediate URL, but using it indiscriminately can make the Back button skip a page users expect to revisit. Test Back and Forward through login, redirects, and client-side transitions rather than selecting an API solely to suppress a redirect loop.

For client-side route changes, update the document title and manage focus so keyboard and screen-reader users can discover the new page. Depending on the application, that may mean moving focus to a suitably focusable main heading or announcing a meaningful change through an appropriate live region. Test with keyboard navigation and assistive technology; avoid moving focus for minor updates that do not represent a page change.

Common Mistakes

  • Inspecting only the final URL. The wrong destination may have been chosen several hops earlier.
  • Treating every network redirect as a page redirect. Check whether the redirected request is the top-level document or a background request.
  • Testing only with a warm session. Cached assets, service workers, and authentication state can conceal a clean-session failure.
  • Fixing a symptom with an unconditional redirect. Identify the matching rule and the state that produced the destination first; otherwise you may introduce a loop.
  • Assuming a local-path check is authorization. Validate return destinations and enforce access on the server.

Best Practices

Keep a small regression matrix covering direct loads and in-app navigation, signed-in and signed-out states, the production base path, and Back/Forward behavior. Add cases for trailing slashes, unknown routes, and login return destinations where applicable.

During diagnosis, log only what is necessary, such as a route name, a non-sensitive pathname, the rule selected, and whether session state was resolved. Avoid recording tokens, credentials, or full URLs that may contain private query parameters. Retest after deployment, including with a clean session, because cached assets or service worker behavior can differ from local development.

Conclusion

Start with the initial document request, trace every later navigation, and then inspect the rule and state that selected the destination. Verify the fix across authentication states, deployment paths, and browser history so the correct page is also reachable and usable.

What would your domain sell for?

A free TidyURLs account unlocks the Domain Estimator. It prices a name from 191,011 real domain sales.