How can a React HTTP interceptor navigate to login after a 401 while pages keep their props?

May 4, 2025

When I added login to AssetMan, my asset management app, I needed navigation in two places. After a successful login, the form could send the user straight to the assets page. But if a session expired while someone was editing an asset, the first code to know about it was an HTTP response interceptor, a callback shared by the pages that use the HTTP client. I wanted that callback to decide when to send the user back to login.

The assets page already worked. Its parent, App, owned the list and the current filter and passed them to AssetPage as props. I wanted to keep that interface while giving the HTTP client a way to navigate from outside React.

What happens when the router sends someone back to login?

Suppose I’m viewing asset 42 at /assets/42. A request returns 401, the app can’t refresh the token, and the interceptor decides to send me to /login. With the browser history routing I used in AssetMan, three things happen:

  1. Update the URL and the history entry. The router can use history.pushState() to add an entry for /login, or history.replaceState() to replace the current entry for /assets/42. Both update the address bar.
  2. Notify the app. Calling either method directly does not fire a popstate event, so a router that writes to history must also notify components subscribed to the location. When the user clicks Back or Forward, the router can listen for popstate.1
  3. Render the login page. The app reads the new path and renders the matching component. The interceptor only has to initiate the navigation.

📓 Note: Hash routing follows the same steps but stores the path after the #, for example when moving from /#/assets/42 to /#/login. Opening the asset link directly sends the server a request for /. If server-side rendering (SSR) needs to return the HTML for asset 42, the server needs a way to identify the asset from the request. The fragment alone can’t do that.2

💡 Tip: After deploying a single-page app that uses browser history, open a detail page and refresh it. If clicking through to /assets/42 works but refreshing gives you a 404, configure the server to serve the app’s index.html at that path. Keep /assets/42 in the address bar so the app can match the detail page when it starts.

Can a page still receive ordinary props in React Router?

Yes. Once the router knows the current location, it needs a mapping from paths to components. In React Router v7’s Declarative Mode, you can write that mapping in JSX with <Routes> and <Route>. In Data Mode, you can pass route objects to createBrowserRouter([{ path, element }]) and configure data loading and form submissions on the routes. Framework Mode adds tooling, including a Vite plugin, on top of Data Mode.3

For example, if App is already inside a <BrowserRouter>, it can render this JSX. I’ve adapted the example to show just the assets route.4

<Routes>
  <Route
    path="/assets"
    element={
      <AssetPage
        assets={assets}
        setAssets={setAssets}
        filterStatus={filterStatus}
        setFilterStatus={setFilterStatus}
      />
    }
  />
</Routes>

The element prop accepts a React element, so App can pass values to AssetPage in the usual way. The route determines when to show the page. The page receives a list, a filter and two callbacks. I can put it in another layout or render it in a test with a few sample assets using the same props. The private routes tutorial I read had a smaller example of this, with <Home user={user} /> supplied as the route element.5

On April 23, I tried defining four route objects at the top of main.jsx and passing them to createBrowserRouter. One entry was { path: "assets", element: <AssetPage /> }. That element can take props too. The difficulty was scope: the code that constructed the element had no access to the assets state inside App. That was what led me to ask how a parent could pass data through an Outlet.6

Who initiates navigation when an interceptor receives a 401?

In the UI, a “Back to assets” link can be a <Link>, and the navigation menu can use <NavLink> to highlight the active page. A login form that handles its own submission can get a function from useNavigate() and call it when the request succeeds. Data and Framework modes also support submitting a <Form> to a route action, which can return redirect('/assets') after saving.7

It’s tempting to call redirect('/login') in an interceptor because it’s an ordinary function. The important part is who receives its return value. It creates a redirect response. A router that receives it from a loader or action can carry out the navigation. Returning the same response to the application code that issued a Fetch request leaves the browser at its current address. My interceptor needed a function that could actually initiate navigation.78

