Routing
Match URLs to views, read the current location, and navigate with links.
Xote comes with a router built on signals. The current URL is a signal, so a route change is an ordinary reactive update: the matching view swaps in and nothing else re-renders.
Set up the router
Initialize the router once, then render your routes.
1open Xote23Router.init()45let app = () => {6 <div>7 {Router.routes([8 {pattern: "/", render: _ => <HomePage />},9 {pattern: "/users/:id", render: params =>10 switch params->Dict.get("id") {11 | Some(id) => <UserPage id />12 | None => <NotFoundPage />13 }14 },15 ])}16 </div>17}
Read the current location
Router.location() returns the shared location signal. Read it with Signal.get wherever you need the current URL.
1Effect.run(() => {2 let current = Signal.get(Router.location())3 Console.log2("Current path:", current.pathname)4 None5})
The location record has pathname, search and hash.
Match routes
Patterns can be static or dynamic. A dynamic segment is written :name, and its value arrives in the params dictionary.
1{pattern: "/", render: _ => <HomePage />}2{pattern: "/about", render: _ => <AboutPage />}3{pattern: "/users/:id", render: params =>4 switch params->Dict.get("id") {5 | Some(id) => <UserPage id />6 | None => <NotFoundPage />7 }8}
Navigate from code
Router.push adds a history entry; Router.replace replaces the current one. Both take optional ~search and ~hash.
1Router.push("/users/123", ())2Router.push("/search", ~search="?q=xote", ())3Router.replace("/login", ())
Link between pages
Router.Link renders a real <a href>, so middle-click, "open in new tab" and crawlers work normally. Only a plain left click is intercepted, and the page doesn't reload.
1module Nav = {2 @xote.component3 let make = () =>4 <nav>5 <Router.Link to="/" class="nav-link"> {"Home"} </Router.Link>6 <Router.Link to="/docs" class="nav-link"> {"Docs"} </Router.Link>7 </nav>8}
Server rendering
On the server, use Router.initSSR instead of Router.init. It sets the starting location without touching browser APIs. See Server rendering for the full setup.
1Router.initSSR(2 ~pathname="/docs",3 ~search="?tab=signals",4 (),5)
Example: app with navigation
1open Xote23Router.init()45module Nav = {6 @xote.component7 let make = () =>8 <nav>9 <Router.Link to="/"> {"Home"} </Router.Link>10 <Router.Link to="/users"> {"Users"} </Router.Link>11 </nav>12}1314let app = () => {15 <div>16 <Nav />17 {Router.routes([18 {pattern: "/", render: _ => <HomePage />},19 {pattern: "/users", render: _ => <UsersPage />},20 {pattern: "/users/:id", render: params =>21 switch params->Dict.get("id") {22 | Some(id) => <UserPage id />23 | None => <NotFoundPage />24 }25 },26 ])}27 </div>28}
Tips
- Initialize the router once at the app's entry point, not from leaf components.
- Treat
Router.location()as shared state. Read it where you need it instead of copying it elsewhere. - Prefer
Router.Linkfor ordinary navigation, so the intent stays obvious in markup. - Use
Router.initSSRon the server so routing matches between server rendering and hydration. - Hosting under a subpath? Pass
~basePathtoRouter.init; Deploying covers hosting.
Summary
The router is a single global signal of the current app-relative location (Router.location()), updated by Router.push, Router.replace, link clicks and the browser's back and forward buttons. Router.routes renders the first entry whose pattern matches; Router.route renders one pattern on its own; Router.link and <Router.Link> render a real <a href> that navigates without a page load. Call Router.init() once in the browser entry and Router.initSSR(...) once per request on the server, before rendering. The rule that matters most: a matched screen is rebuilt on every location change, including query-string and hash changes, so state that must survive navigation MUST live outside the screen.
Availability
| Item | Value |
|---|---|
| Modules | Router (navigation, rendering), Route (pure pattern matching) |
| Import / entry | xote (with -open Xote), or xote/router; Route via xote/route |
| First stable version | 1.0.0 (signal-based router with pattern matching); basePath since 4.10.0; scroll restoration since 4.13.0; Router.initSSR since 4.16.0; scrolling to the hash target after navigation since 7.0.0 |
| Status | stable since 7.1.0 |
| PPX required | No. Router.link and Router.routes are plain functions; <Router.Link> is a JSX component |
Rules
- Router state is a global singleton stored under
Symbol.for("xote.router.state")onglobalThis. Every copy of Xote bundled into the page (for example an app and a component library) shares the same location signal and base path. Router.init(~basePath=?, ())normalizes the base path (leading/, no trailing/;""and"/"mean none), sets the location fromwindow.locationwith the base path stripped, and installs onepopstatelistener (only on the first call). Calling it again updates the base path and re-reads the URL; it is idempotent otherwise.Router.initSSR(~basePath=?, ~pathname=?, ~search=?, ~hash=?, ())sets the base path and the location signal without touching browser APIs.pathnameis app-relative (base path already removed). Call it before every server render, because the state is global (rule 1).Router.location()returnsSignal.t<location>withpathname(app-relative),search(with leading?, or"") andhash(with leading#, or""). Read it withSignal.getin a tracking scope to react to navigation.Router.push(pathname, ~search=?, ~hash=?, ())saves the current scroll position into the current history entry, pushes a new entry for the base path pluspathname ++ search ++ hash, sets the location signal, then scrolls: to the element whose id matches the hash (on a microtask), or to the top when there is no hash.Router.replace(...)does the same aspushwithout saving scroll position and without adding a history entry.- Back/forward (
popstate) re-reads the URL into the location signal and restores the scroll position saved by rule 5 for that entry, if any. - Pattern syntax:
/-separated segments; a segment starting with:captures that whole segment under its name; any other segment is a literal. There are no wildcards, optional segments or regex:*is a literal segment. - Matching is exact on the number of non-empty segments:
/users/:idmatches/users/42but not/users/42/editor/users. Empty segments are ignored, so a trailing slash does not matter (/docsmatches/docs/). Matching is case-sensitive and ignoressearchandhash. - Captured parameters are raw path segments (
Dict.t<string>): they are not URL-decoded (/u/a%20bgives"a%20b"). Decode withdecodeURIComponentif needed. Router.routes(configs)renders the first matching entry in array order, and nothing when no entry matches.Router.route(pattern, render)rendersrender(params)while the pattern matches, and nothing otherwise. Severalroutecalls can match at once.- Both
routesandrouteare reactive regions over the whole location: every location change (pathname, search or hash) re-runs the match and callsrenderagain, replacing the screen's DOM and disposing everything it owned, even when the same entry still matches. Router.link(~to, ~attrs=?, ~children=?, ())and<Router.Link to=...>parsetoaspath?query#hash, render<a href>with the base path added, and on everyclickevent callpreventDefaultandRouter.push. Modifier clicks (Ctrl/Cmd/Shift + click) andtarget="_blank"links are intercepted too; middle-click does not fireclickand is not intercepted.<Router.Link>'sonClickhandler runs after the navigation (Router.push) has happened.- Using
push,replace,route,routes,linkorLinkbeforeinit/initSSRlogs a[Xote Router] ... called before Router.init()warning; the location is then the default/.
API
| Name | Signature | Behaviour |
|---|---|---|
Router.location | unit => Signal.t<location> | The current app-relative location signal. |
Router.init | (~basePath: string=?, unit) => unit | Browser setup: read URL, listen to popstate. |
Router.initSSR | (~basePath: string=?, ~pathname: string=?, ~search: string=?, ~hash: string=?, unit) => unit | Server setup: seed the location for one render. |
Router.push | (string, ~search: string=?, ~hash: string=?, unit) => unit | Navigate with a new history entry, then scroll. |
Router.replace | (string, ~search: string=?, ~hash: string=?, unit) => unit | Navigate replacing the current entry, then scroll. |
Router.routeConfig | {pattern: string, render: Route.params => View.node} | One entry of a routes table. |
Router.route | (string, Route.params => View.node) => View.node | Render while one pattern matches. |
Router.routes | array<routeConfig> => View.node | Render the first matching entry. |
Router.link | (~to: string, ~attrs: array<(string, View.attrValue)>=?, ~children: array<View.node>=?, unit) => View.node | Anchor that navigates client-side. |
Router.Link | props to, class?, id?, style?, target?, ariaLabel?, attrs?, onClick?, children? | JSX anchor; class etc. accept a value, a signal or a thunk. |
Route.match | (string, string) => matchResult | Pure match of a pattern against a pathname: Match(params) or NoMatch. |
Route.params | Dict.t<string> | Captured :name segments. |
Patterns
Use for the standard app shell: initialize in the entry, render a route table, link with <Router.Link>, and mark the active link with a thunk (props of Router.Link are not made reactive by the PPX, so the thunk is required).
1module App = {2 @xote.component3 let make = () =>4 <div>5 <nav>6 <Router.Link7 to="/"8 class={() => Signal.get(Router.location()).pathname == "/" ? "nav-link active" : "nav-link"}>9 {"Home"}10 </Router.Link>11 <Router.Link to="/users/42" class="nav-link"> {"User 42"} </Router.Link>12 </nav>13 {Router.routes([14 {pattern: "/", render: _ => <h1> {"Home"} </h1>},15 {16 pattern: "/users/:id",17 render: params => <UserPage id={params->Dict.get("id")->Option.getOr("")} />,18 },19 ])}20 </div>21}2223// Browser entry24Router.init()25View.mountById(<App />, "app")
Use when the app is served from a subdirectory: pass the same base path everywhere; patterns, push, replace and to stay root-relative.
1Router.init(~basePath="/my-app", ())
Use for a not-found screen. routes renders nothing for an unmatched path, and a /:rest entry only catches single-segment paths, so check the patterns yourself:
1let patterns = ["/", "/users/:id"]23let isKnown = (pathname: string) =>4 patterns->Array.some(pattern =>5 switch Route.match(pattern, pathname) {6 | Match(_) => true7 | NoMatch => false8 }9 )1011// Inside the app's JSX, next to the routes table:12{isKnown(Signal.get(Router.location()).pathname) ? View.null() : <NotFound />}
Use for state carried in the query string or hash: derive it with a computed over Router.location(), and navigate with ~search.
1let tab = Computed.make(() => {2 let search = Signal.get(Router.location()).search3 search == "?tab=posts" ? "posts" : "profile"4})56let goToResults = (q: string) => Router.push("/search", ~search="?q=" ++ encodeURIComponent(q), ())7let redirectToLogin = () => Router.replace("/login", ())
Use on the server, once per request, before rendering:
1let renderRequest = (~pathname, ~search) => {2 Router.initSSR(~pathname, ~search, ())3 SSR.renderToString(() => <App />)4}
Anti-patterns
Keeping screen state in a route's component when the query string or hash changes.
1// Inside the screen rendered by routes: a local signal for the open panel2let open_ = Signal.make(false)3// ...and a link to "#comments" or "?tab=posts" on the same page
Symptom: clicking a same-page hash or query link resets the screen (local signals back to their initial values, inputs cleared, scroll and focus lost). Correct: keep such state at module level or in a component above Router.routes, or derive it from Router.location() (as with tab above). Why: rule 13; the matched screen is rebuilt on every location change.
Expecting "*" or "/:rest" to catch every unknown URL.
1Router.routes([2 {pattern: "/", render: _ => <Home />},3 {pattern: "*", render: _ => <NotFound />},4])
Symptom: unknown multi-segment URLs (/a/b) render nothing; * only matches the literal path /*. Correct: the isKnown pattern above. Why: rules 8 and 9.
Assuming <Router.Link onClick> runs before navigation.
1<Router.Link to="/checkout" onClick={_ => Signal.set(draftSaved, saveDraft())}> {"Checkout"} </Router.Link>
Symptom: the handler sees the new location, and anything it does happens after the checkout screen has already been built. Correct: do the work first and navigate yourself from a <button onClick> with Router.push, or do the work in the destination screen. Why: rule 15.
Using Router.link for external URLs or new-tab links.
Symptom: an external to is pushed into history as an app path; a target="_blank" link opens in the same tab. Correct: use a plain <a href target="_blank"> for anything that should leave the app. Why: rule 14.
Forgetting Router.initSSR per request.
Symptom: the server renders the screen for the previous request's URL (global state, rule 1), and the client then hydrates a different screen. Correct: call Router.initSSR(~pathname, ~search, ()) immediately before each render.
Edge cases
Router.location()is app-relative: withbasePath="/my-app", the browser URL/my-app/users/1givespathname == "/users/1", and/my-appgives"/". A URL outside the base path is passed through unchanged.push/replaceadd the base path;locationremoves it;link/Linkput the base path intohref. Never include the base path yourself.- Pushing the current URL again still adds a history entry and still rebuilds the matched screen.
- Hash scrolling uses
document.getElementById(decodeURIComponent(hash))after a microtask; if the target renders later than that (for example after data loads), it is not scrolled to. - The
popstatelistener is never removed;initis meant to be called once per page. Route.matchis pure and safe on the server and in tests.
SSR and hydration
- On the server there is no
window: useRouter.initSSRwith the request's app-relative pathname, search and hash.Router.initwould readwindow.locationand fail. - In the browser call
Router.init()(with the samebasePathas the server) beforeHydration.hydrateById, so the location matches the URL the server rendered. - A
routesorrouteregion is a reactive region: on hydration it is rendered again on the client rather than adopted (its DOM is replaced once), which is invisible when both sides render the same screen. - Mismatched base paths between server and client produce a different screen after hydration, or none.
Verify
- Compile errors:
Router.push("/x")without the final()is a type error (the function takes labelled optionals andunit). Aroutesentry with a misspelt field is a record type error. - Pure matching test:
Route.match("/users/:id", "/users/42")isMatch(params)withparams->Dict.get("id") == Some("42"). - jsdom test: call
Router.init(), mount the app, callRouter.push("/users/1", ()), assert the rendered text; thenRouter.push("/a/b", ())and assert what renders for unknown paths. - Server test:
Router.initSSR(~pathname="/users/42", ())thenSSR.renderToString(() => <App />)contains the user screen. - Warning check: a
[Xote Router] ... called before Router.init()console warning meansinit/initSSRdid not run first.
Related
/docs/advanced/ssr— the server and client entries that callinitSSRandinit./docs/guides/deploying— base paths and static hosting fallbacks./docs/learn/computeds— deriving state fromRouter.location()./docs/learn/rendering— reactive regions, whichroute/routesare.