@luwiostack/router 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,780 @@
1
+ # @luwiostack/router
2
+
3
+ Locale-aware routing for [TanStack Router](https://tanstack.com/router). Define **one route per
4
+ file**, give each a **translated URL segment per locale**, register it, and expand the whole
5
+ registry into a real TanStack route tree — one localized sub-tree per locale.
6
+
7
+ Part of [LuwioStack](https://github.com/) — standalone, but pairs with `@luwiostack/locale`.
8
+
9
+ ```
10
+ /en-BE/about /nl-BE/over-ons /fr-BE/pour-nous
11
+ ```
12
+
13
+ > **Runnable example:** [`apps/showcase`](../../apps/showcase) — a small localized app that uses
14
+ > this router (localized routes, a layout route, a locale switcher) alongside the other `@luwiostack`
15
+ > packages. `pnpm --filter @luwiostack/showcase dev`.
16
+
17
+ ## Why
18
+
19
+ TanStack's file-based routing keys each path to a filename, so `about.tsx` can only ever produce
20
+ the segment `about`. Real multilingual sites need `/nl-BE/over-ons`, `/fr-BE/pour-nous`, … This
21
+ package keeps every TanStack feature (`loader`, `beforeLoad`, `validateSearch`, layout routes, …)
22
+ and adds locale-translated segments on top, driven by config at runtime.
23
+
24
+ ## Install
25
+
26
+ ```bash
27
+ npm install @luwiostack/router @luwiostack/locale
28
+ ```
29
+
30
+ `@luwiostack/locale` is a **direct dependency of the router**, so `npm install @luwiostack/router`
31
+ alone already pulls it into `node_modules` (which in turn pulls in `@luwiostack/country` and
32
+ `@luwiostack/language`). Install it explicitly anyway — as shown above — because your app imports
33
+ `@luwiostack/locale` directly (`Locale`, `ILocale`, `useLocale`), and a package you import should be
34
+ a declared dependency rather than a transitive one that could change or disappear when the router
35
+ bumps its range.
36
+
37
+ `react` (18+) is the only peer dependency. **`@tanstack/react-router` is bundled in** — you don't
38
+ install or import it directly. This package vendors it and surfaces only the structural bindings you
39
+ need — `RouterProvider`, `Outlet`, `HeadContent` — re-exported from `@luwiostack/router` itself:
40
+
41
+ ```tsx
42
+ import { RouterProvider, Outlet } from '@luwiostack/router'
43
+ ```
44
+
45
+ Everything else goes through the router object (`useRouter().router`, or `context.router` in a
46
+ `beforeLoad` / `loader`): URL generation (`href` / `path` / `absolute`), navigation (`navigate`), and
47
+ locale-aware `redirect` / `notFound`. There is no `<Link>`; render `<a href={router.href(...)}>` and
48
+ call `router.navigate(...)` from your own `onClick`.
49
+
50
+ ## Usage
51
+
52
+ Define a route and **export** it — `createRoute` takes every TanStack option plus an `id`; add a
53
+ slug per locale with `.alias`. No manual registration: the file just exports the route, and the
54
+ tooling (below) collects it — the same shape as TanStack's `export const Route = …`.
55
+
56
+ ```tsx
57
+ // routes/about.route.tsx
58
+ import { createRoute } from '@luwiostack/router'
59
+ import { Locale } from '@luwiostack/locale'
60
+ import { About } from './About'
61
+
62
+ export default createRoute({
63
+ id: 'about',
64
+ // title() + description() are REQUIRED on every URL route (SEO — see below).
65
+ title: ({ context }) => context.t('about.title'),
66
+ description: ({ context }) => context.t('about.desc'),
67
+ beforeLoad: ({ context }) => ({ crumb: 'About' }), // context.locale is the active ILocale
68
+ loader: ({ context }) => fetchTeam(context.locale.country_code),
69
+ component: About,
70
+ })
71
+ .alias(Locale.new({ languageOrLocale: 'en-BE' }), 'about')
72
+ .alias(Locale.new({ languageOrLocale: 'nl-BE' }), 'over-ons')
73
+ .alias(Locale.new({ languageOrLocale: 'fr-BE' }), 'pour-nous')
74
+ ```
75
+
76
+ **The index route.** Alias a route to the **empty string** to mount it at the locale root
77
+ (`/en-BE`) rather than a named segment. Every URL-bearing route needs **at least one alias** —
78
+ `createRouter` throws on a route defined without one (only layout routes are exempt) — so the empty
79
+ alias is how you deliberately make a route the index:
80
+
81
+ ```tsx
82
+ export default createRoute({
83
+ id: 'home',
84
+ title: ({ context }) => context.t('home.title'),
85
+ description: ({ context }) => context.t('home.desc'),
86
+ component: Home,
87
+ })
88
+ .alias(Locale.new({ languageOrLocale: 'en-BE' }), '') // → /en-BE
89
+ .alias(Locale.new({ languageOrLocale: 'nl-BE' }), '') // → /nl-BE
90
+ ```
91
+
92
+ ### Dynamic path params
93
+
94
+ An alias is a full TanStack path pattern, so a **`$`-prefixed** segment is a dynamic param and a bare
95
+ **`$`** is a splat (catch-all). It can be **multi-segment**, so the static parts and the param live in
96
+ one alias — and both may differ per locale, while the param name stays the same:
97
+
98
+ ```tsx
99
+ export default createRoute<{ postId: string }>({ // generic types params in beforeLoad/loader/head
100
+ id: 'blog.post',
101
+ title: ({ context }) => context.t('post.title'), // required on every URL route (SEO)
102
+ description: ({ context }) => context.t('post.desc'),
103
+ loader: ({ params, context }) => fetchPost(context.locale, params.postId),
104
+ component: Post,
105
+ })
106
+ .alias(Locale.new({ languageOrLocale: 'en-BE' }), 'blog/$postId') // /en-BE/blog/$postId
107
+ .alias(Locale.new({ languageOrLocale: 'nl-BE' }), 'post/$postId') // /nl-BE/post/$postId
108
+
109
+ // a splat — matches the rest of the path into params['*'] (title/description omitted for brevity):
110
+ createRoute({ id: 'docs.catchAll', title, description }).alias(enBE, 'docs/$') // /en-BE/docs/*
111
+ ```
112
+
113
+ (You can still split the hierarchy across routes with `parent` when a real layout/guard sits at the
114
+ static prefix — see [layout routes](#advanced--layout-routes). A multi-segment alias is the shortcut
115
+ when the prefix is *just* a URL prefix.)
116
+
117
+ Read them in a component with `useRouteParams()` (path params) and `useRouteQuery()` (the query
118
+ string). Both are thin wrappers over TanStack Router's `useParams` / `useSearch`, pinned to the
119
+ **current route** (`strict: false`), so no `from` id is needed — pass a type argument, or let the
120
+ route's `validateSearch` shape the query:
121
+
122
+ ```tsx
123
+ import { createRoute, useRouteParams, useRouteQuery } from '@luwiostack/router'
124
+
125
+ function Post() {
126
+ const { postId } = useRouteParams<{ postId: string }>() // from the /blog/$postId segment
127
+ const { page = 1 } = useRouteQuery<{ page?: number }>() // from ?page=2 (typed by validateSearch)
128
+
129
+ return <Article id={postId} page={page} />
130
+ }
131
+
132
+ // Define the query shape once on the route; useRouteQuery reads it back.
133
+ createRoute<{ postId: string }, { page: number }>({
134
+ id: 'blog.post',
135
+ validateSearch: (s): { page: number } => ({ page: Number(s.page ?? 1) }),
136
+ // … + required title/description
137
+ })
138
+ ```
139
+
140
+ > These read the **active** route. To read another route's params/query type-safely, call TanStack's
141
+ > `useParams` / `useSearch` with a `from` route id directly.
142
+
143
+ **Watch just one value.** Pass a `select` function to subscribe to a single param or query value — the
144
+ component re-renders **only** when that value changes, not on every params/search update. It's the
145
+ same `select` as TanStack's `useParams` / `useSearch`, so structural sharing skips no-op re-renders:
146
+
147
+ ```tsx
148
+ // re-renders only when postId changes, even if the query string or other params change:
149
+ const postId = useRouteParams((p) => p.postId)
150
+
151
+ // select AND map one query value (parse ?page=2 → 2):
152
+ const page = useRouteQuery((s) => Number(s.page ?? 1))
153
+
154
+ // type it explicitly when params/search aren't inferred:
155
+ const id = useRouteParams((p: { postId: string }) => p.postId)
156
+ ```
157
+
158
+ Build a localized href or navigate by **id + params** — the router fills each `$segment` from
159
+ `params` (the splat reads `params['*']`) and throws if a required one is missing, so you never ship a
160
+ half-built URL:
161
+
162
+ ```tsx
163
+ const { router } = useRouter()
164
+ router.href({ id: 'blog.post', params: { postId: '42' } }) // '/en-BE/blog/42'
165
+ router.href({ id: 'blog.post', params: { postId: '42' }, locale: 'nl-BE' }) // '/nl-BE/blog/42'
166
+ router.navigate({ id: 'blog.post', params: { postId: '42' }, query: { page: 2 } })
167
+ ```
168
+
169
+ `params` / `query` are loosely typed by default; augment `RouteRegister` once to make `href` /
170
+ `navigate` **require** the right params and type the query per id — see [Type safety](#type-safety).
171
+
172
+ Expand the registry into a router once, at boot:
173
+
174
+ ```tsx
175
+ // router.ts
176
+ import 'virtual:@luwiostack/router/routes' // every *.route file is now registered (Vite plugin, below)
177
+ import { createRouter, routeRegistry } from '@luwiostack/router'
178
+ import { Locale } from '@luwiostack/locale'
179
+
180
+ export const router = createRouter(routeRegistry, {
181
+ locales: ['en-BE', 'nl-BE', 'fr-BE'].map((l) => Locale.new({ languageOrLocale: l })),
182
+ defaultLocale: Locale.new({ languageOrLocale: 'en-BE' }),
183
+ })
184
+ ```
185
+
186
+ ```tsx
187
+ import { RouterProvider } from '@luwiostack/router' // re-exported; no @tanstack/react-router install
188
+
189
+ <RouterProvider router={router} />
190
+ ```
191
+
192
+ ### Auto-registration
193
+
194
+ Route files only `export` their routes — something has to import those files and collect the
195
+ exports into the registry. Two ways:
196
+
197
+ **Recommended — the Vite plugin.** Add it once; it scans your routes directory and registers every
198
+ exported route through a virtual module, so app code stays free of globs. This is how TanStack
199
+ Router's own plugin works.
200
+
201
+ ```ts
202
+ // vite.config.ts
203
+ import { luwioRouter } from '@luwiostack/router/vite'
204
+
205
+ export default defineConfig({
206
+ plugins: [luwioRouter()], // defaults to scanning src/routes/**/*.route.{ts,tsx}
207
+ })
208
+ ```
209
+
210
+ ```ts
211
+ // src/vite-env.d.ts — types for the virtual module
212
+ /// <reference types="@luwiostack/router/vite-client" />
213
+ ```
214
+
215
+ Then `import 'virtual:@luwiostack/router/routes'` once (shown above). Adding or removing a route file
216
+ reloads automatically. Options: `dir`, `suffix`, `virtualId`.
217
+
218
+ **Or a plain glob** with `registerModules`, if you'd rather not add a plugin:
219
+
220
+ ```ts
221
+ import { registerModules } from '@luwiostack/router'
222
+
223
+ registerModules(import.meta.glob('./routes/**/*.route.tsx', { eager: true }))
224
+ ```
225
+
226
+ Either way: without one of these, the registry comes up empty — the files are never collected.
227
+
228
+ ### The locale in context
229
+
230
+ Before each route's own `beforeLoad` runs, `createRouter` injects `{ routeId, locale }` into the
231
+ route context, where `locale` is the full [`ILocale`](../locale) — so `loader` and `beforeLoad`
232
+ can read `context.locale.language()`, `.country()`, `.country_code`, etc. The locale layout also
233
+ wraps the tree in `@luwiostack/locale`'s provider, so `useLocale()` works in every component.
234
+
235
+ ### The active locale & a language switcher
236
+
237
+ `createRouter` mounts **one sub-tree per locale** and seeds each route's context with its
238
+ `{ routeId, locale }` (above). `useRouter()` reads that back reactively from the active match, so
239
+ `router.locale` is always the locale of the page you're on — `/nl-BE/…` resolves to `nl-BE`. It's the
240
+ same value as `useRouteLocale()` and a route's `context.locale`, and it falls back to `defaultLocale`
241
+ before the first match resolves, so it's never undefined. Every `router.href` / `navigate` **without
242
+ an explicit `locale` uses it** — you never thread the current locale through yourself.
243
+
244
+ ```ts
245
+ const { router } = useRouter()
246
+ router.locale // the active ILocale
247
+ router.locale.code // 'nl-BE'
248
+ router.routeId // the active route id
249
+ ```
250
+
251
+ A language switcher is therefore just navigation to the **same route id** in another locale — the id
252
+ is stable, so the URL translates itself (`/en-BE/blog/42` → `/nl-BE/post/42`). Walk `router.locales`,
253
+ disable the ones the current page has no alias for (`availableLocales`), and carry `params` across so
254
+ dynamic routes keep their values:
255
+
256
+ ```tsx
257
+ import { useRouteParams, useRouter } from '@luwiostack/router'
258
+
259
+ function LanguageSwitcher() {
260
+ const { router } = useRouter()
261
+ const activeId = router.routeId ?? 'home'
262
+ const params = useRouteParams() // carry params across the switch
263
+ const available = new Set(router.availableLocales(activeId).map((l) => l.code))
264
+
265
+ return (
266
+ <nav aria-label="Language">
267
+ {router.locales.map((l) => (
268
+ <button
269
+ key={l.code}
270
+ type="button"
271
+ disabled={!available.has(l.code)} // no alias on this page → not switchable
272
+ aria-current={l.code === router.locale.code} // router.locale = the active locale
273
+ onClick={() => router.navigate({ id: activeId, locale: l, params })}
274
+ >
275
+ {l.language().machine_name} {/* 'Dutch', 'English', … */}
276
+ </button>
277
+ ))}
278
+ </nav>
279
+ )
280
+ }
281
+ ```
282
+
283
+ ## Route options
284
+
285
+ `createRoute(config)` takes this package's own three keys plus TanStack Router's route options. The
286
+ common ones are typed and documented below (with `params`/`search`/`locale` wired in); **any other
287
+ TanStack route option is accepted and forwarded untouched**.
288
+
289
+ | Option | Type | What it does |
290
+ | ------ | ---- | ------------ |
291
+ | `id` \* | `string` | Stable, unique id. Wires `parent` and identifies the route for navigation. |
292
+ | `parent` | `string` | Parent route id. Omit for a top-level route. |
293
+ | `layout` | `boolean` | Pathless route — contributes no URL segment but wraps its children (guards, shells). Takes no aliases. |
294
+ | `beforeLoad` | `(ctx) => unknown` | Runs before load; its return **merges into context** for this route + descendants. `ctx.context.locale` is the active locale. |
295
+ | `loader` | `(ctx) => unknown` | Loads data before render (`useRouteLoaderData()`). |
296
+ | `loaderDeps` | `({ search }) => object` | The `search` slice the loader depends on, so it re-runs when those change. |
297
+ | `validateSearch` | `(search) => T` | Parse/validate the query string into typed `search`. |
298
+ | `title` / `description` | `(ctx) => string` | **Required** for URL routes (SEO). The router emits them (plus canonical, hreflang, og) into the head. `ctx.context.locale` is the active locale. See below. |
299
+ | `head` | `(ctx) => RouteHead` | **Optional** extra head tags beyond the SEO essentials the router already emits. See below. |
300
+ | `component` | component | The page (or a layout shell around `<Outlet />`). |
301
+ | `pendingComponent` | component | Shown while the loader is pending. |
302
+ | `errorComponent` | component | Shown when the route (or a child) throws. |
303
+ | `notFoundComponent` | component | Shown when `notFound()` is thrown beneath it. |
304
+ | `staleTime` / `gcTime` | `number` (ms) | Loader-data freshness / cache lifetime. |
305
+ | `shouldReload` | `boolean \| (ctx) => boolean` | Whether the loader re-runs on navigation. |
306
+ | `caseSensitive` | `boolean` | Case-sensitive path matching. |
307
+ | `wrapInSuspense` | `boolean` | Wrap the component in `<Suspense>`. |
308
+ | _…anything else_ | | Forwarded to TanStack's `createRoute` untouched. |
309
+
310
+ \* required. `path` and `getParentRoute` are **not** accepted — the URL segment comes from
311
+ `.alias(locale, slug)` per locale, and the parent from `parent`. Type `params` / `search` with the
312
+ generics: `createRoute<{ postId: string }, { page: number }>({ … })`.
313
+
314
+ ### SEO & document head
315
+
316
+ Every URL route **must** declare `title()` and `description()` — SEO essentials, enforced
317
+ (`createRouter` throws if one is missing; layout routes are exempt). Both receive the head ctx, so
318
+ `context.locale` (and anything an ancestor put on context) is available. The router is
319
+ **translation-agnostic** — it knows nothing about `@luwiostack/translations` or any i18n library. You
320
+ translate inside `title()`/`description()` yourself, typically via a `context.t` a layout's
321
+ `beforeLoad` puts on context (`return { t }`).
322
+
323
+ From those two functions plus its own locale knowledge, the router **auto-emits the full i18n SEO
324
+ head** — `<title>`, `<meta name="description">`, `<link rel="canonical">`, one
325
+ `<link rel="alternate" hreflang>` per locale the route is aliased in (+ `x-default`), and
326
+ `og:title`/`og:description`/`og:locale`/`og:url`. Canonical/hreflang need an origin — the `origin`
327
+ config option, defaulting to `window.location.origin` (set it for SSR). `head()` stays **optional**,
328
+ for anything bespoke on top (JSON-LD, extra og/twitter, preloads).
329
+
330
+ ```tsx
331
+ import { createRoute } from '@luwiostack/router'
332
+
333
+ export default createRoute({
334
+ id: 'about',
335
+ title: ({ context }) => context.t('about.title'),
336
+ description: ({ context }) => context.t('about.desc'),
337
+ head: ({ context }) => ({ meta: [{ property: 'og:type', content: 'website' }] }), // optional
338
+ })
339
+ .alias(Locale.new({ languageOrLocale: 'en-BE' }), 'about')
340
+ ```
341
+
342
+ Mount `<HeadContent />` once, in your root or app-shell layout's head:
343
+
344
+ ```tsx
345
+ import { HeadContent, Outlet } from '@luwiostack/router'
346
+
347
+ const AppShell = () => (
348
+ <>
349
+ <HeadContent /> {/* writes the merged title/meta/link tags */}
350
+ <Outlet />
351
+ </>
352
+ )
353
+ ```
354
+
355
+ TanStack merges head across the matched routes (the **deepest** route wins for `title` and each
356
+ `meta` name/property), and the router emits `canonical`/`hreflang` from the leaf only, so links never
357
+ duplicate. Use `<Scripts />` (also re-exported) for body scripts under SSR.
358
+
359
+ > **Don't put a static `<title>` in `index.html`.** `<HeadContent />` renders its own, so a static
360
+ > one leaves the page with two title tags. The router sets a title on every route — the HTML shell
361
+ > needs none.
362
+
363
+ ## Loading states & skeletons
364
+
365
+ Two patterns, both driven by the route's `loader` — the layout and shell stay mounted throughout, so
366
+ either one renders *inside* your chrome.
367
+
368
+ **1. A route skeleton — `pendingComponent`.** Navigation awaits the `loader`; if it runs longer than
369
+ `pendingMs`, the skeleton takes the route's `<Outlet />` slot. `pendingMinMs` keeps it visible long
370
+ enough not to flicker. The skeleton can read `useRouteLocale()`, so even the loading state is
371
+ localized.
372
+
373
+ ```tsx
374
+ createRoute({
375
+ id: 'explore',
376
+ title, description, // required on every URL route (SEO) — see below
377
+ loader: ({ context }) => fetchThings(context.locale.country_code),
378
+ component: Explore,
379
+ pendingComponent: ExploreSkeleton, // shown once the loader passes pendingMs
380
+ pendingMs: 200, // start sooner than the ~1s default
381
+ pendingMinMs: 300, // ...and stay ≥300ms, so it can't flash
382
+ })
383
+ ```
384
+
385
+ Router-wide defaults go through the `router` passthrough:
386
+ `createRouter(reg, { …, router: { defaultPendingComponent, defaultPendingMs: 200 } })`.
387
+
388
+ **2. Render through, defer the slow part.** Return a **promise** from the loader instead of awaiting
389
+ it — the component renders immediately and only the deferred piece shows a fallback. Consume it with
390
+ `<Await>` (re-exported here) or React 19's `use()`:
391
+
392
+ ```tsx
393
+ createRoute({
394
+ id: 'post',
395
+ title, description, // required on every URL route (SEO)
396
+ loader: ({ params, context }) => ({
397
+ post: fetchPost(context.locale, params.id), // fast — awaited
398
+ comments: fetchComments(params.id), // slow — return the PROMISE, don't await
399
+ }),
400
+ component: Post,
401
+ })
402
+ ```
403
+
404
+ ```tsx
405
+ import { Await, useRouteLoaderData } from '@luwiostack/router'
406
+
407
+ function Post() {
408
+ const { post, comments } = useRouteLoaderData()
409
+ return (
410
+ <>
411
+ <Article post={post} />
412
+ <Await promise={comments} fallback={<CommentsSkeleton />}>
413
+ {(list) => <Comments items={list} />}
414
+ </Await>
415
+ </>
416
+ )
417
+ }
418
+ ```
419
+
420
+ `Await`, `useAwaited` and `defer` are re-exported from `@luwiostack/router` — no `@tanstack/react-router`
421
+ import. To skip skeletons entirely, preload on intent:
422
+ `createRouter(reg, { …, router: { defaultPreload: 'intent' } })`.
423
+
424
+ ## Advanced — layout routes
425
+
426
+ Set `layout: true` to create a **pathless** route: it contributes no URL segment, but still wraps
427
+ its children. Use it for auth guards (`beforeLoad`) and shared UI shells (`component`). Layout
428
+ routes take no aliases.
429
+
430
+ ```tsx
431
+ // routes/auth.route.tsx — pathless guard, invisible in the URL
432
+ export default createRoute({
433
+ id: 'auth',
434
+ layout: true,
435
+ beforeLoad: ({ context, location }) => {
436
+ const session = getSession()
437
+ if (!session) {
438
+ // context.router is locale-aware — redirect by route id (same shape as navigate), no path building.
439
+ throw context.router.redirect({ id: 'login', query: { redirect: location.href } })
440
+ }
441
+ return { session } // flows into every child's context
442
+ },
443
+ })
444
+ ```
445
+
446
+ `context.router` is a locale-bound router (the same surface as `useRouter().router`) injected into
447
+ every route's context, so a guard resolves the active locale's translated `/login` for you and can
448
+ also `throw context.router.notFound()`.
449
+
450
+ ```tsx
451
+ // routes/app.route.tsx — pathless layout, shared chrome
452
+ export default createRoute({
453
+ id: 'app',
454
+ parent: 'auth', // sits inside the guard
455
+ layout: true,
456
+ component: AppShell, // renders sidebar/nav around <Outlet />
457
+ })
458
+ ```
459
+
460
+ ```tsx
461
+ // routes/account.route.tsx — real page under auth + layout
462
+ export default createRoute({
463
+ id: 'account',
464
+ parent: 'app',
465
+ title: ({ context }) => context.t('account.title'), // required on every URL route (SEO)
466
+ description: ({ context }) => context.t('account.desc'),
467
+ loader: ({ context }) => fetchAccount(context.session, context.locale.country_code),
468
+ component: Account,
469
+ })
470
+ .alias(Locale.new({ languageOrLocale: 'en-BE' }), 'account')
471
+ .alias(Locale.new({ languageOrLocale: 'fr-BE' }), 'compte')
472
+ ```
473
+
474
+ Resulting tree — `auth` and `app` never appear in the URL, but run on every request beneath them:
475
+
476
+ ```
477
+ /en-BE
478
+ └─ auth [pathless] session guard → context.session
479
+ └─ app [pathless] AppShell (chrome)
480
+ └─ account /account → context.locale + context.session
481
+ ```
482
+
483
+ | Locale | URL |
484
+ | ------- | ---------------- |
485
+ | `en-BE` | `/en-BE/account` |
486
+ | `fr-BE` | `/fr-BE/compte` |
487
+
488
+ ## Config-driven availability
489
+
490
+ `createRouter`'s config decides what actually mounts, so one build can serve different route/locale
491
+ sets per deployment, market, or feature flag:
492
+
493
+ ```ts
494
+ createRouter(routeRegistry, {
495
+ locales: [/* … */], // required
496
+ defaultLocale, // required
497
+ unprefixedDefault: true, // also mount the default locale without a /{locale} prefix
498
+ exclude: ['blog'], // drop a route and all its descendants
499
+ excludeStatus: 'forbidden', // excluded paths 403 (→ statusPages[403]) instead of 404; default 'notFound'
500
+ origin: 'https://ex.com', // for the canonical + hreflang URLs the router emits (SSR); else window.origin
501
+ statusPages: { // required — the router's generic 404/403/5xx handling, by HTTP status
502
+ 404: 'notFound', // best practice, but optional — falls back to `default` if omitted
503
+ 403: 'signin', // ditto
504
+ 503: 'maintenance', // any other status: a dedicated page for a beforeLoad/loader failure
505
+ default: 'serverError', // required — the catch-all for everything else
506
+ },
507
+ redirects: { '/nl/*': '/nl-BE/*' }, // legacy-URL 301s (old bookmarks) — see below
508
+ router: { /* … */ }, // extra options forwarded to TanStack's createRouter
509
+ })
510
+ ```
511
+
512
+ ### Not found, forbidden & error (404 / 403 / 5xx)
513
+
514
+ Handle all three in **one map**, keyed by HTTP status, as **redirects to real routes**:
515
+ `statusPages`. Only `default` is required — it's the guaranteed catch-all, so the router always has
516
+ *somewhere* to send a failure. `404` and `403` are best practice (a dedicated not-found / forbidden
517
+ page), not requirements: omit either and it falls back to `default` too.
518
+
519
+ - **404** — a URL matching no route redirects to `statusPages[404]` in the active locale
520
+ (`/nl-BE/typo` → `/nl-BE/404`). The same target also catches an explicit `throw notFound()` from a
521
+ **matched** route (e.g. a loader that couldn't find its resource) — every kind of "not found" ends
522
+ up on the same real, translated, linkable 404 page. Define it as a normal route.
523
+ - **403** — a guard throws `context.router.forbidden()`, a locale-aware redirect to
524
+ `statusPages[403]`. The target lives in config, so the guard never repeats it; pass `query` to
525
+ carry a return URL.
526
+ - **Any other status** (`503`, `429`, …) — a dedicated page for a `beforeLoad`/`loader` failure whose
527
+ thrown value carries that `status` (an `HttpError` from `@luwiostack/http`, or anything else shaped
528
+ like one: `{ status: 503, … }`).
529
+ - **5xx generically** — a route's `beforeLoad` or `loader` (its **data lifecycle**, which runs
530
+ *before* the component ever renders) throws something that isn't a deliberate `redirect()` (how
531
+ `forbidden()`'s 403 works too) or `notFound()`: a bug, a failed request, anything unexpected. The
532
+ router catches it generically — the route never needs its own try/catch, the same way an unmatched
533
+ URL generically 404s — logs it (`console.error`, so it still reaches an error tracker) and redirects
534
+ to the matching `statusPages` entry (or `default`, when the status has no dedicated one, or there's
535
+ no status at all). That resolved status also becomes the redirect's own HTTP status code (falling
536
+ back to 500 when there is none).
537
+
538
+ Every status page can read **{@link useRouteFailure}** for what actually sent it there:
539
+
540
+ ```tsx
541
+ import { useRouteFailure } from '@luwiostack/router'
542
+
543
+ function Maintenance() {
544
+ const failure = useRouteFailure() // { status, error? } — undefined if opened directly (a bookmark)
545
+ return (
546
+ <>
547
+ <h1>{failure?.status ?? 503} — The website is in maintenance</h1>
548
+ {failure?.error && <p>Details: {failure.error.message}</p>}
549
+ </>
550
+ )
551
+ }
552
+ ```
553
+
554
+ `error` is only present for a `beforeLoad`/`loader` failure — a 404/403 carries `status` only, since
555
+ there's no exception behind either.
556
+
557
+ **This is scoped to the data lifecycle only.** An error thrown by the route's own `component`
558
+ *during render* is a UI bug, not a load failure, and is never touched by `statusPages` — it's left
559
+ entirely to the implementor: that route's own `errorComponent`, `rootErrorComponent`, or TanStack's
560
+ own default. The two failure modes are handled completely differently on purpose: a load failure
561
+ means the page has nothing to show, so redirecting to a real error page makes sense; a render bug is
562
+ the app's own code breaking, which redirecting away would just hide from you.
563
+
564
+ ```tsx
565
+ // the 404 route — aliased in every locale it should catch
566
+ createRoute({
567
+ id: 'notFound',
568
+ parent: 'shell',
569
+ component: NotFound,
570
+ title: ({ context }) => context.t('notfound.title'), // required on every URL route (SEO)
571
+ description: ({ context }) => context.t('notfound.desc'),
572
+ })
573
+ .alias(Locale.new({ languageOrLocale: 'en-BE' }), '404')
574
+ .alias(Locale.new({ languageOrLocale: 'nl-BE' }), '404')
575
+
576
+ // a guard — 403 → sign-in, carrying the return URL
577
+ beforeLoad: ({ context, location }) => {
578
+ if (!getSession()) {
579
+ throw context.router.forbidden({ query: { redirect: (location as { href: string }).href } })
580
+ }
581
+ }
582
+
583
+ // the 500 route — just like the 404 route, a normal aliased page
584
+ createRoute({
585
+ id: 'serverError',
586
+ parent: 'shell',
587
+ component: ServerError,
588
+ title: ({ context }) => context.t('error.title'), // required on every URL route (SEO)
589
+ description: ({ context }) => context.t('error.desc'),
590
+ })
591
+ .alias(Locale.new({ languageOrLocale: 'en-BE' }), '500')
592
+ .alias(Locale.new({ languageOrLocale: 'nl-BE' }), '500')
593
+ ```
594
+
595
+ There's deliberately no "render inline instead" escape hatch for 404 — `statusPages[404]` (falling
596
+ back to `default`) always redirects, the same way `forbidden()` always does for 403. `rootErrorComponent`
597
+ is unrelated to `statusPages`: it's TanStack's ordinary top-level boundary for a RENDER error, a
598
+ separate failure mode `statusPages` never touches — see above.
599
+
600
+ #### Excluded routes: 404 vs 403
601
+
602
+ By default an `exclude`d route is dropped outright, so its URL is indistinguishable from a typo — it
603
+ 404s. Set `excludeStatus: 'forbidden'` to instead keep the excluded route's **path** mounted as a
604
+ guard that redirects to `statusPages[403]` with a **403**. Use it when a route is disabled by
605
+ config or a feature flag but should read as _"exists, but not available right now"_ rather than
606
+ _"never existed"_ — the path (and everything under it) 403s instead of 404ing.
607
+
608
+ ```ts
609
+ createRouter(routeRegistry, {
610
+ locales, defaultLocale,
611
+ exclude: ['beta-feature'],
612
+ excludeStatus: 'forbidden', // /en-BE/beta-feature (+ any sub-path) → 403
613
+ statusPages: { 403: 'signin', default: 'serverError' }, // the 403 page must be registered
614
+ })
615
+ ```
616
+
617
+ The two axes stay distinct on purpose:
618
+
619
+ - **An excluded route** lives _inside_ a mounted locale sub-tree, so there's a path to guard →
620
+ `excludeStatus: 'forbidden'` makes it **403** (only in the locales it's aliased in; a locale it was
621
+ never aliased in still 404s, since that URL never existed there).
622
+ - **A missing locale** has no `/{code}` sub-tree at all, so `/{code}/anything` is **always a 404**
623
+ regardless of `excludeStatus` — there is nothing to forbid. `/nl-BE/page` when `nl-BE` isn't in
624
+ `locales` 404s even though `page` is aliased.
625
+
626
+ `excludeStatus: 'forbidden'` requires its resolved 403 page (`statusPages[403]`, or `default` if 403
627
+ has no dedicated entry) to be a **registered** route, else the build throws. `router.has(id)` still
628
+ reports an excluded route as **not** mounted — a 403 guard is not
629
+ something you link to.
630
+
631
+ ### Legacy redirects
632
+
633
+ When URLs change (renamed locale codes, a moved page), old bookmarks and indexed links shouldn't
634
+ 404. `redirects` is a map of **permanent (301)** redirects from old paths to new, resolved _before_
635
+ the not-found catch-all:
636
+
637
+ - **Wildcard** — a pattern ending in `/*` captures the rest of the path and appends it to the
638
+ target's `/*`: `'/nl/*': '/nl-BE/*'` sends `/nl/over-ons` → `/nl-BE/over-ons`. **Query and hash are
639
+ preserved**, and the bare prefix redirects too (`/nl` → `/nl-BE`).
640
+ - **Exact** — a pattern with no `*` redirects that one path: `'/pricing': '/plans'`.
641
+
642
+ ```ts
643
+ createRouter(routeRegistry, {
644
+ locales, defaultLocale,
645
+ redirects: {
646
+ '/nl/*': '/nl-BE/*', // wildcard, keeps the tail + query + hash
647
+ '/pricing': '/plans', // exact
648
+ },
649
+ })
650
+ // /nl/over-ons?x=1#a → /nl-BE/over-ons?x=1#a (301)
651
+ ```
652
+
653
+ A pattern must not collide with a real mounted path — old locale codes differ from the new ones, so
654
+ they don't. It's plain path-to-path rewriting; the router knows nothing about the old scheme beyond
655
+ this map.
656
+
657
+ **Every route is mounted by default** — `exclude` is the only route filter: it drops the listed ids
658
+ together with all of their descendants. So one build can serve different route sets per deployment,
659
+ market, or feature flag just by changing `exclude`.
660
+
661
+ **A route mounts in exactly the locales it's aliased in.** A URL-bearing route must have **at least
662
+ one** alias — one defined with no `.alias()` at all is rejected at build (only layout routes may omit
663
+ it). Beyond that, coverage is up to you: alias a route in every locale and it's everywhere; alias it
664
+ in a subset and it deliberately exists only there. There's no "strict" flag — partial is simply how
665
+ aliases work, and a locale a route isn't aliased in just doesn't mount it.
666
+
667
+ ### Is a route available?
668
+
669
+ Because `exclude` and partial aliasing can both leave a route unavailable, ask the router before you
670
+ link to it — `router.has(id)` is `true` only when the id is mounted (survived `exclude`), and
671
+ `router.has(id, locale)` also requires it be available in that locale:
672
+
673
+ ```ts
674
+ const { router } = useRouter()
675
+
676
+ router.has('blog') // false — excluded from this build
677
+ router.has('about') // true
678
+ router.has('about', 'nl-BE') // true only if aliased for nl-BE
679
+ router.availableLocales('about') // the locales it resolves in ([] if excluded)
680
+ ```
681
+
682
+ ### Prefixing the default locale
683
+
684
+ By default every locale — including the default — is mounted under its `/{locale}` prefix, and `/`
685
+ redirects to the default locale's tree. Set `unprefixedDefault: true` to **also** serve the default
686
+ locale without a prefix, so both resolve:
687
+
688
+ ```
689
+ nl-BE is the default:
690
+ /home ✓ (unprefixed — the canonical URL for the default locale)
691
+ /nl-BE/home ✓ (prefixed — still resolves)
692
+ /fr-BE/home ✓ (non-default locales are always prefixed)
693
+ ```
694
+
695
+ On an unprefixed route the active locale is the default locale — `useRouter().router.locale`,
696
+ `useRouteLocale()`, and `context.locale` all report it. And URL generation **strips the prefix** for
697
+ the default locale: `router.href({ id: 'home' })` returns `/home`, not `/nl-BE/home` — so `navigate`
698
+ and every generated link stay unprefixed while you're in the default locale.
699
+
700
+ ## API
701
+
702
+ | Export | Description |
703
+ | ----------------------------------- | -------------------------------------------------------------------------------------- |
704
+ | `createRoute(config)` | Define a route; returns a chainable `RouteBuilder`. `config.id` is required. Export it. See [Route options](#route-options). |
705
+ | `RouteBuilder` | `.alias(locale, slug)`, `.slugFor(locale)`, `.hasAlias(locale)`. |
706
+ | `registerModules(modules, reg?)` | Register exported routes from a glob record or module array. Defaults to `routeRegistry`.|
707
+ | `routeRegistry` | The shared `RouteRegistry` singleton. |
708
+ | `RouteRegistry` | Registry class — `.all()`, `.get()`, `.clear()`, low-level `.add()`. For isolated sets. |
709
+ | `createRouter(registry, config)` | Expand a registry into a TanStack `Router`. |
710
+ | `useRouter()` | `{ router }` — `href`/`path`/`absolute`/`navigate`/`redirect`/`notFound`/`forbidden`, plus `locale`, `routeId`, `locales`, `has`, `availableLocales`. |
711
+ | `router.redirect` / `.notFound` / `.forbidden` | Locale-aware, throwable results for `beforeLoad` / `loader` — redirect by route id, notFound, or forbidden (→ `statusPages[403]`). Also on `context.router`. |
712
+ | `useRouteFailure()` | `{ status, error? } \| undefined` — the failure that redirected to the current `statusPages` page. See [Not found, forbidden & error](#not-found-forbidden--error-404--403--5xx). |
713
+ | `RouterProvider` / `Outlet` | Re-exported from the bundled TanStack Router. Mount the tree / render children. |
714
+ | `HeadContent` / `Scripts` | Re-exported from the bundled TanStack Router. Render a route's `head()` tags / body scripts. |
715
+ | `Await` / `useAwaited` / `defer` | Re-exported from the bundled TanStack Router. Stream deferred loader data (skeletons). |
716
+ | `luwioRouter(options?)` | The Vite plugin, from `@luwiostack/router/vite`. |
717
+ | `RouteConfig` / `RouterConfig` | Config types. `createRoute<TParams, TSearch>` types the handler `ctx`. |
718
+ | `StatusPages` | The `statusPages` config type — `Record<number, string> & { default: string }`. |
719
+ | `RouteRegister` | Augment to map `id` → `{ params?; search? }` for typed `href` / `navigate` (see below). |
720
+
721
+ ## Type safety
722
+
723
+ Because the tree is assembled at runtime, TanStack can't infer literal `to` strings from a static
724
+ route tree. This package recovers the type safety that matters most in two opt-in layers:
725
+
726
+ **1. Typed handler context (no setup).** `createRoute` is generic over a route's `params` / `search`,
727
+ so `beforeLoad` and `loader` get typed callbacks — and `context.locale` is always typed:
728
+
729
+ ```tsx
730
+ createRoute<{ postId: string }, { page: number }>({
731
+ id: 'blog.post',
732
+ title, description, // required on every URL route (SEO)
733
+ loader: ({ params, search, context }) => {
734
+ fetchPost(params.postId, search.page) // params.postId: string, search.page: number
735
+ return context.locale.country_code // context.locale: ILocale — always typed
736
+ },
737
+ })
738
+ ```
739
+
740
+ **2. Typed ids + params for `href` / `navigate` (augment once).** Augment `RouteRegister` to map each
741
+ id to its `params` / `search`. `href`, `path`, `absolute` and `navigate` then check the id, require
742
+ the right `params`, type `query`, and reject unknown ids — while unaugmented apps keep the loose
743
+ `string` id behavior:
744
+
745
+ ```ts
746
+ declare module '@luwiostack/router' {
747
+ interface RouteRegister {
748
+ about: {}
749
+ 'blog.post': { params: { postId: string }; search: { page?: number } }
750
+ }
751
+ }
752
+
753
+ router.href({ id: 'blog.post', params: { postId: '42' } }) // ✓
754
+ router.href({ id: 'blog.post' }) // ✗ params required
755
+ router.navigate({ id: 'aboot' }) // ✗ unknown route id
756
+ ```
757
+
758
+ This package deliberately renders no link component: it only **generates URLs** (`href` / `path` /
759
+ `absolute`) and **navigates imperatively** (`navigate`). Render a plain anchor with the generated
760
+ href and route in-app on a plain left click — the `onClick` is yours to write; the router doesn't own
761
+ it. Guard for modified clicks so middle / ⌘ / Ctrl / Shift / Alt still open a new tab, copy the link,
762
+ etc.:
763
+
764
+ ```tsx
765
+ import { useRouter } from '@luwiostack/router'
766
+
767
+ const { router } = useRouter()
768
+
769
+ <a
770
+ href={router.href({ id: 'about' })}
771
+ onClick={(e) => {
772
+ if (e.button === 0 && !e.metaKey && !e.ctrlKey && !e.shiftKey && !e.altKey) {
773
+ e.preventDefault()
774
+ router.navigate({ id: 'about' }) // in-app nav; modified clicks fall through to the href
775
+ }
776
+ }}
777
+ >
778
+ About
779
+ </a>
780
+ ```