An interceptor can call a navigation function it already has. It can’t call a React Hook when a response arrives. That leaves a practical question: how does the HTTP module get a function to call?89

Routing setupHow the assets page gets its propsHow the interceptor navigates
React Router, declarative JSX routes inside AppSet the route’s element to <AssetPage assets={assets} />.Call useNavigate() in a component under the router. When registering the interceptor, pass a callback such as () => navigate('/login', { replace: true }).
React Router, data routes defined at the top of main.jsxThe route table can’t read local state in App. A child route can read it from outlet context and pass the original props to the page.Give the HTTP module the instance created by createBrowserRouter(...). It can then call router.navigate('/login', { replace: true }).
wouter with default browser routingApp reads the path with useLocation() and renders <AssetPage assets={assets} /> as before.Import navigate directly from wouter/use-browser-location.

One way to wire up the first option is to mount a component that returns null. Its effect registers the interceptor and its cleanup removes it, tying registration to the React tree. With the second option, calling createBrowserRouter(...) outside React gives you a JavaScript object with a navigate method. The entry point passes it to <RouterProvider router={router} />, and the interceptor can use that same object. The third option suited my browser app. The wouter FAQ even had my question as a heading: “Can I initiate navigation from outside a component?”9

In wouter 3.7 the top-level <Router> is optional. AssetMan renders <App /> directly, so a component’s useLocation() uses the default browser location. The separately exported navigate writes to browser history. With the defaults, both reach /login. A configured base path changes this: under <Router base="/app">, the hook’s navigate('/login') goes to /app/login, while the standalone function still goes to /login.9

Why did React Router move from direct history access to navigate?

Passing my app’s router instance to an HTTP module felt roundabout for a single redirect. JavaScript already has access to browser history. A routing library can update it and notify the page through a standalone API. I remembered doing something like this with early React Router. The v3 guide actually used middleware as its example: pass the exported browserHistory to <Router> at startup, then import browserHistory from the same package in middleware and call browserHistory.push('/login'). The application didn’t have to store or forward a separate reference.10

The change came well before v7. By v4.3.1, <BrowserRouter> created its own history object. An application could still share a custom history object by supplying it explicitly to the lower-level <Router>.11

The v6 upgrade guide gives one reason for moving to navigate. Suppose I click asset A in a list, then click B while A is still loading. When I press Back from B, I expect to see the list I was reading. If each click immediately adds a history entry, Back takes me to A, a page I never got to see. A router that knows the first navigation is pending can replace its entry when the second click interrupts it.12

From v6.4 on, data routers also coordinate loading with URL updates. After a click, the router can wait for the detail data before committing the destination. When the user presses Back, the address has already changed by the time popstate fires. The router handles both cases. In v7 Data Mode, code outside React can still initiate navigation by calling router.navigate('/login') on the application’s router instance.138

How I passed a navigation function to an HTTP handler with a singleton

In 2023 I ran into this problem in ArticlePostFrontend, an app for publishing articles. I wanted pages to share one HTTP handler that cleared the login state and sent the user to login after a 401. My first attempt called redirect("/login") in an ordinary response callback. There was no route loader or action there to hand the redirect response back to the router.14

I initially called useNavigate() in App and tried to store the result in a singleton. But App itself returned the <BrowserRouter> in its JSX. Only components under that router could read its context. On December 2, 2023, I moved the assignment into the root route’s existing Layout. It already rendered the navbar and child pages, so I had it store the function after mounting. Here’s the component from that commit.1514

const Layout = () => {

  const navigate = useNavigate()

  useEffect(
    _ => {
     NavigateSingleton.getInstance().setNavigate(navigate)
    }
  )

  return (
    <>
      <Navbar />
      <Outlet />
    </>
  )
};

I put NavigateSingleton in its own module so that both Layout and the HTTP handler could import it. This is the full implementation.16

