
Solid Router brings fine-grained reactivity to route navigation, enabling your single-page application to become multi-paged without full page reloads. Fully integrated into the SolidJS ecosystem, Solid Router provides declarative syntax with features like universal rendering and parallel data fetching for best performance.
Explore the official documentation for detailed guides and examples.
Core Features
- All Routing Modes:
- TypeScript: Full integration for robust, type-safe development
- Universal Rendering: Seamless rendering on both client and server environments
- Declarative: Define routes as components or as an object
- Preload Functions: Parallel data fetching, following the render-as-you-fetch pattern
- Dynamic Route Parameters: Flexible URL patterns with parameters, optional segments, and wildcards
- Data APIs with Caching: Reactive data fetching with deduplication and revalidation
Table of contents
Getting Started
Set Up the Router
npm add @solidjs/router
Install @solidjs/router, then start your application by rendering the router component
import { render } from "@solidjs/web";
import { Router } from "@solidjs/router";
render(() => <Router />, document.getElementById("app"));
This sets up a Router that will match on the url to display the desired page
Configure Your Routes
Solid Router allows you to configure your routes using JSX:
- Add each route to a
<Router> using the Route component, specifying a path and a component to render when the user navigates to that path.
import { render } from "@solidjs/web";
import { Router, Route } from "@solidjs/router";
import Home from "./pages/Home";
import Users from "./pages/Users";
render(
() => (
<Router>
<Route path="/users" component={Users} />
<Route path="/" component={Home} />
</Router>
),
document.getElementById("app")
);
- Provide a root level layout
This will always be there and won't update on page change. It is the ideal place to put top level navigation and Context Providers
import { render } from "@solidjs/web";
import { Router, Route } from "@solidjs/router";
import Home from "./pages/Home";
import Users from "./pages/Users";
const App = (props) => (
<>
<h1>My Site with lots of pages</h1>
{props.children}
</>
);
render(
() => (
<Router root={App}>
<Route path="/users" component={Users} />
<Route path="/" component={Home} />
</Router>
),
document.getElementById("app")
);
- Create a catch-all route (404 page)
We can create catch-all routes for pages not found at any nested level of the router. We use * and optionally the name of a parameter to retrieve the rest of the path.
import { render } from "@solidjs/web";
import { Router, Route } from "@solidjs/router";
import Home from "./pages/Home";
import Users from "./pages/Users";
import NotFound from "./pages/404";
const App = (props) => (
<>
<h1>My Site with lots of pages</h1>
{props.children}
</>
);
render(
() => (
<Router root={App}>
<Route path="/users" component={Users} />
<Route path="/" component={Home} />
<Route path="*404" component={NotFound} />
</Router>
),
document.getElementById("app")
);
- Lazy-load route components
This way, the Users and Home components will only be loaded if you're navigating to /users or /, respectively.
import { lazy } from "solid-js";
import { render } from "@solidjs/web";
import { Router, Route } from "@solidjs/router";
const Users = lazy(() => import("./pages/Users"));
const Home = lazy(() => import("./pages/Home"));
const App = (props) => (
<>
<h1>My Site with lots of pages</h1>
{props.children}
</>
);
render(
() => (
<Router root={App}>
<Route path="/users" component={Users} />
<Route path="/" component={Home} />
</Router>
),
document.getElementById("app")
);
Create Links to Your Routes
Use an anchor tag that takes you to a route:
import { lazy } from "solid-js";
import { render } from "@solidjs/web";
import { Router, Route } from "@solidjs/router";
const Users = lazy(() => import("./pages/Users"));
const Home = lazy(() => import("./pages/Home"));
const App = (props) => (
<>
<nav>
<a href="/about">About</a>
<a href="/">Home</a>
</nav>
<h1>My Site with lots of pages</h1>
{props.children}
</>
);
render(
() => (
<Router root={App}>
<Route path="/users" component={Users} />
<Route path="/" component={Home} />
</Router>
),
document.getElementById("app")
);
Dynamic Routes
If you don't know the path ahead of time, you might want to treat part of the path as a flexible parameter that is passed on to the component.
import { lazy } from "solid-js";
import { render } from "@solidjs/web";
import { Router, Route } from "@solidjs/router";
const Users = lazy(() => import("./pages/Users"));
const User = lazy(() => import("./pages/User"));
const Home = lazy(() => import("./pages/Home"));
render(
() => (
<Router>
<Route path="/users" component={Users} />
<Route path="/users/:id" component={User} />
<Route path="/" component={Home} />
</Router>
),
document.getElementById("app")
);
The colon indicates that id can be any string, and as long as the URL fits that pattern, the User component will show.
You can then access that id from within a route component with useParams.
Note on Animation/Transitions:
Routes that share the same path match will be treated as the same route. If you want to force re-render you can wrap your component in a keyed <Show> like:
<Show when={params.something} keyed>
<MyComponent />
</Show>
Each path parameter can be validated using a MatchFilter.
This allows for more complex routing descriptions than just checking the presence of a parameter.
import { lazy } from "solid-js";
import { render } from "@solidjs/web";
import { Router, Route } from "@solidjs/router";
import type { MatchFilters } from "@solidjs/router";
const User = lazy(() => import("./pages/User"));
const filters: MatchFilters = {
parent: ["mom", "dad"],
id: /^\d+$/,
withHtmlExtension: (v: string) => v.length > 5 && v.endsWith(".html"),
};
render(
() => (
<Router>
<Route
path="/users/:parent/:id/:withHtmlExtension"
component={User}
matchFilters={filters}
/>
</Router>
),
document.getElementById("app")
);
Here, we have added the matchFilters prop. This allows us to validate the parent, id and withHtmlExtension parameters against the filters defined in filters.
If the validation fails, the route will not match.
So in this example:
/users/mom/123/contact.html would match,
/users/dad/123/about.html would match,
/users/aunt/123/contact.html would not match as :parent is not 'mom' or 'dad',
/users/mom/me/contact.html would not match as :id is not a number,
/users/dad/123/contact would not match as :withHtmlExtension is missing .html.
Optional Parameters
Parameters can be specified as optional by adding a question mark to the end of the parameter name:
<Route path="/stories/:id?" component={Stories} />
Wildcard Routes
:param lets you match an arbitrary name at that point in the path. You can use * to match any end of the path:
<Route path="foo/*" component={Foo} />
If you want to expose the wild part of the path to the component as a parameter, you can name it:
<Route path="foo/*any" component={Foo} />
Note that the wildcard token must be the last part of the path; foo/*any/bar won't create any routes.
Multiple Paths
Routes also support defining multiple paths using an array. This allows a route to remain mounted and not rerender when switching between two or more locations that it matches:
<Route path={["login", "register"]} component={Login} />
Nested Routes
The following two route definitions have the same result:
<Route path="/users/:id" component={User} />
<Route path="/users">
<Route path="/:id" component={User} />
</Route>
/users/:id renders the <User/> component, and /users/ is an empty route.
Only leaf Route nodes (innermost Route components) are given a route. If you want to make the parent its own route, you have to specify it separately:
<Route path="/users" component={Users}>
<Route path="/:id" component={User} />
</Route>
<Route path="/users" component={Users} />
<Route path="/users/:id" component={User} />
<Route path="/users">
<Route path="/" component={Users} />
<Route path="/:id" component={User} />
</Route>
You can also take advantage of nesting by using props.children passed to the route component.
function PageWrapper(props) {
return (
<div>
<h1> We love our users! </h1>
{props.children}
<A href="/">Back Home</A>
</div>
);
}
<Route path="/users" component={PageWrapper}>
<Route path="/" component={Users} />
<Route path="/:id" component={User} />
</Route>;
The routes are still configured the same, but now the route elements will appear inside the parent element where the props.children was declared.
You can nest indefinitely - just remember that only leaf nodes will become their own routes. In this example, the only route created is /layer1/layer2, and it appears as three nested divs.
<Route
path="/"
component={(props) => <div>Onion starts here {props.children}</div>}
>
<Route
path="layer1"
component={(props) => <div>Another layer {props.children}</div>}
>
<Route path="layer2" component={() => <div>Innermost layer</div>} />
</Route>
</Route>
Preload Functions
Even with smart caches it is possible that we have waterfalls both with view logic and with lazy loaded code. With preload functions, we can instead start fetching the data parallel to loading the route, so we can use the data as soon as possible. The preload function is called when the Route is loaded or eagerly when links are hovered.
As its only argument, the preload function is passed an object that you can use to access route information:
import { lazy } from "solid-js";
import { Route } from "@solidjs/router";
const User = lazy(() => import("./pages/users/[id].js"));
function preloadUser({ params, location }) {
}
<Route path="/users/:id" component={User} preload={preloadUser} />;
| params | object | The route parameters (same value as calling useParams() inside the route component) |
| location | { pathname, search, hash, query, state, key} | An object that you can use to get more information about the path (corresponds to useLocation()) |
| intent | "initial", "navigate", "native", "preload" | Indicates why this function is being called. - "initial" - the route is being initially shown (ie page load)
- "native" - navigate originated from the browser (eg back/forward)
- "navigate" - navigate originated from the router (eg call to navigate or anchor clicked)
- "preload" - not navigating, just preloading (eg link hover)
|
A common pattern is to export the preload function and data wrappers that corresponds to a route in a dedicated route.data.js file. This way, the data function can be imported without loading anything else.
import { lazy } from "solid-js";
import { Route } from "@solidjs/router";
import preloadUser from "./pages/users/[id].data.js";
const User = lazy(() => import("/pages/users/[id].js"));
<Route path="/users/:id" component={User} preload={preloadUser} />;
The preload function's return value is passed to the page component for any intent other than "preload", allowing you to initialize data or alternatively use our new Data APIs:
Data APIs
Keep in mind that these are entirely optional, but they demonstrate the power of our preload mechanism.
query
To prevent duplicate fetching and to handle refetching triggers, we provide a query API that accepts a function and returns the same function.
const getUser = query(async (id) => {
return (await fetch(`/api/users/${id}`)).json();
}, "users");
It is expected that the arguments to the query function are serializable.
This query accomplishes the following:
- It does deduping on the server for the lifetime of the request.
- It fills a preload cache in the browser which lasts 5 seconds. When a route is preloaded on hover or when preload is called when entering a route it will make sure to dedupe calls.
- We have a reactive refetch mechanism based on key. So we can tell routes that aren't new to retrigger on action revalidation.
- It will serve as a back/forward cache for browser navigation up to 5 mins. Any user based navigation or link click bypasses this cache. Revalidation or new fetch updates the cache.
Using it with preload function might look like:
import { lazy } from "solid-js";
import { Route } from "@solidjs/router";
import { getUser } from ...
const User = lazy(() => import("./pages/users/[id].js"));
function preloadUser({params, location}) {
void getUser(params.id)
}
<Route path="/users/:id" component={User} preload={preloadUser} />;
Inside your page component you:
import { getUser } from ...
import { createMemo } from "solid-js";
export default function User(props) {
const user = createMemo(() => getUser(props.params.id));
return <h1>{user().name}</h1>;
}
Cached function has a few useful methods for getting the key that are useful for invalidation.
let id = 5;
getUser.key;
getUser.keyFor(id);
You can revalidate the query using the revalidate method or you can set revalidate keys on your response from your actions. If you pass the whole key it will invalidate all the entries for the query (ie "users" in the example above). You can also invalidate a single entry by using keyFor.
query can be defined anywhere and then used inside your components with:
Async reads in Solid 2
On this Solid 2 branch, query() results are meant to be consumed directly with Solid primitives like createMemo and createProjection.
const user = createMemo(() => getUser(params.id));
return <h1>{user().name}</h1>;
For object-shaped data where you want a deeply reactive result, use createProjection.
const todos = createProjection(() => getTodos(), []);
action
Router action() is the router-aware mutation wrapper for Solid 2. It keeps form submission, redirects, and invalidation wired into the router while letting you compose optimistic UI with Solid's built-in primitives.
import { action, revalidate, redirect } from "@solidjs/router"
const myAction = action(async (data) => {
await doMutation(data);
throw redirect("/", { revalidate: getUser.keyFor(data.id) });
});
<form action={myAction} method="post" />
<button type="submit" formaction={myAction}></button>
Actions only work with post requests, so make sure to put method="post" on your form.
For optimistic updates, use Solid's optimistic primitives for the rendered state and attach owner-scoped submit hooks to the router action:
import { createOptimisticStore } from "solid-js";
import { action, query } from "@solidjs/router";
const getTodos = query(async () => fetchTodos(), "todos");
const [todos, setTodos] = createOptimisticStore(() => getTodos(), []);
const addTodo = action(async (todo) => {
await saveTodo(todo);
return { ok: true, todo };
}, "add-todo").onSubmit(todo => {
setTodos(items => {
items.push({ ...todo, pending: true });
});
});
myAction.onSubmit(...) registers a listener for that action in the current reactive owner. Multiple components can register hooks against the same action, and those hooks are automatically removed when their owner is disposed. myAction.onSettled(...) works the same way for observing completed submissions.
The preferred pattern is for actions to return values and let the client interpret the result. Throwing errors is still supported, but Submission.error is mainly an escape hatch for that legacy style.
Sometimes it might be easier to deal with typed data instead of FormData and adding additional hidden fields. For that reason Actions have a with method. That works similar to bind which applies the arguments in order.
Picture an action that deletes Todo Item:
const deleteTodo = action(async (formData: FormData) => {
const id = Number(formData.get("id"))
await api.deleteTodo(id)
})
<form action={deleteTodo} method="post">
<input type="hidden" name="id" value={todo.id} />
<button type="submit">Delete</button>
</form>
Instead with with you can write this:
const deleteTodo = action(api.deleteTodo)
<form action={deleteTodo.with(todo.id)} method="post">
<button type="submit">Delete</button>
</form>
Actions also take a second argument which can be the name or an option object with name. name is used to identify SSR actions that aren't server functions (see note below).
Notes on <form> implementation and SSR
This requires stable references as you can only serialize a string as an attribute, and across SSR they'd need to match. The solution is providing a unique name.
const myAction = action(async (args) => {}, "my-action");
useAction
Instead of forms you can use actions directly by wrapping them in a useAction primitive. This is how we get the router context.
const submit = useAction(myAction);
submit(...args);
The outside of a form context you can use custom data instead of formData, and these helpers preserve types. However, even when used with server functions (in projects like SolidStart) this requires client side javascript and is not Progressive Enhanceable like forms are.
useSubmissions
This returns settled submission records for an action. It is useful for reading completed results, clearing old submissions, retrying a prior submission, or replaying settled errors. It is not the optimistic state layer.
type Submission<T, U> = {
readonly input: T;
readonly result?: U;
readonly error: any;
readonly url: string;
clear: () => void;
retry: () => void;
};
const submissions = useSubmissions(action, (input) => filter(input));
const latestSubmission = submissions.at(-1);
Use Solid's createOptimistic or createOptimisticStore for in-flight UI, and use submissions as the durable settled record layer.
Response Helpers
These are used to communicate router navigations from query/actions, and can include invalidation hints. Generally these are thrown to not interfere the with the types and make it clear that function ends execution at that point.
redirect(path, options)
Redirects to the next route
const getUser = query(() => {
const user = await api.getCurrentUser()
if (!user) throw redirect("/login");
return user;
})
reload(options)
Reloads the data on the current page
const getTodo = query(async (id: number) => {
const todo = await fetchTodo(id);
return todo;
}, "todo");
const updateTodo = action(async (todo: Todo) => {
await updateTodo(todo.id, todo);
reload({ revalidate: getTodo.keyFor(todo.id) });
});
Config Based Routing
You don't have to use JSX to set up your routes; you can pass an array of route definitions:
import { lazy } from "solid-js";
import { render } from "@solidjs/web";
import { Router } from "@solidjs/router";
const routes = [
{
path: "/users",
component: lazy(() => import("/pages/users.js")),
},
{
path: "/users/:id",
component: lazy(() => import("/pages/users/[id].js")),
children: [
{
path: "/",
component: lazy(() => import("/pages/users/[id]/index.js")),
},
{
path: "/settings",
component: lazy(() => import("/pages/users/[id]/settings.js")),
},
{
path: "/*all",
component: lazy(() => import("/pages/users/[id]/[...all].js")),
},
],
},
{
path: "/",
component: lazy(() => import("/pages/index.js")),
},
{
path: "/*all",
component: lazy(() => import("/pages/[...all].js")),
},
];
render(() => <Router>{routes}</Router>, document.getElementById("app"));
Also you can pass a single route definition object for a single route:
import { lazy } from "solid-js";
import { render } from "@solidjs/web";
import { Router } from "@solidjs/router";
const route = {
path: "/",
component: lazy(() => import("/pages/index.js")),
};
render(() => <Router>{route}</Router>, document.getElementById("app"));
Alternative Routers
Hash Mode Router
By default, Solid Router uses location.pathname as route path. You can simply switch to hash mode through using <HashRouter>.
import { HashRouter } from "@solidjs/router";
<HashRouter />;
Memory Mode Router
You can also use memory mode router for testing purpose.
import { MemoryRouter } from "@solidjs/router";
<MemoryRouter />;
SSR Routing
For SSR you can use the static router directly or the browser Router defaults to it on the server, just pass in the url.
import { isServer } from "@solidjs/web";
import { Router } from "@solidjs/router";
<Router url={isServer ? req.url : ""} />;
Components
<Router>
This is the main Router component for the browser.
| children | JSX.Element, RouteDefinition, or RouteDefinition[] | The route definitions |
| root | Component | Top level layout component |
| base | string | Base url to use for matching routes |
| actionBase | string | Root url for server actions, default: /_server |
| preload | boolean | Enables/disables preloads globally, default: true |
| explicitLinks | boolean | Disables all anchors being intercepted and instead requires <A>. Default: false. (To disable interception for a specific link, set target to any value, e.g. <a target="_self">.) |
<A>
Like the <a> tag but supports automatic apply of base path + relative paths and active class styling (requires client side JavaScript).
The <A> tag has an active class if its href matches the current location, and inactive otherwise. Note: By default matching includes locations that are descendants (eg. href /users matches locations /users and /users/123), use the boolean end prop to prevent matching these. This is particularly useful for links to the root route / which would match everything.
| href | string | The path of the route to navigate to. This will be resolved relative to the route that the link is in, but you can preface it with / to refer back to the root. |
| noScroll | boolean | If true, turn off the default behavior of scrolling to the top of the new page |
| replace | boolean | If true, don't add a new entry to the browser history. (By default, the new page will be added to the browser history, so pressing the back button will take you to the previous route.) |
| state | unknown | Push this value to the history stack when navigating |
| inactiveClass | string | The class to show when the link is inactive (when the current location doesn't match the link) |
| activeClass | string | The class to show when the link is active |
| end | boolean | If true, only considers the link to be active when the current location matches the href exactly; if false, check if the current location starts with href |
<Navigate />
Solid Router provides a Navigate component that works similarly to A, but it will immediately navigate to the provided path as soon as the component is rendered. It also uses the href prop, but you have the additional option of passing a function to href that returns a path to navigate to:
function getPath({ navigate, location }) {
return "/some-path";
}
<Route path="/redirect" component={() => <Navigate href={getPath} />} />;
<Route>
The Component for defining Routes:
| path | string | Path partial for defining the route segment |
| component | Component | Component that will be rendered for the matched segment |
| matchFilters | MatchFilters | Additional constraints for matching against the route |
| children | JSX.Element | Nested <Route> definitions |
| preload | RoutePreloadFunc | Function called during preload or when the route is navigated to. |
Router Primitives
Solid Router provides a number of primitives that read off the Router and Route context.
useParams
Retrieves a reactive, store-like object containing the current route path parameters as defined in the Route.
const params = useParams();
const [user] = createResource(() => params.id, fetchUser);
useNavigate
Retrieves method to do navigation. The method accepts a path to navigate to and an optional object with the following options:
- resolve (boolean, default
true): resolve the path against the current route
- replace (boolean, default
false): replace the history entry
- scroll (boolean, default
true): scroll to top after navigation
- state (any, default
undefined): pass custom state to location.state
Note: The state is serialized using the structured clone algorithm which does not support all object types.
const navigate = useNavigate();
if (unauthorized) {
navigate("/login", { replace: true });
}
useLocation
Retrieves reactive location object useful for getting things like pathname.
const location = useLocation();
const pathname = createMemo(() => parsePath(location.pathname));
useSearchParams
Retrieves a tuple containing a reactive object to read the current location's query parameters and a method to update them. The object is a proxy so you must access properties to subscribe to reactive updates. Note values will be strings and property names will retain their casing.
The setter method accepts an object whose entries will be merged into the current query string. Values '', undefined and null will remove the key from the resulting query string. Updates will behave just like a navigation and the setter accepts the same optional second parameter as navigate and auto-scrolling is disabled by default.
const [searchParams, setSearchParams] = useSearchParams();
return (
<div>
<span>Page: {searchParams.page}</span>
<button
onClick={() =>
setSearchParams({ page: (parseInt(searchParams.page) || 0) + 1 })
}
>
Next Page
</button>
</div>
);
useIsRouting
Retrieves a signal that indicates whether the router is currently processing a navigation. Useful for showing pending navigation state while the next route and its data settle.
const isRouting = useIsRouting();
return (
<div class={{ "grey-out": isRouting() }}>
<MyAwesomeContent />
</div>
);
useMatch
useMatch takes an accessor that returns the path and creates a Memo that returns match information if the current path matches the provided path. Useful for determining if a given path matches the current route.
const match = useMatch(() => props.href);
return <div class={{ active: Boolean(match()) }} />;
useCurrentMatches
useCurrentMatches returns all the matches for the current matched route. Useful for getting all the route information.
For example if you stored breadcrumbs on your route definition you could retrieve them like so:
const matches = useCurrentMatches();
const breadcrumbs = createMemo(() =>
matches().map((m) => m.route.info.breadcrumb)
);
usePreloadRoute
usePreloadRoute returns a function that can be used to preload a route manual. This is what happens automatically with link hovering and similar focus based behavior, but it is available here as an API.
const preload = usePreloadRoute();
preload(`/users/settings`, { preloadData: true });
useBeforeLeave
useBeforeLeave takes a function that will be called prior to leaving a route. The function will be called with:
- from (Location): current location (before change).
- to (string | number): path passed to
navigate.
- options (NavigateOptions): options passed to
navigate.
- preventDefault (function): call to block the route change.
- defaultPrevented (readonly boolean):
true if any previously called leave handlers called preventDefault.
- retry (function, force?: boolean ): call to retry the same navigation, perhaps after confirming with the user. Pass
true to skip running the leave handlers again (i.e. force navigate without confirming).
Example usage:
useBeforeLeave((e: BeforeLeaveEventArgs) => {
if (form.isDirty && !e.defaultPrevented) {
e.preventDefault();
setTimeout(() => {
if (window.confirm("Discard unsaved changes - are you sure?")) {
e.retry(true);
}
}, 100);
}
});
Migration from 0.16.x
This branch is the Solid 2 migration. Most route configuration stays the same, but the data APIs and recommended async patterns have changed.
Async reads move to Solid 2 primitives
createAsync and createAsyncStore are gone. Read query results with Solid 2 primitives like createMemo, createProjection, createOptimistic, and createOptimisticStore.
const user = createMemo(() => getUser(params.id));
const [todos, setTodos] = createOptimisticStore(() => getTodos(), []);
query() stays the source of truth
Continue using query() for cached reads and invalidation, but consume the results directly through Solid 2's async primitives instead of router-specific wrappers.
action() lifecycle hooks changed
The action API is now centered around instance methods:
const saveTodo = action(async (todo) => {
await api.saveTodo(todo);
return { ok: true, todo };
}, "save-todo")
.onSubmit(todo => {
})
.onSettled(submission => {
});
- Use
onSubmit(...) for owner-scoped optimistic/pre-submit work.
- Use
onSettled(...) for owner-scoped observation of completed submissions.
- Use returned values for expected application-level results. Thrown errors are still captured on
Submission.error when something fails unexpectedly.
useSubmissions() is the submission API
Submissions are now settled history, not in-flight mutation state. Read them through useSubmissions() and select the latest entry with at(-1) when needed.
const submissions = useSubmissions(saveTodo);
const latestSubmission = submissions.at(-1);
SPAs in Deployed Environments
When deploying applications that use a client side router that does not rely on Server Side Rendering you need to handle redirects to your index page so that loading from other URLs does not cause your CDN or Hosting to return not found for pages that aren't actually there.
Each provider has a different way of doing this. For example on Netlify you create a _redirects file that contains:
/* /index.html 200
On Vercel you add a rewrites section to your vercel.json:
{
"rewrites": [
{
"source": "/(.*)",
"destination": "/index.html"
}
]
}