Solid Router brings fine-grained reactivity to route navigation. Routes are config objects — the single source of truth for matching and types — and the router upgrades HTML's own interaction verbs instead of wrapping them: <a href={path}> and <form action={action}> carry typed, URL-addressable values on real platform elements, intercepted by delegation, decorated with a shared attribute vocabulary, and fully functional without JavaScript.
Explore the official documentation for detailed guides and examples.
- Typed Routing: URLs built through a typed path proxy inferred from your route config —
paths.users(2).settingstypechecks against the tree - Plain Anchors: no link component —
<a>elements getaria-currentanddata-activeautomatically via compiler-claimed anchors, anddata-pendingwith the opt-inpendingLinksplugin - Universal Rendering: one factory for browser, hash, memory, and server rendering; history adapters are imports, so unused ones never enter your bundle
- Preload Functions: parallel data fetching following the render-as-you-fetch pattern, triggered eagerly by opt-in link preloading
- Data APIs with Caching:
queryandformActionwith deduplication, revalidation, single-flight mutations, and progressive enhancement — plusliveQueryfor keyed queries over live streams - Typed Search Params: opt-in per-route Standard Schema validation —
search.pageis anumber, not"2"
- Getting Started
- The Mental Model: Instance vs Hooks
- Route Definitions
- Typed Paths
- Links
- Preloading
- Preload Functions
- Data APIs
- Typed Search Params
- Router Config Reference
- Router Primitives
- Other Environments
- Server Integration
- Migration from 0.x
- SPAs in Deployed Environments
# use preferred package manager
npm add @solidjs/routerDefine your routes as config objects and create the router outside JSX. The instance is the provider component, and paths is a typed URL builder inferred from the tree:
// app/router.ts
import { lazy } from "solid-js";
import { createRouter } from "@solidjs/router";
export const Router = createRouter({
routes: [
{ path: "/", component: lazy(() => import("./pages/Home")) },
{ path: "/about", component: lazy(() => import("./pages/About")) },
{
path: "/users/:id",
component: lazy(() => import("./pages/User")),
children: [
{ path: "/", component: lazy(() => import("./pages/UserOverview")) },
{ path: "/settings", component: lazy(() => import("./pages/UserSettings")) }
]
},
{ path: "*404", component: lazy(() => import("./pages/NotFound")) }
]
});
export const { paths } = Router;This one module serves everything: the client renders the instance, and on the server the same instance reads its location from the request (or the configured history when there is none — SSG, tests). There is no separate "server router" and no need to export the raw route array.
When a tree is composed across files (feature subtrees), wrap the extracted arrays in defineRoutes — an identity function that preserves the literal types inference feeds on (a bare extracted array silently widens to string paths without it or as const) and type-checks the definitions where they're written:
// features/admin/routes.ts
export const adminRoutes = defineRoutes([
{
path: "/admin",
component: Admin,
children: [
/* ... */
]
}
]);
// app/router.ts
export const Router = createRouter({ routes: [...appRoutes, ...adminRoutes] });Its single-route sibling defineRoute also types params inside the route's own component and preload — see Typed Route Params.
Mount it by rendering the instance. The render-prop child is your root layout — it always stays mounted, receives the matched content as props.children, and is the ideal place for top-level navigation and context providers:
// app/index.tsx
import { render } from "@solidjs/web";
import { Router } from "./router";
render(
() => (
<Router>
{props => (
<>
<h1>My Site with lots of pages</h1>
{props.children}
</>
)}
</Router>
),
document.getElementById("app")!
);Links are plain anchors. Typed path nodes coerce to strings on the attribute, and the router intercepts clicks through delegation:
import { paths } from "./router";
<nav>
<a href={paths()}>Home</a>
<a href={paths.about}>About</a>
<a href={paths.users(user.id).settings}>Settings</a>
</nav>;The API splits across two surfaces, and the line between them is precise: could two concurrent server requests give different answers? If yes, it's a hook. If no, it's on the instance.
The instance is shared — one module-level object serving every mount, every request, every test. It is deliberately non-stateful (on the server there are many "current locations" at once), so it carries only the app's static routing vocabulary. Hooks read the live session from context.
| Instance — facts about the app | Hooks — facts about the session |
|---|---|
paths — how to spell URLs |
useLocation, useParams — where am I |
match(url) — how would a URL match |
useNavigate, usePreloadRoute — move / warm |
routes, config — what exists |
useIsRouting, useRouteMatches, useSearchParams — live state |
They compose as noun and verb — the instance supplies a typed URL, the hook acts on the current session:
const navigate = useNavigate();
navigate(paths.users(2)); // verb(noun)
const params = useParams(paths.users); // hook, typed by the instanceHooks are the default; import the router only when you need typed URLs or matching outside a render. Components that only read their session (params, location, string-path navigation) never need the instance — which also means component files don't form import cycles with the router module that references them in its config.
A route definition supports:
| key | type | description |
|---|---|---|
path |
string | string[] |
Path partial for this route segment |
component |
Component |
Component rendered for the matched segment |
children |
RouteDefinition | RouteDefinition[] | () => Promise<...> |
Nested route definitions, or a thunk for a lazy subtree |
preload |
RoutePreloadFunc |
Called on link preloading and navigation |
matchFilters |
MatchFilters |
Additional constraints for matching parameters |
search |
StandardSchemaV1 |
Search-param validator; its types flow into paths and hooks |
info |
Record<string, any> |
Arbitrary metadata, readable via useRouteMatches |
The tree is immutable and there is one router per app — that's what makes paths and the typed hooks truthful, it lets matching compile once and be shared by every mount, request, and match() call, and it means delegation, link state, and preloading all have a single owner. Compose large apps by spreading subtrees into the config (see defineRoutes above); mounting a router inside another router is not supported (nested <Routes> has been gone since 0.10) and warns in development. Sections whose code shouldn't load up front are lazy route subtrees — still one tree, still typed.
Treat part of the path as a parameter with a colon:
const routes = defineRoutes([
{ path: "/users", component: Users },
{ path: "/users/:id", component: User }
]);As long as the URL fits the pattern, the User component shows, and id is available via useParams.
Params are decoded: on /users/%E7%8C%AB (/users/猫), id is "猫", and matchFilters see the decoded value too. Each segment is decoded after matching, so an encoded slash stays inside its param (/users/a%2Fb gives id: "a/b"), and a malformed escape is left as-is. paths encodes params on the way out, so paths.users("猫") round-trips. When building a URL from a param by hand, encode it (encodeURIComponent) or use paths. location.pathname keeps the URL's own encoding.
Note on Animation/Transitions: routes that share the same path match are treated as the same route. To force a re-render, wrap your component in a keyed <Show>:
<Show when={params.something} keyed>
<MyComponent />
</Show>By default params is an open record — every key is string | undefined, even when the pattern guarantees it. Wrap a route in defineRoute and its component and preload are typed from the route's own path:
import { defineRoute } from "@solidjs/router";
const story = defineRoute({
path: "/stories/:id/:tab?",
preload: ({ params }) => getStory(params.id), // params.id: string
component: props => (
<Story
id={props.params.id} // string — the pattern guarantees it
tab={props.params.tab} // string | undefined — optional param
/>
)
});defineRoute is an identity function at runtime — the route object drops into routes (or a parent's children) like any plain object, and path, children, matchFilters, and search still flow into paths and the typed hooks. Params inherited from parent routes stay accessible as string | undefined; nested children type their own params only if they use defineRoute themselves.
For components declared away from their route, RouteProps takes a path witness — the same paths node you navigate with (import type keeps the instance out of the runtime graph, so no cycle) — plus an optional data type:
import type { RouteComponent, RouteProps } from "@solidjs/router";
import type { Router } from "./app/router";
function Story(props: RouteProps<typeof Router.paths.stories, StoryData>) {
props.params.id; // string
}
// component-type form — props infer contextually
const Story: RouteComponent<typeof Router.paths.stories, StoryData> = props => (
<h1>{props.params.id}</h1>
);
// or, anywhere under the route:
const params = useParams(paths.stories); // typed from the treeWhen no instance is in scope at the definition site — most notably file-system route files, where the pattern lives in the filename — the witness can be the pattern string itself: RouteProps<"/stories/:id">.
Each parameter can be validated with a MatchFilter — an enum array, a regex, or a predicate. If validation fails, the route doesn't match:
import { int, type MatchFilters } from "@solidjs/router";
const filters: MatchFilters = {
parent: ["mom", "dad"], // enum values
id: /^\d+$/, // only numbers
withHtmlExtension: (v: string) => v.length > 5 && v.endsWith(".html")
};
const routes = defineRoutes([
{ path: "/users/:parent/:id/:withHtmlExtension", component: User, matchFilters: filters }
]);So /users/mom/123/contact.html matches, while /users/aunt/123/contact.html (invalid parent) and /users/mom/me/contact.html (non-numeric id) don't.
The built-in int filter is typed: it constrains matching to integers at runtime and types the param as number at paths callsites:
{ path: "/users/:id", matchFilters: { id: int }, component: User }
paths.users(123); // ok
paths.users("abc"); // type errorAdd a question mark to make a parameter optional:
// Matches stories and stories/123 but not stories/123/comments
{ path: "/stories/:id?", component: Stories }Use * to match any remainder of the path, optionally naming it to expose it as a parameter:
{ path: "foo/*", component: Foo } // matches foo/, foo/a, foo/a/b/c
{ path: "foo/*any", component: Foo } // rest of the path available as params.anyThe wildcard token must be the last part of the path; foo/*any/bar won't create any routes.
An array of paths lets a route stay mounted (no re-render) when switching between locations it matches:
// Navigating from login to register does not re-render Login
{ path: ["login", "register"], component: Login }Only leaf nodes become routes. A parent with a component wraps its children, which render where the parent places props.children:
function PageWrapper(props) {
return (
<div>
<h1>We love our users!</h1>
{props.children}
<a href={paths()}>Back Home</a>
</div>
);
}
const routes = defineRoutes([
{
path: "/users",
component: PageWrapper,
children: [
{ path: "/", component: Users },
{ path: "/:id", component: User }
]
}
]);You can nest indefinitely. In this example the only route created is /layer1/layer2, rendered as three nested divs:
{
path: "/",
component: props => <div>Onion starts here {props.children}</div>,
children: [{
path: "layer1",
component: props => <div>Another layer {props.children}</div>,
children: [{ path: "layer2", component: () => <div>Innermost layer</div> }]
}]
}children also accepts a thunk, so a whole section's route table (not just its components) stays out of the initial bundle:
// admin/routes.ts
export default defineRoutes([
{ path: "/", component: lazy(() => import("./Dashboard")) },
{ path: "/users/:id", matchFilters: { id: int }, component: lazy(() => import("./User")) }
]);
// app.ts
const router = createRouter({
routes: [
{ path: "/", component: Home },
{ path: "/admin", component: AdminShell, children: () => import("./admin/routes") }
]
});The import only fires when something needs the subtree — preloading a link into it, navigating into it, or the server matching a URL beneath it. Until then the tree carries a placeholder that knows every URL under /admin belongs to the subtree without knowing its contents (static sibling routes still win without triggering the load). Everything folds in as if the routes were inline:
- Types: TypeScript never runs the thunk — inference flows through the import's promise type, so
paths.admin.users(2)typechecks (match filters and search schemas included) before any of the subtree's code exists client-side. The module'sdefaultorroutesexport is used. Only tables genuinely built at runtime (typed as plainRouteDefinition[]) degrade to untyped. - Navigation: the table load folds into the navigation transition — the old screen holds until the subtree (and its matched components) are ready, exactly like a
lazy()route component. - Preloading: a link preload kicks the table load, and when it lands the preload continues into the inner routes' components and
preloadfunctions — one cascading warm-up from the earliest possible moment. - Server: SSR resolves matched boundaries during the render (use the streaming entry point
renderToStream— awaiting it resolves with the settled HTML — as with any async work), and the single-flight collector resolves them before its data pass.
Resolution is cached per thunk and append-only: the tree never changes shape after a subtree lands, it just gets more specific. Keep thunks deterministic — () => import(...) — rather than switching tables on runtime state.
Solid's experimental server components are "use server" functions that return a component. serverRouteComponent takes a query over one and uses it as a route's component directly — the router owns the URL → call translation a client wrapper used to spell out:
// story.tsx — the source owns its key
import { query, type ServerRouteArgs } from "@solidjs/router";
export const getStory = query(async ({ params }: ServerRouteArgs<{ id: string }>) => {
"use server";
const story = await db.stories.get(params.id);
return props => (
<article>
<h1>{story.title}</h1>
{props.children}
</article>
);
}, "story");
// routes.ts
defineRoute({ path: "/stories/:id", component: serverRouteComponent(getStory) });The source is called with derived arguments, not a live location — the call's (function, arguments) address keys both the query cache and the frame store, so the args name exactly what the route depends on:
params: the params this route's pattern (and its ancestors') declares — never a child's, so a layout does not refetch when a leaf param changes.defineRoutechecks them against the pattern.search: the validated output of the route'ssearchschema, only when one is declared. Otherwiseundefined, and the route never tracks the query string.
A route view is route-shaped on purpose — the address stays stable and defineRoute can check its params against the pattern — which means it is only callable as a route. When the same server component is also used elsewhere, keep it a plain (non-exported, non-endpoint) function and have the route view call it with params.id. The value serverRouteComponent returns is a component only so it fits the component field; mounting it any other way (through lazy(), or by hand) throws, since outside the match there are only merged params to call with.
The router mounts the resolved component with the outlet as children, so a server component can be a layout, and it calls the same source under preload intent — link preloading, usePreloadRoute, the single-flight collector — with the same derived args. What that call means is the source's: the router does not choose the cache strategy or own the key.
query(fn, key): link intent warms the entry the render reads,revalidate("story")and action responses refetch it, and the collector reproduces it so a mutation's response carries the route's fresh markup. Argument changes deliver into the mounted boundary — it morphs in place rather than remounting.liveQuery(fn, key): the frame stream stays open and the channel owns it — a link preload connects it (held through the preload window, so a preloaded link is an open stream),revalidate(key)reconnects, and the mutation sweep and the single-flight collector both leave it alone — nothing pulls it server-side, and the stream is its own freshness.
Anything else callable with the args works too; wrapping is what gives dedupe, preload, and revalidation.
Mutations reach these routes the way they reach any query, and the cost model is worth knowing: a swept server route is a server-side re-render plus its markup in the response, not a small data blob. From a server action, redirect(url) re-collects everything the target shows and a bare reload() everything the current page shows — server routes included, shell and layouts too. On a server-component-heavy page, name what a mutation actually changed instead. Router.keysFor(url) answers the query keys of the server routes a URL shows, root to leaf — the app's own keys, from pure matching, so it works in an action and never spells a key:
export const addComment = formAction(async (form: FormData) => {
"use server";
await db.comments.add(form);
return reload({ revalidate: Router.keysFor(paths.stories(form.get("id"))) });
});Route keys, not addresses: every story page is refetched, which is what prefix matching gives a hand-written revalidate("story") too.
An app shell is a pathless layout route whose component is a server component. With no pattern, its args are the constant { params: {}, search: undefined } — one call, one address, persisting across every navigation — and as a route it gets preload, collection, and revalidate like any other. The <Router> root slot exists for client providers that need router context without following route rules; a server component has neither, so it does not go there:
const routes = [{ component: serverRouteComponent(query(appShell, "shell")), children: pages }];
render(() => <Router routes={routes} />, document.body);children is the only client position the router fills, and the helper's type says so: a server component that requires other props — event handlers, refs, named slots — is rejected. Those come from the client, so that route has a client half; write it as an ordinary route component around dynamicComponent(). Interaction that lives on the server — form posts to server actions via action={addTodo} — needs no client component at all.
The @solidjs/router/fs adapter turns a file-routes manifest into route definitions — the app imports the virtual module, the adapter maps it:
import { pageRoutes } from "virtual:file-routes";
import { fileRoutes } from "@solidjs/router/fs";
export const Router = createRouter({ routes: fileRoutes(pageRoutes) });Route files export their component as default and everything else as a route config export, which is spread into the definition. Inside a route file the pattern lives in the filename, so there's no paths node to witness with at the definition site — defineFileRoute takes the pattern string instead, types preload's params from it, and validates matchFilters along the way. The config then doubles as the component's RouteProps witness, typing params from the pattern and data from the preload's return type:
// routes/blog/[id].tsx
import { int } from "@solidjs/router";
import { defineFileRoute } from "@solidjs/router/fs";
export const route = defineFileRoute("/blog/:id", {
matchFilters: { id: int },
preload: ({ params }) => getPost(params.id) // params.id: string
});
export default function Post(props: RouteProps<typeof route>) {
props.params.id; // string
props.data; // ReturnType of the preload above
}The pattern string is a typing witness — at runtime the manifest's path (from the filename) is the source of truth. With the plugin's types option generating a literal declaration for the virtual module, the file paths flow into paths and the typed hooks like a hand-written tree — paths.blog(42) typechecks, filters and search schemas included, and useParams(paths.blog) works as usual anywhere under the route.
A route file's page can be a server component: make the default export a "use server" function of the route args. With fileRoutes({ serverComponents: true }) on the file-routes plugin, the scanner flags such a file and the adapter builds the route the hand-written tree spells out — serverRouteComponent(query(fn, key)) with the file's path as the key. No query, key, or wrapper in the route file. (That option turns on server component routes; server components themselves are Solid's plugin's serverFunctions: { components: true }, the same switch a hand-written server route needs.)
// routes/stories/[id].tsx
import { defineFileRoute } from "@solidjs/router/fs";
import type { ServerRouteArgs } from "@solidjs/router";
export const route = defineFileRoute("/stories/:id", { search: storySearch });
export default async function Story({ params, search }: ServerRouteArgs<typeof route>) {
"use server";
const story = await db.stories.get(params.id);
return props => <article>{story.title}{props.children}</article>;
}ServerRouteArgs<typeof route> reads the config as a witness like RouteProps does: params from the pattern, search as the schema's output (undefined with no schema). The key is the file — Router.keysFor(paths.stories(7)) answers ["src/routes/stories/[id].tsx"] (plus any server layouts above it), so an action names the page without spelling a path; because keys match by prefix, revalidate("src/routes/stories") refetches every page under the directory (pathless layouts have no route path of their own, so the file is what tells them apart). The directive has to be the first statement of the inline default export — behind a wrapper call or a re-export the scanner cannot see it, the page is code-split like a client page, and in development the adapter throws a directed error when the chunk resolves.
A live page names its wrapper in the route config — defineFileRoute("/feed", { query: liveQuery }) — and the adapter sources through that instead of query. The route file imports liveQuery, so only an app with a live page carries it.
Apps with no server page pay nothing for any of this. The plugin folds the scan into filesystem-routing/flags, and the adapter's only path to serverRouteComponent and query is a module gated on that constant, so the branch — and with it the frames runtime — tree-shakes away. pnpm build asserts it.
paths is a proxy inferred from the route tree. Property access descends into static segments, calls bind params, and it mirrors URL anatomy — params, then a search object, then a hash string:
paths.users(123); // ok — matchFilters flow into the callsite
paths.users(2).settings; // chainable into children
paths.users(2, { tab: "x" }, "comments"); // "/users/2?tab=x#comments"
paths.about(); // zero-arg/search calls terminate to a plain string
paths(); // "/" — the rootEvery node coerces via toString, so nodes drop straight into href, navigate(), and redirect() without explicit termination. Nodes include the router's base, so they are the portable way to link under one: a plain string that starts with / is a full path everywhere (href, navigate(), useLinkState, useResolvedPath, redirect()), and the base is never added to it. Accessing a segment that doesn't exist in the tree, or binding a param with the wrong type, is a compile error.
There is no link component. Use <a>; the router intercepts same-origin clicks through delegation and manages link state through compiler-claimed anchors — correct at creation (so late mounts under <Show>, <For>, or portals are never stale) and refreshed if a dynamic href changes.
Behavior modifiers are attributes, so they work identically in client, server-rendered, and third-party markup:
| attribute | description |
|---|---|
replace |
Replace the history entry instead of pushing |
noscroll |
Turn off scrolling to the top after navigation |
state |
JSON string pushed onto the history stack |
preload |
"false" opts this link out of all preloading; "viewport" or "eager" opts it into that strategy |
link |
Marks a router link when explicitLinks is enabled |
target |
Any value (e.g. _self) opts the anchor out of router handling |
<a href={paths.login} replace>Log in</a>
<a href={paths.docs} noscroll>Docs</a>
<a href="https://example.com">External — untouched</a>Active and pending state is styled with CSS — one vocabulary for every kind of link. aria-current and data-active are automatic; data-pending is opt-in:
nav a[aria-current="page"] {
font-weight: 600;
} /* exact match, query included */
nav a[data-active] {
color: var(--accent);
} /* exact or prefix match on the path */
a[data-pending] {
opacity: 0.6;
} /* target of in-flight navigation — needs `links: pendingLinks` */data-pending is opt-in, so an app that never shows pending link state doesn't ship the code that computes it. Pass the pendingLinks plugin to the router:
import { createRouter, pendingLinks } from "@solidjs/router";
const Router = createRouter({ routes, links: pendingLinks });It marks the links whose path covers the in-flight destination of a link click or navigate() call — by the same path rule as data-active — until that navigation lands. Back/forward traversals don't mark links pending. data-pending agrees with useLinkState().pending at every moment; the hook works with or without the plugin.
One rule decides both, for anchors and useLinkState alike:
- current (
aria-current="page") — same path and same query, ignoring parameter order and the hash. On/?filter=active,<a href="/?filter=active">is current and<a href="/">is not. - active (
data-active, anddata-pendingfor the in-flight target) — the path only, exact or prefix, so both of those links are active there. The root path (the router'sbase, when it has one) only ever matches exactly, sohref={paths()}doesn't light up on every page.
An aria-current you write yourself (aria-current="step" in a stepper, say) is yours: the router never overwrites or removes it, and only manages the attribute on links where it set it.
For component-library links that need reactive state beyond CSS, useLinkState is the programmatic counterpart of the attribute vocabulary:
import { useLinkState } from "@solidjs/router";
function TabLink(props: { href: string; children: JSX.Element }) {
const link = useLinkState(() => props.href);
return (
<a href={props.href} class="tab" data-selected={link.active() || undefined}>
{props.children}
</a>
);
}The router can warm a link's route before it is clicked: preloading code loads the matched routes' lazy() components (and any lazy subtree on the way), and preloading data also runs their preload functions with intent: "preload". Nothing is preloaded unless you opt in. Earlier versions preloaded on hover, focus, and touch by default; that built-in is gone. A boolean preloadLinks is a type error and, in development, a warning — it preloads nothing.
import { createRouter, intentPreload } from "@solidjs/router";
const Router = createRouter({ routes, preloadLinks: intentPreload() });| strategy | preloads a link when | defaults |
|---|---|---|
intentPreload({ delay = 20, data = true }) |
the pointer rests on it for delay ms, it is focused (focusin), or a touch starts on it (touchstart). Moving over a link that already preloaded does not preload it again until the pointer leaves |
code and data |
tapPreload({ data = true }) |
a pointer goes down on it (pointerdown: mouse, touch, or pen), ahead of the click |
code and data |
viewportPreload({ all = false, data = false, delay = 100, rootMargin }) |
it has stayed in the viewport for delay ms and the browser is then idle (requestIdleCallback, or setTimeout if that is missing). Once per href; leaving before the idle flush cancels it, and a new href preloads again. One shared IntersectionObserver. rootMargin is passed through (the observer's own "0px" when omitted) |
code |
eagerPreload({ all = false, data = false }) |
the page has loaded and the browser is idle, including links mounted later. Once per href; a link removed before that flush is dropped |
code |
Pass an array to combine strategies — viewport for code, intent for data:
const Router = createRouter({
routes,
preloadLinks: [viewportPreload({ all: true }), intentPreload()]
});Strategies are client-only, and an app ships only the ones it imports. intentPreload and tapPreload apply to every router link. viewportPreload and eagerPreload apply only to links that name them, <a href="/pricing" preload="viewport"> or preload="eager", unless created with { all: true }. They also skip preloading when the browser reports Save-Data or a 2g connection (effectiveType of "2g" or "slow-2g").
The href and preload attribute are read when the preload runs, so a dynamic href is the one the link has then.
Hover, focus, and touch preloads do not check modifier keys or defaultPrevented, and neither does tapPreload's pointerdown. A click still does: the router ignores it when preventDefault was already called, when it is not the primary button, or when alt, ctrl, meta, or shift is held.
Preloading is purely an optimization: without it every navigation still loads the same code and data, just after the click instead of before it. A link with preload="false" is never preloaded by any strategy.
Whether a strategy also preloads data is its own data option, not a per-link choice. intentPreload and tapPreload default to data because the user is about to click; a data preload runs only for route levels the navigation would change, and query keeps the result for the few seconds until the click arrives. viewportPreload and eagerPreload warm links that are merely on screen or already on the page, so they default to code only — a data preload there is worth it only when the cache outlives the moment of clicking, as with TanStack Query or an HTTP-cached GET server function. Pass { data: true } to opt in.
usePreloadRoute triggers the same work by hand.
Even with smart caches, waterfalls happen when data fetching waits on view logic or lazy-loaded code. Preload functions start fetching data in parallel with loading the route — called when a route renders, and eagerly when the router preloads a link with data.
import { lazy } from "solid-js";
const User = lazy(() => import("./pages/users/[id].js"));
function preloadUser({ params, location }) {
void getUser(params.id);
}
const routes = defineRoutes([{ path: "/users/:id", component: User, preload: preloadUser }]);The preload function receives:
| key | type | description |
|---|---|---|
| params | object | The route parameters (same value as useParams() inside the route component) |
| location | { pathname, search, hash, query, state, key } |
Path information (corresponds to useLocation()) |
| intent | "initial" | "navigate" | "native" | "preload" |
Why this is being called: initial — first render; navigate — router navigation; native — browser back/forward; preload — link preloading, not navigating |
The factory-level preload option is the app-wide counterpart: it runs once per mount/request with the merged params of every match, and its result reaches the root render-prop as props.data.
These are entirely optional, but they demonstrate the power of the preload mechanism.
Wrap a fetching function to dedupe calls and participate in revalidation:
const getUser = query(async id => {
return (await fetch(`/api/users/${id}`)).json();
}, "users"); // query key; arguments are serialized alongside itA query:
- Dedupes on the server for the lifetime of the request.
- Fills a preload cache in the browser lasting 5 seconds, so link preloads and route entry share one fetch.
- Refetches reactively by key on action revalidation.
- Serves as a back/forward cache for browser navigation up to 5 minutes; user-initiated navigation bypasses it.
After a query rejects in the browser, a subsequent read can fetch again immediately. For example, an <Errored> fallback can call reset() to retry the query.
Consume results directly with Solid primitives — there is no router-specific async wrapper:
const user = createMemo(() => getUser(params.id));
return <h1>{user().name}</h1>;
// deeply reactive object data
const todos = createProjection(() => getTodos(), []);Keys support targeted invalidation:
getUser.key; // "users"
getUser.keyFor(5); // "users[5]"Revalidate with the revalidate export or by setting revalidate keys on action responses — the whole key invalidates every entry for the query, keyFor invalidates one.
A query may also redirect: a guard read that throws or returns redirect() (from @solidjs/web) navigates instead of resolving. A path starting with a single / is a full path, as everywhere in the router: the base is never added, so redirect(paths.login) and redirect("/app/login") both land on /app/login under base: "/app". Same-origin targets navigate softly with replace only within the router's base, when the history integration can represent their URL; otherwise they navigate the document. On the client, a Location header only navigates for redirect statuses (301, 302, 303, 307, 308). For example, returning respond({ id: 1 }, { status: 201, headers: { Location: "/items/1" } }) delivers { id: 1 } without navigating. Any revalidate keys on a redirect response invalidate first, and the client read stays pending so nothing renders the redirect as data. This holds for "use server" queries too, where the transport carries the redirect to the client rather than letting fetch follow it. The carrier takes precedence over Location.
query's live sibling: a keyed query over a value-shaped stream. The function is an async iterable (typically an async generator server function) whose yields are successive values of one logical query — each yield is the current state, not an event — with the contract that it re-yields current state on every invocation:
const roomMessages = liveQuery(async function* (room: string) {
"use server";
yield await db.messages.list(room); // current state, immediately
for await (const change of db.messages.watch(room)) {
yield await db.messages.list(room); // current state again, on change
}
}, "messages");Declaring it is what makes it live — no separate wrapper, and server functions are declared GET at creation just like query. Consumption is the same story as query: Solid primitives, no router-specific async wrapper. The value updates in place as yields arrive:
const messages = createMemo(() => roomMessages(params.room));
return <For each={messages()}>{msg => <Message {...msg} />}</For>;One connection per key (name + arguments) is shared by every consumer: late subscribers get the latest value immediately, delivery is latest-wins, and the connection closes when the last consumer leaves. A connected stream that dies transiently (network, 5xx) reconnects with exponential backoff while the latest value keeps serving; a definite rejection (4xx) or a first-connect failure surfaces to the consumer like any thrown error.
Live queries ride the router's existing machinery rather than adding their own:
- Preload — calling one in a preload function warms the connection, so navigation renders against an already-delivered value instead of holding the transition on connect.
- SSR — the document face renders the first value; hydration adopts it and reconnects. Server-side, consumers of a key within one request observe the same value.
- Revalidation — explicit
revalidate(key)reconnects (the producer re-yields current state by contract). The post-mutation sweep leaves healthy connections alone: the stream is its own freshness mechanism. - Single-flight — live keys are neither collected nor swept: the stream is the freshness mechanism, and a mutation reaches a live query through its producer (the
watchyielding the changed state), not through the mutation response. The flight-data seam that pushes payload values into open channels stays available to an integration that collects live keys itself.
The callable carries the query conventions (key, keyFor) plus a reactive status(...args) read ("idle" | "connecting" | "connected" | "reconnecting" | "closed") for surfacing connection state in UI.
A form action is an action with a URL — Solid's action primitive plus a form binding: URL addressability, submission tracking, aria-busy, and no-JS posts. Data helpers come from the router; response helpers (redirect, reload) come from @solidjs/web — they're protocol-level and work without the router:
import { formAction } from "@solidjs/router";
import { redirect } from "@solidjs/web";
import { paths } from "./router";
const updateUser = formAction(async (form: FormData) => {
await db.users.update(form.get("id"), form);
throw redirect(paths.users(form.get("id"))); // typed paths work in redirects
});<form action={updateUser} method="post">
<button>Save</button>
</form>
// or
<button type="submit" formaction={updateUser}>Save</button>Form actions only work with POST requests, so put method="post" on your form. Submitting forms get aria-busy="true" automatically from submit until the action's result is on screen — the mutation, then its revalidation or redirect, until that update commits — the same CSS story as links:
form[aria-busy] button {
pointer-events: none;
opacity: 0.6;
}Busy state belongs to the form's action URL, not the element: a form re-rendered or replaced mid-flight (a server-component morph, a keyed re-mount) still shows it. An aria-busy you set yourself is left alone.
Forms work without JavaScript: a real POST, a redirect back, and the result seeded into submission state through a one-shot flash cookie. Single-flight mutations are on by default — the mutation response carries the refreshed route data in the same round trip.
Single flight is the router's, not the form action's: a mounted router applies any server function's revalidation keys, redirect(), reload(), and flight data, so a mutation called straight from an event handler needs no wrapper — call the server function (or a core action around it) directly. singleFlight={false} on the router opts out.
Every POST server function call is treated as a mutation. POST is the default for server functions. A call that declares no
revalidatekeys has the server re-collect the current page's data, and the client then revalidates everyqueryon screen, the same default form actions have always had. Reads are exempt when they go throughquery(), which switches a server function toGETautomatically, or when the function is declared withGET(fn). A POST that isn't a mutation (logging, a search called on keystroke) should returnrespond(value, { revalidate: "" })(orrespond(null, { revalidate: "" })with nothing to return) to touch nothing, or name the keys it did change.
Delegation doesn't require the action's module on the client either. A form bound directly to a server action in a server-only module (a server component) renders a plain action="/_server?id=...&args=..." — a self-describing URL. On submit, the router synthesizes the invocation from it: the form data posts to that URL through the server-function transport, .with() arguments ride along in the query string, and submissions, aria-busy, redirects, revalidation, and single-flight data flow through the normal pipeline. The handler loads lazily on first such submit, so router-only bundles don't carry the data layer. The no-JS POST above remains the fallback only for clients that actually have no JavaScript. (Client-only form actions — formAction(fn, "name") without use server — are their module's JS by definition and still require it on the client.)
For optimistic UI, attach owner-scoped hooks to the action and use Solid's optimistic primitives for rendered state:
import { createOptimisticStore } from "solid-js";
import { formAction, query } from "@solidjs/router";
const getTodos = query(async () => fetchTodos(), "todos");
const [todos, setTodos] = createOptimisticStore(() => getTodos(), []);
const addTodo = formAction(async todo => {
await saveTodo(todo);
return { ok: true, todo };
}, "add-todo").onSubmit(todo => {
setTodos(items => {
items.push({ ...todo, pending: true });
});
});onSubmit(...) registers a listener in the current reactive owner — multiple components can register against the same action, and hooks are removed when their owner is disposed. onSettled(...) works the same way for observing completed submissions. A submission settles when its result is on screen: the hooks run, the record enters useSubmissions, and aria-busy clears once the action's update commits — after any revalidation or redirect it triggered, which may be later than the promise from a direct call resolves. The hooks that run are the ones registered when the action finished: a hook whose owner that commit unmounts (the page a redirect leaves) still sees the submission, while a hook registered later, or removed with its owner before then, does not.
The preferred pattern is returning values and letting the client interpret the result; thrown errors are still captured on Submission.error as an escape hatch.
Form actions have a with method (like bind) for typed arguments instead of hidden form fields:
const deleteTodo = formAction(api.deleteTodo);
<form action={deleteTodo.with(todo.id)} method="post">
<button type="submit">Delete</button>
</form>;Since form actions serialize to string attributes that must match across SSR, form actions that aren't server functions need a stable name: formAction(fn, "my-action").
Deprecated, with no replacement: outside a form, call the server function (or a core action) directly — the router applies its revalidation and redirect either way. Still works, with a dev warning, until the next major.
Returns settled submission records for an action — the durable history layer, not in-flight state. Useful for reading completed results, clearing old submissions, retrying, or replaying settled errors:
const submissions = useSubmissions(addTodo, input => filter(input));
const latest = submissions.at(-1);
// { input, result?, error, url, clear(), retry() }The list is history: a later submission never removes an earlier record, including one that returns nothing, so every failed row of a list keeps its own retry(). Records go away through their own clear() / retry(), and every client navigation clears the list. A form that shows only its latest outcome clears the old records when a new submission starts:
const submissions = useSubmissions(addTodo);
addTodo.onSubmit(() => submissions.forEach(s => s.clear()));
const error = () => submissions.at(-1)?.error;Use Solid's createOptimistic / createOptimisticStore for in-flight UI.
Give a route a Standard Schema validator (Valibot, Zod, ArkType, hand-rolled…) and its types flow into paths and useSearchParams:
import * as v from "valibot";
const routes = defineRoutes([
{
path: "/search",
component: Search,
search: v.object({
q: v.optional(v.string(), ""),
page: v.optional(v.pipe(v.unknown(), v.transform(Number)), 1)
})
}
]);const [search, setSearch] = useSearchParams(paths.search);
search.page; // number (parsed, not "2")
setSearch({ page: search.page + 1 }); // typed setter
<a href={paths.search({ q: "solid", page: 2 })}>Search</a>; // typed builderWithout a schema, useSearchParams() behaves as before: raw string values, merge-on-set semantics ('', undefined, and null remove keys), navigation-like updates with auto-scrolling disabled.
createRouter(config);| option | type | description |
|---|---|---|
routes |
RouteDefinition[] |
The route tree — inline arrays infer literally; wrap extracted trees in defineRoutes |
base |
string |
Base url to use for matching routes. A path that starts with / is a full path; use paths for base-aware links |
preload |
RoutePreloadFunc |
App-wide preload: once per mount/request, result reaches the root render-prop as props.data |
history |
RouterHistory |
History adapter; defaults to browser history on the client and the request URL on the server |
singleFlight |
boolean |
Single-flight mutations, default true |
actionBase |
string |
Root url for server actions, default /_server |
preloadLinks |
LinkPreload | LinkPreload[] |
Link preload strategies, e.g. intentPreload(); none by default. A boolean is a type error |
explicitLinks |
boolean |
Require the link attribute for router handling instead of intercepting all anchors, default false |
links |
LinksPlugin |
Link claims plugin — pendingLinks adds data-pending to the in-flight navigation's target |
transformUrl |
(url: string) => string |
Rewrite URLs before matching |
Under Vite's base, pass import.meta.env.BASE_URL as the router base and link with paths, so links, navigate() and redirect() follow it.
The returned instance is the provider component and carries the static surface:
| member | description |
|---|---|
paths |
The typed path proxy |
match |
Pure matching against an arbitrary URL — no rendering or request context; root→leaf, [] if none |
routes |
The config tree |
config |
The full config — lets server integrations consume the instance directly |
Hooks read the live session off router context.
Retrieves a reactive, store-like object of the current route's path parameters. Pass a paths node for typing:
const params = useParams(); // Params (strings)
const params = useParams(paths.users); // { id: string } — typed from the treeInside a route's own component/preload, defineRoute types props.params without a witness.
Retrieves a method to navigate. Accepts a string or a typed path node, plus options:
resolve(boolean, defaulttrue): resolve the path against the current routereplace(boolean, defaultfalse): replace the history entryscroll(boolean, defaulttrue): scroll to top after navigationstate(any): pass custom state tolocation.state(serialized with structured clone)
const navigate = useNavigate();
navigate(paths.login, { replace: true });A string that starts with / is a full path, like an href: under base: "/app", navigate("/about") goes to /about, not /app/about. Use paths.about (or `${base}/about`) for a path under the base. A full path outside the base is another document, so navigate() loads it (as an anchor or a redirect to it does).
For declarative redirects on render (the old <Navigate>), call it during component setup or redirect from a preload.
Retrieves the reactive location object:
const location = useLocation();
const pathname = createMemo(() => parsePath(location.pathname));Returns true under a router and false elsewhere. The other primitives throw outside a router, so a component that also renders outside it (an error fallback above the router, for example) can check first. Like them, it reads from the reactive owner, so call it during component setup, not from an event handler:
const location = useInRouter() ? useLocation() : undefined;See Typed Search Params. Reads are proxied — access properties to subscribe.
A signal indicating whether the router is processing a navigation — useful for pending UI while the next route and its data settle. It's the way to read routing state: RouterContext doesn't carry isRouting or pendingTarget.
const isRouting = useIsRouting();
return <div classList={{ "grey-out": isRouting() }}>...</div>;The router doesn't expose where a navigation is heading; read it off the location with Solid's isPending and latest. It covers back/forward traversals too:
import { isPending, latest } from "solid-js";
const location = useLocation();
const target = () =>
isPending(() => location.pathname) ? latest(() => location.pathname) : undefined;In Solid's dev and observe builds the router also declares every navigation to the attribution engine (solid-js/attribution): holds and re-runs caused by a navigation are named after the route pattern (navigation to /users/:id), timed from the user event that started it, and redirect hops fold onto the navigation they belong to. A link click or a native form submit the router handles runs in the interaction Solid records for that event, so the navigation or action belongs to the same record as any onClick work for that click. attribution.history("navigation") and feedback().navigations list them; nothing of this exists in production builds.
Tests a path pattern you supply against the current location; returns a memo of match information or undefined. It never consults the route tree — the pattern doesn't have to correspond to a defined route. The match's params are typed from the pattern, and a typed path node works too (a concrete URL — useful for "am I here" checks):
const match = useMatch(() => "/admin/*rest");
match()?.params.rest; // string
return <Show when={match()}>...</Show>;
const here = useMatch(() => paths.users(2));Returns an accessor of the router's resolved matches for the current location — the chain of route definitions producing the current render, outermost first. This is the counterpart to useMatch: one reflects the route tree, the other tests a pattern. Useful for reading info metadata:
const matches = useRouteMatches();
const breadcrumbs = createMemo(() => matches().map(m => m.route.info?.breadcrumb));info is freeform by default; augment RouteInfo to type it app-wide — declared keys are checked at route definitions and typed on reads:
declare module "@solidjs/router" {
interface RouteInfo {
breadcrumb?: string;
}
}Returns a function to preload a route manually — the same work link preloading triggers automatically. Accepts strings, URLs, and typed path nodes:
const preload = usePreloadRoute();
preload(paths.users(2).settings, { preloadData: true });Reactive active/current/pending state for custom link components, matched by the same rule as plain anchors:
current()— same path and same query as the location, ignoring parameter order and the hash (whataria-current="page"reflects)active()— the location's path is the link's path or lives under it, query ignored (data-active); a root link (the router'sbase, or/without one) is exact-onlypending()— the link's path is the target of an in-flight navigation, back/forward excluded (data-pending). Works without thependingLinksplugin, which only adds the attribute to plain anchors
Pass { end: true } to make active (and pending) exact-path for any link.
const link = useLinkState(() => props.href, { end: true });Takes a function called before leaving a route. The blocking machinery is installed lazily on first use, so apps that never call useBeforeLeave don't pay for it in their bundle. The handler receives:
from(Location): current location (before change)to(string | number): path passed tonavigateoptions(NavigateOptions): options passed tonavigatepreventDefault(): call to block the route changedefaultPrevented(readonly boolean):trueif any previous handler calledpreventDefaultretry(force?): retry the navigation, e.g. after confirming with the user; passtrueto skip re-running leave handlers
useBeforeLeave((e: BeforeLeaveEventArgs) => {
if (form.isDirty && !e.defaultPrevented) {
e.preventDefault();
setTimeout(() => {
if (window.confirm("Discard unsaved changes - are you sure?")) {
e.retry(true);
}
}, 100);
}
});History adapters are plain imports, so unused ones never enter your bundle:
import { createRouter, hashHistory, memoryHistory } from "@solidjs/router";
// hash mode
const Router = createRouter({ routes, history: hashHistory() });
// tests and non-browser environments
const Router = createRouter({ routes, history: memoryHistory("/users/1") });On runtimes without Proxy support (some older smart TVs), the core router still works: typed paths are built lazily so they only require Proxy if you access them, and params/location.query can be swapped to a Proxy-free implementation through the history adapter's paramsWrapper/queryWrapper utils:
const base = browserHistory();
const history = {
...base,
// wrappers build objects with defined getters instead of a Proxy
utils: { ...base.utils, paramsWrapper, queryWrapper }
};
const Router = createRouter({ routes, history });On the server the request URL drives rendering automatically. Without a request event (SSG scripts, server-side tests), the configured history adapter provides the location, so memoryHistory("/page") renders that page isomorphically.
The instance also matches arbitrary URLs anywhere — server middleware, sitemap generation, tests — with no rendering involved:
import { Router } from "./router";
Router.match("/users/2/settings?tab=x");
// [
// { path: "/users/:id", match: "/users/2", params: { id: "2" } },
// { path: "/settings", match: "/users/2/settings", params: {} }
// ]Framework handler wiring lives in @solidjs/router/server. The integration accepts the router instance directly — its routes, base, and preload are the single source of truth:
import { createFlightDataCollector } from "@solidjs/router/server";
import { Router } from "./app/router";
const collectFlightData = createFlightDataCollector(Router);createFlightDataCollector produces the single-flight hook: after a mutation it reruns the route data the mutation invalidated for the page the client is on (or is redirected to), folding fresh data into the same response. This policy previously lived inside SolidStart; the router now owns it, so custom server setups get single-flight mutations without a framework.
The no-JS form convention needs no wiring at all: the server function runtime answers form posts made without the client runtime by redirecting back with the outcome in a one-shot flash cookie, and the router's SSR reads it into submission state. To configure it (e.g. a base path), pass createNoJSHandler(options) from @solidjs/web/server-functions/server as the handler's handleNoJS.
This guide maps from the stable 0.x releases (Solid 1). 1.0 removes the component-based API — the createRouter factory is the only way to set up the router, and plain <a> elements are the only link primitive. 1.0 also targets Solid 2, so the async data patterns change alongside the router API.
// 0.x
<Router root={App}>
<Route path="/users" component={Users} />
<Route path="/users/:id" component={User} />
</Router>;
// 1.0
const Router = createRouter({
routes: [
{ path: "/users", component: Users },
{ path: "/users/:id", component: User }
]
});
<Router>{props => <App {...props} />}</Router>;<HashRouter>→createRouter({ routes, history: hashHistory() })<MemoryRouter>/createMemoryHistory→createRouter({ routes, history: memoryHistory("/initial") })<StaticRouter url>/<Router url>for SSR → automatic from the request URL; without a request event, passmemoryHistory(url)rootprop → the render-prop child;rootPreload→ the factory'spreloadoption
Route props map 1:1 onto definition keys (path, component, preload, matchFilters, info); nesting becomes children arrays. Wrap extracted route trees in defineRoutes to get typed paths. File-based routing generates config.
<A href replace noScroll state>→<a href replace noscroll state>(attributes, all lowercase)activeClass/inactiveClass→ CSS attribute selectors on[data-active]/[aria-current="page"]end→ style exact matches with[aria-current="page"](which also compares the query) instead of[data-active]; the root path already only matches exactly- Pending link styling →
[data-pending], opt-in withcreateRouter({ routes, links: pendingLinks }) - Route-relative hrefs → typed
paths;useResolvedPath/useHrefremain for manual resolution - Custom link components →
useLinkState - Hover/focus preloading is opt-in →
createRouter({ routes, preloadLinks: intentPreload() });preload="false"on a link skips it entirely.<A>preloaded on hover by default
<Navigate>→ calluseNavigate()during component setup, or redirect from a preloaduseCurrentMatches→useRouteMatches(same behavior)redirect/reload→ import from@solidjs/web; they're protocol-level and work without the routerjson(data, init)→respond(data, init)from@solidjs/webcache(deprecated alias) →queryaction→formAction(Action→FormAction); the old names remain as deprecated aliases with a dev warning.actionis solid-js's own primitive.useAction→ deprecated with no replacement; call the server function or a coreactiondirectlyRouterContext'sisRouting/pendingTarget→useIsRouting(); for the in-flight destination, theisPending/latestrecipe
createAsync/createAsyncStoreare gone — readquery()results with Solid 2 primitives:createMemo,createProjection,createOptimistic,createOptimisticStore.
// 0.x
const user = createAsync(() => getUser(params.id));
// 1.0
const user = createMemo(() => getUser(params.id));query()stays the source of truth for cached reads and invalidation.useSubmission(singular) is gone, and submissions are now settled history rather than in-flight state. Pending/optimistic UI moves to Solid's optimistic primitives fed by the action's.onSubmit(...)hook; read settled results withuseSubmissions()and select the latest with.at(-1)(clear old records in.onSubmitwhen a form shows only its latest outcome).
// 0.x — read in-flight state off the submission
const submitting = useSubmission(addTodo);
<span>{submitting.pending && "Saving..."}</span>;
// 1.0 — optimistic primitives own in-flight state
const [todos, setTodos] = createOptimisticStore(() => getTodos(), []);
const addTodo = formAction(saveTodo).onSubmit(todo =>
setTodos(items => {
items.push({ ...todo, pending: true });
})
);- Action lifecycle centers on instance methods:
.onSubmit(...)for owner-scoped optimistic work,.onSettled(...)for observing completions. Returned values are the expected result channel; thrown errors land onSubmission.error.
When deploying a client-side-routed application without server-side rendering, you need to handle redirects to your index page so that loading other URLs doesn't return a 404.
On Netlify, create a _redirects file:
/* /index.html 200On Vercel, add a rewrites section to vercel.json:
{
"rewrites": [
{
"source": "/(.*)",
"destination": "/index.html"
}
]
}