const NavigateSingleton = (function () {
  let instance
  let navigate

  function init() {
    return {
      getNavigate: function () {
        return navigate
      },
      setNavigate: function (nav) {
        navigate = nav
      }
    }
  }

  return {
    // Get the shared instance
    getInstance: function () {
      if (!instance) {
        instance = init()
      }
      return instance
    },
  }
})()

export default NavigateSingleton;

When the module loads, the outer function runs once, leaving two variables in its closure. On the first call to getInstance(), init() creates the object with the getter and setter, and the code saves it in instance. When Layout calls setNavigate(navigate), it saves the hook’s function in the other variable, navigate. Later, the HTTP handler gets the same object from getInstance() and retrieves the stored function with getNavigate().

In the same commit, I replaced the HTTP handler’s redirect("/login") with the following code. The hook runs when the layout renders. The actual navigation can happen later, when the HTTP response arrives.14

if (res.status === 401) {
    logoutAndClean()(dispatch)
    alert("Session expired. Please login again.")
    let navigate = NavigateSingleton.getInstance().getNavigate()
    navigate("/login")
}

In March 2024 the same lookup appeared in an interceptor I wrote for myxios. On April 24, 2025, AssetMan was already using wouter’s useLocation() for page changes, but an interceptor draft still contained that getNavigate() call. ArticlePostFrontend preserves both ends of the handoff. The AssetMan draft shows the part that retrieved the function.1718

Why I chose wouter over keeping the singleton

What I wanted to keep was the HTTP handler. Both listing articles and creating one went through HttpHandler, so I could write the 401 policy once. The singleton’s job was to pass navigate across. What bothered me was having to trace getNavigate() all the way back to an effect in Layout to find out where the function came from. There was also an ordering requirement between those modules: the layout had to store the function before the handler could call it.1416

In AssetMan I tried the data-router alternative. As long as the interceptor had the application’s router instance, it could call router.navigate('/login') directly. That left the page itself. With the route table at the top of main.jsx, how would I get the four values from App into AssetPage?68

Before the proposed change, App rendered the page and passed its props directly. This is the approach the project kept. The list, filter and both setters are in scope right where the component is rendered.19

// App.jsx
<main>
  {activePage === 'assets' && (
    <AssetPage
      assets={assets}
      setAssets={setAssets}
      filterStatus={filterStatus}
      setFilterStatus={setFilterStatus}
    />
  )}
</main>

With the top-level route table, App could render an Outlet in the same place. Here’s how I could have adapted the draft for the assets route. Matching /assets would select the page, replacing the activePage === 'assets' check. The child route would explicitly read the context supplied to the outlet.620

// App.jsx: replace the page selection inside <main>
<main>
  <Outlet context={{ assets, setAssets, filterStatus, setFilterStatus }} />
</main>
// main.jsx: the route table stays at module scope
const router = createBrowserRouter([{
  path: "/",
  element: <App />,
  children: [{ path: "assets", element: <AssetRoute /> }],
}]);

function AssetRoute() {
  const { assets, setAssets, filterStatus, setFilterStatus } = useOutletContext();
  return (
    <AssetPage
      assets={assets}
      setAssets={setAssets}
      filterStatus={filterStatus}
      setFilterStatus={setFilterStatus}
    />
  );
}

The draft originally specified element: <AssetPage />. Substituting <AssetRoute /> here keeps the React Router dependency in the route component. It reads the outlet context and passes four ordinary props to AssetPage.

I could also skip AssetRoute and call useOutletContext() inside AssetPage. I didn’t like that coupling. With <AssetPage assets={assets} />, any parent can supply the list. With a React Router hook, the page has to get its data from an enclosing <Outlet>. Switching routers would mean editing the assets page even if nothing about displaying or filtering assets had changed.20

