Sub topic 15
Choosing a router: browser, hash, or memory
React Router's data API ships three functions that create a router: createBrowserRouter, createHashRouter, and createMemoryRouter. All three take the same route objects. They differ only in where the current location is stored. This chapter explains that difference, the deployment consequences of each choice, and the errors people commonly hit.
This chapter assumes you can already define route objects and render them with RouterProvider. It also assumes you know what a URL path, a query string, and a fragment (the part after #) are.
What a router flavor actually changes
A router has two jobs. It matches a location against your route objects, and it keeps the location in sync with something. Matching is identical in all three flavors. The "something" is the only difference:
| Function | Location is stored in | Example URL | Needs server support |
|---|---|---|---|
| `createBrowserRouter` | The path, through the History API | `https://site.com/users/42` | Yes, for direct visits to deep URLs |
| `createHashRouter` | The fragment after `#` | `https://site.com/#/users/42` | No |
| `createMemoryRouter` | A JavaScript array in memory | None. The address bar is untouched | No |
Because the route objects are the same, you can define them once and choose the flavor per environment:
import {
createBrowserRouter,
createHashRouter,
createMemoryRouter,
Outlet,
Link,
} from "react-router-dom";
function Layout() {
return (
<div>
<nav>
<Link to="/">Home</Link> <Link to="/about">About</Link>
</nav>
<Outlet />
</div>
);
}
export const routes = [
{
path: "/",
element: <Layout />,
children: [
{ index: true, element: <h1>Home</h1> },
{ path: "about", element: <h1>About</h1> },
],
},
];
export const browserRouter = createBrowserRouter(routes);
export const hashRouter = createHashRouter(routes);
export const memoryRouter = createMemoryRouter(routes, {
initialEntries: ["/about"],
});A <Link to="/about"> works unchanged in all three. React Router builds the correct href for the flavor, so /about for the browser router and #/about for the hash router.
Browser router: the default choice
createBrowserRouter uses the History API (pushState and popstate). URLs look like normal URLs, which is better for users, for sharing links, and for search engines that index the page.
The cost is that the server must cooperate. When a user types https://site.com/users/42 into the address bar, or refreshes on that page, the browser asks the server for /users/42. A static file server has no such file and returns a 404. Client-side routing only takes over after your JavaScript has loaded.
The fix is a fallback rule: for any path that is not a real file, serve index.html. Your bundle then loads, and the router reads the path from the address bar.
server {
listen 80;
root /usr/share/nginx/html;
location / {
try_files $uri /index.html;
}
}Vite's dev server and vite preview already do this fallback. That is why a browser router often works locally and then breaks the first time you deploy to a static host.
Serving the app from a sub-path
If the app lives at https://site.com/app/ instead of the domain root, pass basename:
import { createBrowserRouter } from "react-router-dom";
const router = createBrowserRouter(
[{ path: "/", element: <h1>Home</h1> }],
{ basename: "/app" }
);Route paths stay written as if the app were at the root. React Router adds and strips the prefix. Forgetting basename is a common cause of the router matching nothing and rendering the default 404 screen.
Hash router: when you cannot control the server
createHashRouter stores the location after the #. Browsers never send the fragment to the server, so the server only ever sees a request for /, and every deep link works with no server configuration.
Use it when:
- You deploy to a static host that cannot rewrite URLs to
index.html. - The app is loaded from the
file://protocol, as in some Electron or embedded-webview setups. - The app is mounted inside a page you do not own, and you must not change the path.
The trade-offs are real:
- URLs are less clean, and search engines treat the fragment as part of one page.
- The server cannot see the route, so it cannot do server-side rendering or route-specific redirects.
- Plain in-page anchors such as
<a href="#section">conflict with the router, because the fragment is now the route. Scroll to elements with code instead, or use route-level mechanisms.
Memory router: no address bar at all
createMemoryRouter keeps its history in an array. It never reads or writes window.location. You pick the starting point with initialEntries and, optionally, initialIndex.
It fits three situations:
- Tests, where you want to render a route at a chosen URL without a browser.
- Component previews, such as Storybook, where changing the page URL would be wrong.
- Self-contained widgets, such as a wizard inside a modal, that need internal navigation but must not touch the host page's URL.
import { render, screen } from "@testing-library/react";
import { createMemoryRouter, RouterProvider } from "react-router-dom";
import { routes } from "./routes";
test("renders the about page", async () => {
const router = createMemoryRouter(routes, {
initialEntries: ["/", "/about"],
initialIndex: 1,
});
render(<RouterProvider router={router} />);
expect(await screen.findByText("About")).toBeTruthy();
expect(router.state.location.pathname).toBe("/about");
});Here initialIndex: 1 starts on the second entry, so there is also a "back" entry. You can read router.state.location to assert on where the router ended up. Create a new router inside each test. A router holds state, and sharing one instance between tests leaks the location from one test into the next.
Common errors
- Deep links return 404 after deploy. You used a browser router on a host with no fallback to
index.html. Add the rewrite rule, or switch to a hash router. - Assets fail to load on nested URLs. With a path like
/users/42, a relative asset URL such assrc="main.js"resolves to/users/main.js. Use absolute asset paths, which bundlers produce when you set the correct base. - Everything renders the 404 under a sub-path. You deployed under
/app/but did not setbasename. - Creating the router inside a component. Calling
createBrowserRouterin the body of a component builds a new router on every render and resets navigation state. Create it once at module level. - Tests that touch the real URL. Using a browser router in tests makes them depend on
window.locationand on earlier tests. Use a memory router. - Mixing flavors in one app.
RouterProvidertakes one router. Do not nest a secondRouterProviderto get a different flavor, unless you are deliberately isolating a widget.
Decision criteria
Start with the browser router. Move to another flavor only for a concrete reason.
- Can your host rewrite unknown paths to
index.html? If yes, use the browser router. - If the host is static and cannot rewrite, or the app runs from
file://, use the hash router. - If there is no real address bar to control (tests, previews, embedded widgets), use the memory router.
A practical pattern is to export the routes array from one module. Production code builds a browser (or hash) router from it, and tests build a memory router from the same array. Then your tests exercise the same route configuration that users see.
Exercise
Your app uses createBrowserRouter and works on your laptop. After deploying to a static file host, navigating from the home page to /settings works, but refreshing on /settings shows the host's 404 page. Why does this happen, and what are two ways to fix it?
Show answer
Clicking a link only changes the URL through the History API, so no request goes to the server. A refresh makes the browser request /settings from the server, which has no such file. Fix it by configuring the host to serve index.html for unknown paths (for example, try_files $uri /index.html in nginx), or by switching to createHashRouter so the route lives after the # and the server only ever receives a request for /.
Exercise
You want a test that renders your routes starting at /users/42, with a back entry of /. Which router function and options do you use, and why not a browser router?
Show answer
Use createMemoryRouter(routes, { initialEntries: ["/", "/users/42"], initialIndex: 1 }). A memory router keeps its history in an array, so the test needs no browser URL and cannot leak location state into other tests. A browser router reads and writes window.location, which ties tests to shared global state.