My recollection is that reading the early React Router docs changed the question for me. If v3 middleware could call browserHistory.push('/login') directly, navigation from outside a component was clearly possible. The later design could handle a case I understood: click B while A is still loading, then press Back and skip the A you never saw. That guarantee was worth having, but in AssetMan I could live with the extra history entry. Was there still a lightweight router that exported a navigation function I could call directly? I remember someone mentioning that they used wouter. On April 23, I reached its repository from a Hacker News discussion of the merger and then again from an article comparing router alternatives.101221

Wouter 3.7’s default browser navigation made exactly that tradeoff: each call wrote to history immediately. App could keep passing props to AssetPage in JSX, and the shared HTTP module could import navigate directly. For a few screens and a login redirect, passing a router instance into the HTTP client or making a page read its own data through a router-specific hook felt overengineered to me.221923

When did the interceptor start using wouter’s standalone navigate?

The pages used wouter on April 24, while the interceptor draft still read from the singleton. On April 25, I moved the interceptor out of a component effect into the shared HTTP module. Its failure branches still referred to the component’s setIsLoggedIn and navigate. On May 4, I imported navigate from wouter/use-browser-location in that module. It could then clear the user and go to login on an unrecoverable session without waiting for a component to supply the function. This excerpt keeps the full path for a missing refresh token and the line that registers the interceptor.2423

import myxios from "myxios";
import { navigate } from "wouter/use-browser-location";

export const myxiosInstance = myxios;

const notAuthorizedInterceptor = (res) => {
  const originalResponse = res[0];
  const refresh = JSON.parse(localStorage.getItem("user"))?.refresh;

  if (originalResponse.status === 401) {
    if (refresh !== undefined && refresh !== null) {
      // Returned promise chain omitted: retry the original request after a successful refresh.
      // On an unsuccessful refresh response, clear the stored user and go to login.
    } else {
      localStorage.removeItem("user");
      navigate("/login", { replace: true });
    }
  }
  return Promise.resolve(res);
};

myxiosInstance.addResponseInterceptor(notAuthorizedInterceptor);

With replace: true, the login page replaces the current history entry. Otherwise, a user redirected from /assets could press Back and land straight back at that address. In my implementation App watches the location, updates its login state when the path becomes /login, and renders the login page. The HTTP client decides whether a request can be retried, and React decides which page to show. I wrote separately about preserving headers and request bodies when retrying with Fetch (in Chinese).23

What does importing a shared router pull into a bundle?

Suppose router.js imports the assets page, which imports the HTTP client. If the client imports router from ./router.js, the imports form a cycle: router.js → assets page → http.js → router.js. The modules can initialize successfully if the interceptor only reads router later, when a 401 arrives. Trying to read the binding during top-level interceptor registration can throw a ReferenceError if it hasn’t been initialized. Having the entry point supply an onSessionExpired callback to the HTTP client removes that last import.25

When I revisited the code, I built a two-entry example with Vite 6.3.0. One entry launched the React app, the other displayed service status. Both used the HTTP module. I followed the static imports from the status entry through the production bundles.26

How the HTTP client handles an expired sessionHow the router loads the assets pageApplication code loaded with the status page
Imports the app’s routerStatic importHTTP module, route table and assets page
Imports the app’s routerLazy import()HTTP module and route table. The assets page stays in its own async chunk.
Receives a callback from the entry pointStatic or lazy importOnly the HTTP module. The route table and assets page stay on the React app side.

In a single-entry app that already needs the whole route table at startup, sharing a router instance may add no files at all. The difference showed up here because the status page otherwise had no use for the route table. Wouter’s standalone navigate comes from its browser location module, which has no imports from my pages or route configuration.

Whether a 401 causes a loop depends on what happens after navigation. Clearing the session and going to login can end the sequence. A loop is possible if mounting the login page triggers a protected request, that request returns 401, and navigating makes it run again. Passing a callback can break an import cycle, but the callback can still change the location. In AssetMan the interceptor clears the stored user and navigates to login. The component watching the location sets the login state to false, and that branch ends there. The refresh request uses native fetch, so a 401 from the refresh endpoint doesn’t recursively enter the shared client’s interceptor.23

Why I’d choose a routing library and a full-stack framework separately

Once the interceptor could call navigate('/login') directly, AssetMan’s immediate problem was solved. The decision left me with a broader conviction: standalone routers and full-stack web frameworks serve two markets with clear requirements, and the same design choice can have opposite value in each.

While choosing a router, I read the React Router roadmap and the Remix migration guide. My impression was that the team wanted to build a full web framework. I had opened the docs to find out how to get from the assets page to login. Following them further meant considering which route should load the data, which action should handle a form, and how the app should be built.2728

Take the question of when to change pages. Once my interceptor knows the session has expired, it already has enough information to send the user to login. I want it to do that directly while the assets page keeps receiving its props. If I build another client, I want to reuse the filtering rules and the decision that a session has expired. Each platform can supply its own way to open the login screen. That’s what lightweight, portable routing buys me. When I choose a full-stack framework, I’m willing to hand over more of those decisions. If I click asset A and then B while A is loading, I want the framework to know which request still matters, which page to show, and where Back should take me. To make those guarantees, it has to coordinate loading, rendering and history. That coordination is a reason I’d choose a framework. It’s also the dependency I want to avoid when all I need is routing.1213

That’s why I think positioning React Router itself as a framework was a mistake. For a full-stack web application, the team already had Remix, and Next.js had a substantial lead among respondents to the State of JavaScript survey. I’d compare those two first. For adding routes to an existing client, I’d start with a lightweight library like wouter. React Router still offers both Declarative Mode and Framework Mode, but once I pin down which problem I’m solving, I struggle to name a case where it would be my first choice. That’s how I think it risks losing users in both markets.329

References

Footnotes

  1. MDN contributors. (n.d.). Window: popstate event and Window: hashchange event. MDN Web Docs. The history stack and fragment changes. ↩

  2. React Router contributors. (2025). History (v7.5.0) [Source code]. GitHub. Browser and hash history implementations. See also MDN contributors. (n.d.). URI fragment. MDN Web Docs. Fragments and HTTP requests. ↩

  3. React Router contributors. (2025). Picking a Mode (v7.5.0). GitHub. Declarative, Data, and Framework modes. ↩ ↩2

  4. React Router contributors. (2025). Routing (v7.5.0). GitHub. Configuring Routes and Nested Routes. ↩

  5. Wieruch, R. (2025, January 6). React Router 7: Private Routes (alias Protected Routes). Robin Wieruch. The login example passing user to Home. ↩

  6. borui. (2025, April 23). React Router main.jsx [AssetMan entry-point draft preserved in the frontend README]. GitHub. Nested routes and RouterProvider. ↩ ↩2 ↩3

  7. React Router contributors. (2025). Navigating (v7.5.0). GitHub. Links and useNavigate in Declarative Mode, Form and redirect in Framework Mode, and the Data Mode guide. ↩ ↩2

  8. React Router contributors. (2025). React Router (v7.5.0) [Source code]. GitHub. useLocation and useNavigate and the router instance’s navigate interface. ↩ ↩2 ↩3 ↩4

  9. molefrog and contributors. (n.d.). wouter (v3.7.0). GitHub. “Can I initiate navigation from outside a component?”, first paragraph and example. ↩ ↩2 ↩3

  10. React Router contributors. (n.d.). Navigating Outside of Components (v3.0.5). GitHub. Sharing browserHistory between the app and middleware. ↩ ↩2

  11. React Router contributors. (n.d.). BrowserRouter.js (v4.3.1) [Source code]. GitHub. Creating history and supplying custom history. ↩

  12. React Router contributors. (n.d.). Upgrading from v5. React Router v6.30.1. “Use useNavigate instead of useHistory,” discussion of interrupted navigation. ↩ ↩2 ↩3

  13. React Router contributors. (n.d.). Remixing React Router [Decision 0005]. GitHub. “Inline the history library into the router,” timing of PUSH, REPLACE and POP. ↩ ↩2

  14. borui.cai. (2023, December 2). Refactor to fix httphandler redirect feature [Commit b1f0a5d]. GitHub. Layout storing the function and rendering Navbar and Outlet and HttpHandler retrieving the function. ↩ ↩2 ↩3 ↩4

  15. borui.cai. (2023, December 2). Refactor to make app home public and allocate a private route for create article [Commit e75863b]. GitHub. App calling the hook and rendering BrowserRouter. ↩

  16. borui.cai. (2023, December 2). NavigateSingleton.js [Source code]. GitHub. Closure, getter, setter and getInstance. ↩ ↩2

  17. borui.cai. (2024, March 11). Epoch [Commit 3ef1e4b]. GitHub. Importing the singleton and looking up the function after a failed refresh. ↩

  18. borui. (2025, April 24). Add login feature; add router using wouter [Commit b94e7c7]. GitHub. App switching pages by path and navigation after a successful login. ↩

  19. borui. (2025, April 24). Add login feature; add router using wouter [Commit b94e7c7]. GitHub. App rendering AssetPage with four props. ↩ ↩2

  20. React Router contributors. (n.d.). useOutletContext. React Router. Providing data from a parent route and reading it in a child. ↩ ↩2

  21. Olah, R. (2024, May 17). React Router has merged with Remix, should you use a different router? DEV Community. Alternatives to React Router. See also 0xedb. (2024, May 15). Merging Remix and React Router [Discussion]. Hacker News. ↩

  22. molefrog and contributors. (n.d.). use-browser-location.js (wouter 3.7.0) [Source code]. npm. Browser navigation implementation, lines 48–53. ↩

  23. borui. (2025, May 4). Fix bug on logging out when not authorized [Commit 4122b5b]. GitHub. The 401, refresh and navigation branches and App responding to the login path. ↩ ↩2 ↩3 ↩4

  24. borui. (2025, April 25). Fix bug myxiosRef interceptors aren't added when navigate to another page [Commit 0dde73f]. GitHub. Moving the interceptor into the shared module. ↩

  25. MDN contributors. (n.d.). JavaScript modules. MDN Web Docs. Synchronous and deferred reads in cyclic imports. ↩

  26. For the separate build comparison on November 24, 2026, I used the versions in AssetMan’s May 4 lockfile: Vite 6.3.0, Rollup 4.40.0 and React Router 7.5.2. I ran four production builds, pairing each interceptor setup with a static import or a route using lazy: () => import('./Assets.js'). The table lists application modules reachable by static imports from the entry and shared chunks. See Vite contributors. (n.d.). Features (Vite 6). Async Chunk Loading Optimization. ↩

  27. Remix team. (2024, May 15). Merging Remix and React Router. Remix. The team’s plans for the two projects. See also Remix contributors. (n.d.). Migrating from React Router. Remix v2. Official migration guide. ↩

  28. Jackson, M. (2024, November 22). React Router v7. Remix. “New Apps,” using React Router as a library or a framework. ↩

  29. State of JavaScript. (2024). Meta-Frameworks. Survey respondents’ usage in “Ratios Over Time”. ↩

© 2025 borui. All rights reserved. This content may be freely reproduced, displayed, modified, or distributed with proper attribution to borui and a link to the article: borui (2025-05-04). How can a React HTTP interceptor navigate to login after a 401 while pages keep their props?. https://caiborui.com/blog/2025-05-04-en-react-router-wouter-401-redirect

@misc{borui2025-85e3dbff,
  author = {borui},
  title = {{How can a React HTTP interceptor navigate to login after a 401 while pages keep their props?}},
  year = {2025},
  publisher = {borui's blog},
  url = {https://caiborui.com/blog/2025-05-04-en-react-router-wouter-401-redirect}
}