@rangojs/router 0.0.0-experimental.e9c0b2f2 → 0.0.0-experimental.ea9f40f2
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/AGENTS.md +6 -10
- package/README.md +289 -938
- package/dist/bin/rango.js +271 -46
- package/dist/vite/index.js +673 -193
- package/package.json +10 -8
- package/skills/api-client/SKILL.md +1 -1
- package/skills/breadcrumbs/SKILL.md +31 -14
- package/skills/cache-guide/SKILL.md +5 -2
- package/skills/caching/SKILL.md +59 -4
- package/skills/catalog.json +271 -0
- package/skills/comparison/SKILL.md +50 -0
- package/skills/comparison/agents/openai.yaml +4 -0
- package/skills/comparison/references/framework-comparison.md +837 -0
- package/skills/composability/SKILL.md +83 -2
- package/skills/debug-manifest/SKILL.md +1 -1
- package/skills/defer-hydration/SKILL.md +235 -0
- package/skills/document-cache/SKILL.md +9 -1
- package/skills/fonts/SKILL.md +1 -1
- package/skills/handler-use/SKILL.md +8 -8
- package/skills/hooks/SKILL.md +54 -892
- package/skills/hooks/data.md +273 -0
- package/skills/hooks/handle-and-actions.md +103 -0
- package/skills/hooks/navigation.md +110 -0
- package/skills/hooks/outlets.md +41 -0
- package/skills/hooks/state.md +228 -0
- package/skills/hooks/urls.md +135 -0
- package/skills/host-router/SKILL.md +4 -4
- package/skills/i18n/SKILL.md +1 -1
- package/skills/intercept/SKILL.md +46 -14
- package/skills/layout/SKILL.md +27 -10
- package/skills/links/SKILL.md +1 -1
- package/skills/loader/SKILL.md +23 -1
- package/skills/middleware/SKILL.md +7 -3
- package/skills/migrate-nextjs/SKILL.md +167 -6
- package/skills/migrate-react-router/SKILL.md +59 -677
- package/skills/migrate-react-router/cloudflare-workers.md +129 -0
- package/skills/migrate-react-router/component-migration.md +196 -0
- package/skills/migrate-react-router/data-and-actions.md +225 -0
- package/skills/migrate-react-router/route-mapping.md +271 -0
- package/skills/mime-routes/SKILL.md +1 -1
- package/skills/observability/SKILL.md +9 -1
- package/skills/parallel/SKILL.md +23 -4
- package/skills/ppr/SKILL.md +622 -0
- package/skills/prerender/SKILL.md +28 -18
- package/skills/rango/SKILL.md +84 -25
- package/skills/response-routes/SKILL.md +15 -1
- package/skills/route/SKILL.md +71 -4
- package/skills/router-setup/SKILL.md +14 -3
- package/skills/scripts/SKILL.md +1 -1
- package/skills/server-actions/SKILL.md +3 -2
- package/skills/shell-manifest/SKILL.md +185 -0
- package/skills/streams-and-websockets/SKILL.md +1 -1
- package/skills/tailwind/SKILL.md +1 -1
- package/skills/testing/SKILL.md +2 -1
- package/skills/testing/handles.md +4 -2
- package/skills/testing/render-handler.md +15 -14
- package/skills/testing/reverse-and-types.md +8 -7
- package/skills/theme/SKILL.md +1 -1
- package/skills/typesafety/SKILL.md +45 -919
- package/skills/typesafety/env-and-bindings.md +254 -0
- package/skills/typesafety/generated-files-and-cli.md +335 -0
- package/skills/typesafety/params-and-search.md +153 -0
- package/skills/typesafety/route-types.md +209 -0
- package/skills/use-cache/SKILL.md +30 -3
- package/skills/vercel/SKILL.md +1 -1
- package/skills/view-transitions/SKILL.md +44 -1
- package/src/browser/event-controller.ts +62 -10
- package/src/browser/logging.ts +28 -0
- package/src/browser/merge-segment-loaders.ts +6 -4
- package/src/browser/navigation-bridge.ts +65 -16
- package/src/browser/navigation-client.ts +32 -2
- package/src/browser/navigation-store.ts +128 -14
- package/src/browser/network-error-handler.ts +34 -7
- package/src/browser/partial-update.ts +76 -17
- package/src/browser/prefetch/cache.ts +51 -11
- package/src/browser/prefetch/fetch.ts +59 -21
- package/src/browser/prefetch/queue.ts +19 -4
- package/src/browser/react/Link.tsx +13 -3
- package/src/browser/react/NavigationProvider.tsx +108 -4
- package/src/browser/response-adapter.ts +38 -9
- package/src/browser/rsc-router.tsx +54 -4
- package/src/browser/scroll-restoration.ts +7 -5
- package/src/browser/segment-reconciler.ts +31 -21
- package/src/browser/server-action-bridge.ts +22 -10
- package/src/browser/types.ts +54 -1
- package/src/build/generate-manifest.ts +155 -131
- package/src/build/index.ts +3 -1
- package/src/build/route-trie.ts +35 -7
- package/src/build/route-types/include-resolution.ts +347 -47
- package/src/build/runtime-discovery.ts +4 -1
- package/src/cache/cache-key-utils.ts +29 -0
- package/src/cache/cache-runtime.ts +262 -71
- package/src/cache/cache-scope.ts +2 -17
- package/src/cache/cache-tag.ts +60 -14
- package/src/cache/cf/cf-cache-store.ts +243 -20
- package/src/cache/document-cache.ts +54 -21
- package/src/cache/index.ts +1 -0
- package/src/cache/memory-segment-store.ts +110 -3
- package/src/cache/profile-registry.ts +15 -0
- package/src/cache/read-through-swr.ts +15 -1
- package/src/cache/segment-codec.ts +4 -4
- package/src/cache/shell-snapshot.ts +417 -0
- package/src/cache/types.ts +158 -0
- package/src/cache/vercel/vercel-cache-store.ts +401 -124
- package/src/client.rsc.tsx +0 -3
- package/src/client.tsx +0 -3
- package/src/cloudflare/tracing.ts +7 -8
- package/src/defer.ts +11 -22
- package/src/handle.ts +37 -15
- package/src/handles/MetaTags.tsx +16 -82
- package/src/handles/breadcrumbs.ts +12 -14
- package/src/handles/deferred-resolution.ts +127 -0
- package/src/handles/is-thenable.ts +7 -8
- package/src/handles/meta.ts +7 -44
- package/src/host/errors.ts +15 -0
- package/src/host/index.ts +1 -0
- package/src/index.rsc.ts +8 -2
- package/src/index.ts +19 -13
- package/src/internal-debug.ts +11 -8
- package/src/prerender.ts +17 -4
- package/src/redirect-origin.ts +14 -0
- package/src/render-error-thrower.tsx +20 -0
- package/src/route-content-wrapper.tsx +12 -5
- package/src/route-definition/dsl-helpers.ts +21 -32
- package/src/route-definition/helper-factories.ts +0 -2
- package/src/route-definition/helpers-types.ts +43 -43
- package/src/route-definition/index.ts +1 -2
- package/src/route-definition/resolve-handler-use.ts +0 -1
- package/src/route-definition/use-item-types.ts +3 -6
- package/src/route-map-builder.ts +41 -4
- package/src/route-types.ts +0 -5
- package/src/router/find-match.ts +86 -8
- package/src/router/instrument.ts +9 -4
- package/src/router/lazy-includes.ts +72 -12
- package/src/router/loader-resolution.ts +14 -2
- package/src/router/manifest.ts +56 -11
- package/src/router/match-api.ts +76 -32
- package/src/router/match-handlers.ts +181 -135
- package/src/router/match-middleware/background-revalidation.ts +40 -23
- package/src/router/match-middleware/cache-store.ts +39 -24
- package/src/router/match-result.ts +35 -15
- package/src/router/middleware.ts +64 -38
- package/src/router/navigation-snapshot.ts +7 -5
- package/src/router/parse-pattern.ts +115 -0
- package/src/router/pattern-matching.ts +53 -64
- package/src/router/prefetch-limits.ts +37 -0
- package/src/router/prerender-match.ts +11 -5
- package/src/router/preview-match.ts +3 -1
- package/src/router/request-classification.ts +23 -8
- package/src/router/route-snapshot.ts +14 -2
- package/src/router/router-context.ts +3 -1
- package/src/router/router-interfaces.ts +32 -1
- package/src/router/router-options.ts +30 -0
- package/src/router/segment-resolution/fresh.ts +39 -3
- package/src/router/segment-resolution/loader-cache.ts +93 -2
- package/src/router/segment-resolution/loader-mask.ts +60 -0
- package/src/router/segment-resolution/loader-snapshot.ts +259 -0
- package/src/router/segment-resolution/mask-nested.ts +83 -0
- package/src/router/segment-resolution/revalidation.ts +3 -0
- package/src/router/segment-resolution/view-transition-default.ts +35 -15
- package/src/router/substitute-pattern-params.ts +54 -35
- package/src/router/telemetry-otel.ts +6 -8
- package/src/router/telemetry.ts +9 -1
- package/src/router/tracing.ts +14 -5
- package/src/router/trie-matching.ts +19 -11
- package/src/router/url-params.ts +13 -0
- package/src/router.ts +47 -16
- package/src/rsc/full-payload.ts +70 -0
- package/src/rsc/handler.ts +60 -33
- package/src/rsc/manifest-init.ts +1 -1
- package/src/rsc/nonce.ts +10 -1
- package/src/rsc/progressive-enhancement.ts +61 -4
- package/src/rsc/redirect-guard.ts +2 -1
- package/src/rsc/rsc-rendering.ts +429 -37
- package/src/rsc/server-action.ts +25 -2
- package/src/rsc/shell-capture.ts +1190 -0
- package/src/rsc/shell-serve.ts +181 -0
- package/src/rsc/transition-gate.ts +89 -0
- package/src/rsc/types.ts +30 -0
- package/src/segment-loader-promise.ts +18 -0
- package/src/segment-system.tsx +149 -14
- package/src/server/context.ts +67 -9
- package/src/server/cookie-store.ts +73 -1
- package/src/server/loader-registry.ts +13 -1
- package/src/server/request-context.ts +169 -10
- package/src/ssr/index.tsx +462 -178
- package/src/ssr/inject-rsc-eager.ts +167 -0
- package/src/ssr/ssr-root.tsx +228 -0
- package/src/testing/collect-handle.ts +14 -8
- package/src/testing/dispatch.ts +152 -40
- package/src/testing/generated-routes.ts +27 -11
- package/src/testing/index.ts +6 -0
- package/src/testing/render-handler.ts +14 -0
- package/src/testing/render-route.tsx +13 -10
- package/src/testing/run-transition-when.ts +164 -0
- package/src/theme/ThemeProvider.tsx +36 -26
- package/src/types/handler-context.ts +1 -1
- package/src/types/index.ts +2 -0
- package/src/types/route-config.ts +19 -7
- package/src/types/segments.ts +100 -0
- package/src/urls/include-helper.ts +10 -8
- package/src/urls/include-provider.ts +71 -0
- package/src/urls/index.ts +1 -0
- package/src/urls/path-helper-types.ts +44 -12
- package/src/urls/path-helper.ts +5 -0
- package/src/urls/pattern-types.ts +36 -0
- package/src/urls/type-extraction.ts +43 -18
- package/src/urls/urls-function.ts +0 -1
- package/src/vercel/tracing.ts +7 -7
- package/src/vite/discovery/dev-prerender-cache.ts +117 -0
- package/src/vite/discovery/discover-routers.ts +1 -1
- package/src/vite/discovery/discovery-errors.ts +61 -0
- package/src/vite/index.ts +7 -0
- package/src/vite/inject-client-debug.ts +88 -0
- package/src/vite/plugins/vercel-output.ts +114 -25
- package/src/vite/plugins/version-injector.ts +22 -7
- package/src/vite/plugins/virtual-entries.ts +80 -22
- package/src/vite/rango.ts +29 -19
- package/src/vite/router-discovery.ts +171 -43
- package/src/vite/utils/prerender-utils.ts +17 -4
- package/src/vite/utils/shared-utils.ts +47 -0
- package/src/network-error-thrower.tsx +0 -18
package/README.md
CHANGED
|
@@ -1,81 +1,24 @@
|
|
|
1
1
|
# Rango
|
|
2
2
|
|
|
3
|
-
React
|
|
3
|
+
A code-first, type-safe React Server Components router. Django-inspired:
|
|
4
|
+
routes are expressed in one visible tree, URLs are built from names, and
|
|
5
|
+
everything past the core is opt-in.
|
|
4
6
|
|
|
5
|
-
|
|
7
|
+
> **Experimental:** This package is under active development. APIs may change
|
|
8
|
+
> between releases. Install with `@experimental` tag.
|
|
6
9
|
|
|
7
|
-
|
|
10
|
+
This page is a tour: it builds one small shop and meets the entire core API
|
|
11
|
+
along the way — about six primitives. Everything else is opt-in and linked at
|
|
12
|
+
the end. For the design rationale behind these APIs, read
|
|
13
|
+
[Why Rango](https://github.com/ivogt/vite-rsc/blob/main/packages/rangojs-router/docs/why-rango.md); this page shows how it feels, that page
|
|
14
|
+
argues why it's right.
|
|
8
15
|
|
|
9
|
-
##
|
|
10
|
-
|
|
11
|
-
- **Named routes** — `reverse("blogPost", { slug })` for type-safe URL generation (Django-style)
|
|
12
|
-
- **Structural composability** — Attach routes, loaders, middleware, handles, caching, prerendering, and static generation without hiding the route tree
|
|
13
|
-
- **Composable URL patterns** — Django-style `urls()` DSL with `path`, `layout`, `include`
|
|
14
|
-
- **Data loaders** — `createLoader()` with automatic streaming and Suspense integration
|
|
15
|
-
- **Server actions** — `"use server"` mutations with `useActionState`, `useOptimistic`, and per-segment + per-loader `revalidate()` rules
|
|
16
|
-
- **Live data layer** — Pre-render or cache the UI shell while loaders stay live by default at request time
|
|
17
|
-
- **Layouts & nesting** — Nested layouts with `<Outlet />` and parallel routes
|
|
18
|
-
- **Segment-level caching** — `cache()` DSL with TTL/SWR and pluggable cache stores
|
|
19
|
-
- **Middleware** — Route-level middleware with cookie and header access
|
|
20
|
-
- **Pre-rendering** — `Prerender()` and `Static()` handlers for build-time rendering
|
|
21
|
-
- **Theme support** — Light/dark mode with FOUC prevention and system detection
|
|
22
|
-
- **Host routing** — Multi-app routing by domain/subdomain via `@rangojs/router/host`
|
|
23
|
-
- **Response routes** — `path.json()`, `path.text()`, `path.xml()` for API endpoints
|
|
24
|
-
- **Trailing slash control** — Per-route canonical URLs with `"never"`, `"always"`, or `"ignore"`
|
|
25
|
-
- **CLI codegen** — `rango generate` for route type generation
|
|
26
|
-
|
|
27
|
-
## Design Docs
|
|
28
|
-
|
|
29
|
-
- [Execution model](./docs/internal/execution-model.md)
|
|
30
|
-
- [Semantic change checklist](./docs/internal/semantic-change-checklist.md)
|
|
31
|
-
- [Stability roadmap](./docs/internal/stability-roadmap.md)
|
|
32
|
-
|
|
33
|
-
## Installation
|
|
34
|
-
|
|
35
|
-
```bash
|
|
36
|
-
npm install @rangojs/router@experimental
|
|
37
|
-
```
|
|
38
|
-
|
|
39
|
-
Peer dependencies:
|
|
40
|
-
|
|
41
|
-
```bash
|
|
42
|
-
npm install react @vitejs/plugin-rsc
|
|
43
|
-
```
|
|
44
|
-
|
|
45
|
-
For Cloudflare Workers:
|
|
16
|
+
## Install
|
|
46
17
|
|
|
47
18
|
```bash
|
|
48
|
-
npm install @
|
|
19
|
+
npm install @rangojs/router@experimental react @vitejs/plugin-rsc
|
|
49
20
|
```
|
|
50
21
|
|
|
51
|
-
## Import Paths
|
|
52
|
-
|
|
53
|
-
Use these import paths consistently:
|
|
54
|
-
|
|
55
|
-
- `@rangojs/router` — server/RSC router APIs, route DSL, `createRouter`, `urls`, `redirect`, `Prerender`, `Static`, shared types
|
|
56
|
-
- `@rangojs/router/client` — hooks and components such as `Link`, `Outlet`, `href`, `useNavigation`, `useLoader`, `useAction`, `useLocationState`
|
|
57
|
-
- `@rangojs/router/cache` — public cache APIs such as `CFCacheStore`, `MemorySegmentCacheStore`, `createDocumentCacheMiddleware`
|
|
58
|
-
- `@rangojs/router/host`, `@rangojs/router/theme`, `@rangojs/router/vite` — specialized public subpaths
|
|
59
|
-
- `@rangojs/router/rsc`, `@rangojs/router/ssr` — advanced server-only integration subpaths for custom request/HTML pipelines
|
|
60
|
-
|
|
61
|
-
Use only subpaths that are explicitly exported from the package. Avoid deep imports such as `@rangojs/router/cache/cf`.
|
|
62
|
-
|
|
63
|
-
`@rangojs/router` is conditionally resolved. Server-only root APIs such as
|
|
64
|
-
`createRouter()`, `urls()`, `redirect()`, `Prerender()`, and `cookies()` rely on
|
|
65
|
-
the `react-server` export condition and are meant to run in router definitions,
|
|
66
|
-
handlers, and other RSC/server modules. Outside that environment the root entry
|
|
67
|
-
falls back to stub implementations that throw guidance errors.
|
|
68
|
-
|
|
69
|
-
If you hit a root-entrypoint stub error:
|
|
70
|
-
|
|
71
|
-
- hooks and components like `Link`, `Outlet`, `useLoader`, `useNavigation`, and `MetaTags` belong in `@rangojs/router/client`
|
|
72
|
-
- cache APIs like `CFCacheStore` and `createDocumentCacheMiddleware` belong in `@rangojs/router/cache`
|
|
73
|
-
- host-router APIs belong in `@rangojs/router/host`
|
|
74
|
-
|
|
75
|
-
## Quick Start
|
|
76
|
-
|
|
77
|
-
### Vite Config
|
|
78
|
-
|
|
79
22
|
```ts
|
|
80
23
|
// vite.config.ts
|
|
81
24
|
import react from "@vitejs/plugin-react";
|
|
@@ -87,40 +30,67 @@ export default defineConfig({
|
|
|
87
30
|
});
|
|
88
31
|
```
|
|
89
32
|
|
|
90
|
-
|
|
33
|
+
The `cloudflare` preset targets Cloudflare Workers (add
|
|
34
|
+
`@cloudflare/vite-plugin`); the `vercel` preset emits a ready-to-deploy
|
|
35
|
+
`.vercel/output` (Build Output API) from a plain `vite build` — see the
|
|
36
|
+
[`/vercel` skill](./skills/vercel/SKILL.md); omit `preset` for the default
|
|
37
|
+
Node setup.
|
|
91
38
|
|
|
92
|
-
|
|
93
|
-
`@rangojs/router`.
|
|
39
|
+
## Using the skills with your coding agent
|
|
94
40
|
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
41
|
+
This package ships 43 agent skills in `node_modules/@rangojs/router/skills/` —
|
|
42
|
+
task-focused guides written for LLM coding agents. Start at
|
|
43
|
+
`skills/rango/SKILL.md` (the mental model + catalog); a machine-readable index
|
|
44
|
+
is at `skills/catalog.json`.
|
|
98
45
|
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
46
|
+
- **Claude Code**: point it at the skills (e.g. "read
|
|
47
|
+
node_modules/@rangojs/router/skills/rango/SKILL.md before routing work"), or
|
|
48
|
+
copy/symlink the directories you use into your project's `.claude/skills/`.
|
|
49
|
+
- **Other agents (Cursor, Codex CLI, Gemini CLI, ...)**: these harnesses
|
|
50
|
+
auto-discover skills from `.agents/skills/` in your project (or
|
|
51
|
+
`~/.agents/skills/`) — copy or symlink the skill directories you use from
|
|
52
|
+
`node_modules/@rangojs/router/skills/<name>` into `.agents/skills/<name>`.
|
|
53
|
+
The files are plain markdown; cross-references like `/loader` name sibling
|
|
54
|
+
skill directories.
|
|
103
55
|
|
|
104
|
-
|
|
105
|
-
// reverse("home") -> "/"
|
|
106
|
-
```
|
|
56
|
+
## 1. Pages
|
|
107
57
|
|
|
108
|
-
|
|
58
|
+
A router is a tree. `path()` places a page, `layout()` wraps children,
|
|
59
|
+
`{ name }` gives a route an identity:
|
|
109
60
|
|
|
110
61
|
```tsx
|
|
62
|
+
// src/router.tsx
|
|
111
63
|
import { createRouter, urls } from "@rangojs/router";
|
|
112
|
-
import {
|
|
64
|
+
import { Document } from "./document";
|
|
65
|
+
import { ShopLayout } from "./layouts/shop";
|
|
66
|
+
import { HomePage } from "./routes/home";
|
|
67
|
+
import { ProductPage } from "./routes/product";
|
|
113
68
|
|
|
114
|
-
const urlpatterns = urls(({ path,
|
|
115
|
-
|
|
116
|
-
|
|
69
|
+
const urlpatterns = urls(({ path, layout }) => [
|
|
70
|
+
layout(<ShopLayout />, () => [
|
|
71
|
+
path("/", HomePage, { name: "home" }),
|
|
72
|
+
path("/products/:slug", ProductPage, { name: "product" }),
|
|
73
|
+
]),
|
|
117
74
|
]);
|
|
118
75
|
|
|
119
|
-
export const router = createRouter().routes(urlpatterns);
|
|
120
|
-
// reverse("blog.post", { slug: "hello-world" }) -> "/blog/hello-world"
|
|
76
|
+
export const router = createRouter({ document: Document }).routes(urlpatterns);
|
|
121
77
|
```
|
|
122
78
|
|
|
123
|
-
|
|
79
|
+
```tsx
|
|
80
|
+
// src/layouts/shop.tsx
|
|
81
|
+
import { Outlet } from "@rangojs/router/client";
|
|
82
|
+
|
|
83
|
+
export function ShopLayout() {
|
|
84
|
+
return (
|
|
85
|
+
<div>
|
|
86
|
+
<nav>Shop</nav>
|
|
87
|
+
<main>
|
|
88
|
+
<Outlet /> {/* child routes render here */}
|
|
89
|
+
</main>
|
|
90
|
+
</div>
|
|
91
|
+
);
|
|
92
|
+
}
|
|
93
|
+
```
|
|
124
94
|
|
|
125
95
|
```tsx
|
|
126
96
|
// src/document.tsx
|
|
@@ -145,965 +115,346 @@ export function Document({ children }: { children: ReactNode }) {
|
|
|
145
115
|
}
|
|
146
116
|
```
|
|
147
117
|
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
built-in `DefaultDocument` already includes all three sites, so this is only
|
|
151
|
-
needed for a custom document.
|
|
152
|
-
|
|
153
|
-
## Defining Routes
|
|
154
|
-
|
|
155
|
-
Rango is a named-route router first.
|
|
156
|
-
|
|
157
|
-
Paths define where a route lives. Names define how the app refers to it.
|
|
158
|
-
|
|
159
|
-
It is also structurally composable.
|
|
160
|
-
|
|
161
|
-
As an app grows, routes can pull in external handlers, loaders, middleware, handles, cache policy, intercepts, prerendering, and static generation while keeping the route tree visible at the composition site.
|
|
162
|
-
|
|
163
|
-
### Named Routes
|
|
164
|
-
|
|
165
|
-
```tsx
|
|
166
|
-
import { urls } from "@rangojs/router";
|
|
167
|
-
|
|
168
|
-
const urlpatterns = urls(({ path }) => [
|
|
169
|
-
path("/", HomePage, { name: "home" }),
|
|
170
|
-
path("/product/:slug", ProductPage, { name: "product" }),
|
|
171
|
-
path("/search/:query?", SearchPage, { name: "search" }),
|
|
172
|
-
path("/files/*", FilesPage, { name: "files" }),
|
|
173
|
-
]);
|
|
174
|
-
```
|
|
175
|
-
|
|
176
|
-
Use `ctx.reverse()` from handler context as the default way to link to routes from server code:
|
|
177
|
-
|
|
178
|
-
```tsx
|
|
179
|
-
const ProductPage: Handler<"product"> = (ctx) => {
|
|
180
|
-
const url = ctx.reverse("product", { slug: "widget" }); // "/product/widget"
|
|
181
|
-
const searchUrl = ctx.reverse("search", undefined, { q: "rsc" }); // "/search?q=rsc"
|
|
182
|
-
return <Link to={url}>Widget</Link>;
|
|
183
|
-
};
|
|
184
|
-
```
|
|
185
|
-
|
|
186
|
-
`router.reverse()` (exported from the router module) is the same function without a handler context, useful in scripts or tests. In request code, prefer `ctx.reverse()` — it auto-fills mount params from the current match.
|
|
187
|
-
|
|
188
|
-
### Composable URL Modules
|
|
189
|
-
|
|
190
|
-
Local route names compose cleanly with `include(..., { name })`:
|
|
191
|
-
|
|
192
|
-
```tsx
|
|
193
|
-
import { urls } from "@rangojs/router";
|
|
194
|
-
|
|
195
|
-
export const blogPatterns = urls(({ path }) => [
|
|
196
|
-
path("/", BlogIndexPage, { name: "index" }),
|
|
197
|
-
path("/:slug", BlogPostPage, { name: "post" }),
|
|
198
|
-
]);
|
|
199
|
-
|
|
200
|
-
export const urlpatterns = urls(({ path, include }) => [
|
|
201
|
-
path("/", HomePage, { name: "home" }),
|
|
202
|
-
include("/blog", blogPatterns, { name: "blog" }),
|
|
203
|
-
]);
|
|
204
|
-
|
|
205
|
-
router.reverse("blog.index"); // "/blog"
|
|
206
|
-
router.reverse("blog.post", { slug: "hello-world" }); // "/blog/hello-world"
|
|
207
|
-
```
|
|
208
|
-
|
|
209
|
-
This is the core composition model:
|
|
210
|
-
|
|
211
|
-
- Paths stay local to the module that defines them
|
|
212
|
-
- Names become stable references across the app
|
|
213
|
-
- `include()` scales those names without forcing raw path-string coupling
|
|
214
|
-
|
|
215
|
-
### Structural Composability
|
|
216
|
-
|
|
217
|
-
Rango avoids the usual tradeoff between modularity and visibility.
|
|
218
|
-
|
|
219
|
-
You can extract route behavior into separate files or packages and still keep one readable route definition that shows the structure of the app.
|
|
220
|
-
|
|
221
|
-
```tsx
|
|
222
|
-
import { urls } from "@rangojs/router";
|
|
223
|
-
import { ProductPage } from "./routes/product";
|
|
224
|
-
import { ProductLoader } from "./loaders/product";
|
|
225
|
-
import { productMiddleware } from "./middleware/product";
|
|
226
|
-
import { productRevalidate } from "./revalidation/product";
|
|
227
|
-
|
|
228
|
-
const shopPatterns = urls(({ path, loader, middleware, revalidate, cache }) => [
|
|
229
|
-
path("/product/:slug", ProductPage, { name: "product" }, () => [
|
|
230
|
-
middleware(productMiddleware),
|
|
231
|
-
loader(ProductLoader),
|
|
232
|
-
revalidate(productRevalidate),
|
|
233
|
-
cache({ ttl: 300 }),
|
|
234
|
-
]),
|
|
235
|
-
]);
|
|
236
|
-
```
|
|
237
|
-
|
|
238
|
-
The route tree stays explicit even when behavior is modular.
|
|
239
|
-
|
|
240
|
-
This applies to:
|
|
241
|
-
|
|
242
|
-
- external route modules mounted with `include()`
|
|
243
|
-
- imported loaders, middleware, and handles attached at the route site
|
|
244
|
-
- prerendering and static generation attached without turning the route tree opaque
|
|
245
|
-
|
|
246
|
-
### Loaders As the Live Data Layer
|
|
247
|
-
|
|
248
|
-
Rango separates app structure from app data.
|
|
249
|
-
|
|
250
|
-
Routes, layouts, and pre-rendered segments can be static or cached, while
|
|
251
|
-
loaders stay live by default and re-resolve at request time.
|
|
252
|
-
|
|
253
|
-
This means you can pre-render or cache the shell of a page without freezing its
|
|
254
|
-
data.
|
|
255
|
-
|
|
256
|
-
- `cache()` caches route structure and rendered UI segments
|
|
257
|
-
- `Prerender()` skips loaders at build time
|
|
258
|
-
- `loader()` provides fresh request-time data
|
|
259
|
-
- individual loaders can opt into caching explicitly when needed
|
|
260
|
-
|
|
261
|
-
```tsx
|
|
262
|
-
import { urls, Prerender } from "@rangojs/router";
|
|
263
|
-
import { ArticleLoader } from "./loaders/article";
|
|
264
|
-
|
|
265
|
-
const docsPatterns = urls(({ path, loader }) => [
|
|
266
|
-
path("/docs/:slug", Prerender(DocsArticle), { name: "docs.article" }, () => [
|
|
267
|
-
loader(ArticleLoader), // fresh by default
|
|
268
|
-
]),
|
|
269
|
-
]);
|
|
270
|
-
```
|
|
271
|
-
|
|
272
|
-
Pre-render the page, keep the data live.
|
|
118
|
+
(The built-in `DefaultDocument` already wires all of this — a custom document
|
|
119
|
+
is optional.)
|
|
273
120
|
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
Route handlers receive a typed context with params, search params, and `reverse()`:
|
|
121
|
+
A handler is a function of `ctx`. Typing it by route name gives typed params
|
|
122
|
+
— the Vite plugin generates the route map automatically, nothing to register:
|
|
277
123
|
|
|
278
124
|
```tsx
|
|
125
|
+
// src/routes/product.tsx
|
|
279
126
|
import type { Handler } from "@rangojs/router";
|
|
280
127
|
|
|
281
128
|
export const ProductPage: Handler<"product"> = (ctx) => {
|
|
282
|
-
|
|
283
|
-
const homeUrl = ctx.reverse("home"); // type-safe URL by route name
|
|
284
|
-
return <h1>Product: {slug}</h1>;
|
|
129
|
+
return <h1>{ctx.params.slug}</h1>; // slug: string, from the pattern
|
|
285
130
|
};
|
|
286
131
|
```
|
|
287
132
|
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
All handler typing styles are supported, but they solve different problems:
|
|
291
|
-
|
|
292
|
-
- `Handler<"product">` — default for named app routes
|
|
293
|
-
- `Handler<".post", ScopedRouteMap<"blog">>` — best for reusable included modules
|
|
294
|
-
- `Handler<"/blog/:slug">` — good for unnamed or local-only extracted handlers
|
|
295
|
-
- `Handler<{ slug: string }>` — escape hatch for advanced or decoupled cases
|
|
296
|
-
|
|
297
|
-
Example of a scoped local name inside a mounted module:
|
|
133
|
+
And because routes have names, URLs are built, never hand-written:
|
|
298
134
|
|
|
299
135
|
```tsx
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
type BlogRoutes = ScopedRouteMap<"blog">;
|
|
304
|
-
|
|
305
|
-
export const BlogPostPage: Handler<".post", BlogRoutes> = (ctx) => {
|
|
306
|
-
return <a href={ctx.reverse(".index")}>Back to blog</a>;
|
|
307
|
-
};
|
|
136
|
+
const url = ctx.reverse("product", { slug: "espresso-cup" });
|
|
137
|
+
// "/products/espresso-cup" — name and params compile-time checked
|
|
308
138
|
```
|
|
309
139
|
|
|
310
|
-
|
|
140
|
+
Rename `/products/:slug` to `/shop/:slug` in the one place it's defined and
|
|
141
|
+
every link, redirect, and prefetch follows. In client components, `href()`
|
|
142
|
+
validates static paths against the registered patterns:
|
|
143
|
+
`<Link to={href("/")}>Home</Link>`.
|
|
311
144
|
|
|
312
|
-
|
|
145
|
+
The tree is also lazy-first, which is the shape serverless cold starts want.
|
|
146
|
+
`include()` mounts a whole route module under a prefix — and with the async
|
|
147
|
+
form, `include("/shop", () => import("./shop"))`, the group is code-split:
|
|
148
|
+
its module doesn't load or run until a request matches it, a group nobody
|
|
149
|
+
visits never evaluates at all, and warm requests run zero route handlers.
|
|
150
|
+
Boot cost stays flat as the app grows — one module body at startup, not one
|
|
151
|
+
per group — while matching stays an `O(path length)` prefix trie, identical
|
|
152
|
+
in dev and production. None of this is assumed: the trie is benchmarked
|
|
153
|
+
in-repo against multi-thousand-route manifests, and the lazy guarantees are
|
|
154
|
+
pinned by run-count tests (see
|
|
155
|
+
[matching & lazy discovery](https://github.com/ivogt/vite-rsc/blob/main/packages/rangojs-router/docs/internal/matching-and-lazy-discovery.md)).
|
|
156
|
+
Grow the tree without watching the boot time.
|
|
313
157
|
|
|
314
|
-
|
|
158
|
+
That's a working site. Everything below adds to this app.
|
|
315
159
|
|
|
316
|
-
|
|
317
|
-
const urlpatterns = urls(({ path }) => [
|
|
318
|
-
path("/search", SearchPage, {
|
|
319
|
-
name: "search",
|
|
320
|
-
search: { q: "string", page: "number?", sort: "string?" },
|
|
321
|
-
}),
|
|
322
|
-
]);
|
|
323
|
-
|
|
324
|
-
// Handler receives typed search params via ctx.search
|
|
325
|
-
const SearchPage: Handler<"search"> = (ctx) => {
|
|
326
|
-
const { q, page, sort } = ctx.search;
|
|
327
|
-
// q: string, page: number | undefined, sort: string | undefined
|
|
328
|
-
};
|
|
329
|
-
```
|
|
330
|
-
|
|
331
|
-
### Trailing Slash Handling
|
|
332
|
-
|
|
333
|
-
Trailing slash behavior is a current `path()` feature.
|
|
160
|
+
## 2. Data
|
|
334
161
|
|
|
335
|
-
|
|
162
|
+
The product page needs data. A handler is an async server component — fetch
|
|
163
|
+
where you render:
|
|
336
164
|
|
|
337
165
|
```tsx
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
}
|
|
343
|
-
|
|
344
|
-
name: "docs",
|
|
345
|
-
trailingSlash: "always",
|
|
346
|
-
}),
|
|
347
|
-
path("/webhook", WebhookHandler, {
|
|
348
|
-
name: "webhook",
|
|
349
|
-
trailingSlash: "ignore",
|
|
350
|
-
}),
|
|
351
|
-
]);
|
|
352
|
-
```
|
|
353
|
-
|
|
354
|
-
Modes:
|
|
355
|
-
|
|
356
|
-
- `"never"` — canonical URL has no trailing slash, redirects `/about/` to `/about`
|
|
357
|
-
- `"always"` — canonical URL has a trailing slash, redirects `/docs` to `/docs/`
|
|
358
|
-
- `"ignore"` — matches both forms without redirect
|
|
359
|
-
|
|
360
|
-
Default behavior when `trailingSlash` is omitted:
|
|
361
|
-
|
|
362
|
-
- There is no separate global default mode
|
|
363
|
-
- If the pattern is defined without a trailing slash, the canonical URL is the no-slash form
|
|
364
|
-
- If the pattern is defined with a trailing slash, the canonical URL is the slash form
|
|
365
|
-
- The router redirects to the canonical form based on the pattern you defined
|
|
366
|
-
|
|
367
|
-
The recommended public API is the per-route `path(..., { trailingSlash })` option. Use `"ignore"` sparingly, especially on content pages, because `/x` and `/x/` are distinct URLs.
|
|
368
|
-
|
|
369
|
-
### Response Routes
|
|
370
|
-
|
|
371
|
-
Define API endpoints that bypass the RSC pipeline:
|
|
372
|
-
|
|
373
|
-
```tsx
|
|
374
|
-
const urlpatterns = urls(({ path }) => [
|
|
375
|
-
path.json("/api/health", () => ({ status: "ok" }), { name: "health" }),
|
|
376
|
-
path.text("/robots.txt", () => "User-agent: *\nAllow: /", { name: "robots" }),
|
|
377
|
-
path.xml("/feed.xml", () => "<rss>...</rss>", { name: "feed" }),
|
|
378
|
-
]);
|
|
379
|
-
```
|
|
380
|
-
|
|
381
|
-
Response types available: `path.json()`, `path.text()`, `path.html()`, `path.xml()`, `path.image()`, `path.stream()`, `path.any()`.
|
|
382
|
-
|
|
383
|
-
## Layouts & Nesting
|
|
384
|
-
|
|
385
|
-
### Layouts with Outlet
|
|
386
|
-
|
|
387
|
-
```tsx
|
|
388
|
-
import { urls } from "@rangojs/router";
|
|
389
|
-
|
|
390
|
-
const urlpatterns = urls(({ path, layout }) => [
|
|
391
|
-
layout(<MainLayout />, () => [
|
|
392
|
-
path("/", HomePage, { name: "home" }),
|
|
393
|
-
path("/about", AboutPage, { name: "about" }),
|
|
394
|
-
]),
|
|
395
|
-
]);
|
|
396
|
-
```
|
|
397
|
-
|
|
398
|
-
```tsx
|
|
399
|
-
"use client";
|
|
400
|
-
import { Outlet } from "@rangojs/router/client";
|
|
401
|
-
|
|
402
|
-
function MainLayout() {
|
|
403
|
-
return (
|
|
404
|
-
<div>
|
|
405
|
-
<nav>...</nav>
|
|
406
|
-
<Outlet />
|
|
407
|
-
</div>
|
|
408
|
-
);
|
|
409
|
-
}
|
|
410
|
-
```
|
|
411
|
-
|
|
412
|
-
### Loading Skeletons
|
|
413
|
-
|
|
414
|
-
```tsx
|
|
415
|
-
const urlpatterns = urls(({ path, loading }) => [
|
|
416
|
-
path("/product/:slug", ProductPage, { name: "product" }, () => [
|
|
417
|
-
loading(<ProductSkeleton />),
|
|
418
|
-
]),
|
|
419
|
-
]);
|
|
420
|
-
```
|
|
421
|
-
|
|
422
|
-
### Parallel Routes
|
|
423
|
-
|
|
424
|
-
```tsx
|
|
425
|
-
const urlpatterns = urls(({ path, layout, parallel, loader, loading }) => [
|
|
426
|
-
layout(BlogLayout, () => [
|
|
427
|
-
parallel({ "@sidebar": BlogSidebarHandler }, () => [
|
|
428
|
-
loader(BlogSidebarLoader),
|
|
429
|
-
loading(<SidebarSkeleton />),
|
|
430
|
-
]),
|
|
431
|
-
path("/blog", BlogIndexPage, { name: "blog" }),
|
|
432
|
-
path("/blog/:slug", BlogPostPage, { name: "blogPost" }),
|
|
433
|
-
]),
|
|
434
|
-
]);
|
|
166
|
+
// src/routes/product.tsx
|
|
167
|
+
export const ProductPage: Handler<"product"> = async (ctx) => {
|
|
168
|
+
const product = await db.products.find(ctx.params.slug);
|
|
169
|
+
ctx.use(Meta)({ title: product.name }); // metadata where the data is
|
|
170
|
+
return <ProductView product={product} />;
|
|
171
|
+
};
|
|
435
172
|
```
|
|
436
173
|
|
|
437
|
-
|
|
174
|
+
That's the default data path. React Router and Remix split data into a
|
|
175
|
+
loader beside the component because components couldn't fetch; RSC collapses
|
|
176
|
+
the split, and Rango doesn't reintroduce it. (That `ctx.use(Meta)` line is
|
|
177
|
+
also the whole metadata story: push tags where the data already is, layouts
|
|
178
|
+
set title templates, deeper segments override — no separate metadata export,
|
|
179
|
+
no second fetch.)
|
|
438
180
|
|
|
439
|
-
|
|
181
|
+
Loaders enter when data needs a life of its own. First case: a **client
|
|
182
|
+
component** needs server data — the stock badge is interactive, but the
|
|
183
|
+
stock lives in the database:
|
|
440
184
|
|
|
441
185
|
```tsx
|
|
186
|
+
// src/loaders/stock.ts
|
|
442
187
|
import { createLoader } from "@rangojs/router";
|
|
443
188
|
|
|
444
|
-
export const
|
|
445
|
-
|
|
446
|
-
return
|
|
189
|
+
export const StockLoader = createLoader(async (ctx) => {
|
|
190
|
+
"use server";
|
|
191
|
+
return db.stockFor(ctx.params.slug);
|
|
447
192
|
});
|
|
448
193
|
```
|
|
449
194
|
|
|
450
|
-
### Using in Server Components (Handlers)
|
|
451
|
-
|
|
452
195
|
```tsx
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
const { posts } = await ctx.use(BlogSidebarLoader);
|
|
458
|
-
return (
|
|
459
|
-
<ul>
|
|
460
|
-
{posts.map((p) => (
|
|
461
|
-
<li key={p.slug}>{p.title}</li>
|
|
462
|
-
))}
|
|
463
|
-
</ul>
|
|
464
|
-
);
|
|
465
|
-
}
|
|
196
|
+
path("/products/:slug", ProductPage, { name: "product" }, () => [
|
|
197
|
+
loader(StockLoader),
|
|
198
|
+
loading(<ProductSkeleton />),
|
|
199
|
+
]),
|
|
466
200
|
```
|
|
467
201
|
|
|
468
|
-
### Using in Client Components
|
|
469
|
-
|
|
470
202
|
```tsx
|
|
203
|
+
// src/components/stock-badge.tsx
|
|
471
204
|
"use client";
|
|
472
205
|
import { useLoader } from "@rangojs/router/client";
|
|
473
|
-
import {
|
|
206
|
+
import { StockLoader } from "../loaders/stock";
|
|
474
207
|
|
|
475
|
-
function
|
|
476
|
-
const { data } = useLoader(
|
|
477
|
-
return
|
|
478
|
-
<ul>
|
|
479
|
-
{data.posts.map((p) => (
|
|
480
|
-
<li key={p.slug}>{p.title}</li>
|
|
481
|
-
))}
|
|
482
|
-
</ul>
|
|
483
|
-
);
|
|
208
|
+
export function StockBadge() {
|
|
209
|
+
const { data } = useLoader(StockLoader);
|
|
210
|
+
return <span>{data.inStock ? "In stock" : "Sold out"}</span>;
|
|
484
211
|
}
|
|
485
212
|
```
|
|
486
213
|
|
|
487
|
-
|
|
214
|
+
Loaders run in parallel with the handler and stream; `loading()` opts the
|
|
215
|
+
segment into skeleton-then-stream. Without it, document requests arrive
|
|
216
|
+
**ready** — the HTML ships with data in place; the skeleton is a per-segment
|
|
217
|
+
choice, not the first impression.
|
|
488
218
|
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
]);
|
|
495
|
-
```
|
|
219
|
+
The rule of thumb: fetch in the **handler** when the data belongs to the
|
|
220
|
+
rendered page — it will be frozen with the shell if you cache it (step 4).
|
|
221
|
+
Put data in a **loader** when it must outlive the shell: shared with client
|
|
222
|
+
components, fresh on every hit even when the segment is cached, refetchable
|
|
223
|
+
from the client, or revalidated on its own after actions.
|
|
496
224
|
|
|
497
|
-
##
|
|
225
|
+
## 3. Mutations
|
|
498
226
|
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
227
|
+
Users add to cart. A server action is a plain `"use server"` function; the
|
|
228
|
+
form posts to it with standard React 19 hooks — and it works without
|
|
229
|
+
JavaScript:
|
|
502
230
|
|
|
503
231
|
```tsx
|
|
504
|
-
//
|
|
232
|
+
// src/actions/cart.ts
|
|
505
233
|
"use server";
|
|
506
234
|
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
export async function addToCart(productId: string): Promise<void> {
|
|
510
|
-
const ctx = getRequestContext();
|
|
511
|
-
const userId = ctx.get("user").id;
|
|
512
|
-
await db.cart.insert({ userId, productId });
|
|
235
|
+
export async function addToCart(productId: string) {
|
|
236
|
+
await db.cart.insert({ productId });
|
|
513
237
|
}
|
|
514
238
|
```
|
|
515
239
|
|
|
516
240
|
```tsx
|
|
517
|
-
//
|
|
241
|
+
// src/components/add-to-cart.tsx
|
|
518
242
|
"use client";
|
|
519
243
|
import { useActionState } from "react";
|
|
520
|
-
import {
|
|
244
|
+
import { addToCart } from "../actions/cart";
|
|
521
245
|
|
|
522
|
-
export function
|
|
523
|
-
const [
|
|
246
|
+
export function AddToCart({ productId }: { productId: string }) {
|
|
247
|
+
const [, action, pending] = useActionState(() => addToCart(productId), null);
|
|
524
248
|
return (
|
|
525
249
|
<form action={action}>
|
|
526
|
-
<
|
|
527
|
-
{state?.errors?.name && <p role="alert">{state.errors.name}</p>}
|
|
528
|
-
<button disabled={pending}>{pending ? "Saving…" : "Save"}</button>
|
|
250
|
+
<button disabled={pending}>{pending ? "Adding…" : "Add to cart"}</button>
|
|
529
251
|
</form>
|
|
530
252
|
);
|
|
531
253
|
}
|
|
532
254
|
```
|
|
533
255
|
|
|
534
|
-
After an action
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
256
|
+
After an action, route segments and loaders re-render by default so the UI
|
|
257
|
+
reflects the new state. `revalidate()` narrows that to the segments that
|
|
258
|
+
actually own the data — matched by action **reference**, so renames are
|
|
259
|
+
compile errors, not stale predicates:
|
|
538
260
|
|
|
539
261
|
```tsx
|
|
540
|
-
|
|
541
|
-
// Segment-level: re-render the cart page handler after cart actions.
|
|
542
|
-
// Nest loaders that belong to this route inside the same path() so the
|
|
543
|
-
// segment owns its data dependencies.
|
|
544
|
-
path("/cart", CartPage, { name: "cart" }, () => [
|
|
545
|
-
revalidate(
|
|
546
|
-
({ actionId }) => actionId?.startsWith("src/actions/cart.ts#") ?? false,
|
|
547
|
-
),
|
|
548
|
-
loader(CartLoader, () => [
|
|
549
|
-
revalidate(
|
|
550
|
-
({ actionId }) => actionId?.startsWith("src/actions/cart.ts#") ?? false,
|
|
551
|
-
),
|
|
552
|
-
]),
|
|
553
|
-
]),
|
|
554
|
-
]);
|
|
555
|
-
```
|
|
556
|
-
|
|
557
|
-
For the full guide — validation with Zod, error handling, file uploads,
|
|
558
|
-
`useOptimistic`, redirects, and progressive enhancement — see the
|
|
559
|
-
`/server-actions` skill.
|
|
262
|
+
import * as CartActions from "./actions/cart";
|
|
560
263
|
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
```tsx
|
|
568
|
-
import { Link } from "@rangojs/router/client";
|
|
569
|
-
import type { Handler } from "@rangojs/router";
|
|
570
|
-
|
|
571
|
-
const BlogPostPage: Handler<"blogPost"> = (ctx) => {
|
|
572
|
-
const backUrl = ctx.reverse("blog");
|
|
573
|
-
return <Link to={backUrl}>Back to blog</Link>;
|
|
574
|
-
};
|
|
575
|
-
```
|
|
576
|
-
|
|
577
|
-
`reverse()` is type-safe — route names and required params are checked at compile time. Included routes use dotted names: `ctx.reverse("api.health")`.
|
|
578
|
-
|
|
579
|
-
For scripts, tests, or other code without a handler context, import the router-level `reverse`:
|
|
580
|
-
|
|
581
|
-
```tsx
|
|
582
|
-
import { reverse } from "./router";
|
|
583
|
-
reverse("blogPost", { slug: "my-post" });
|
|
584
|
-
```
|
|
585
|
-
|
|
586
|
-
### Client Components
|
|
587
|
-
|
|
588
|
-
**`reverse()` is server-only.** It depends on the route manifest and handler context — neither is available in the browser bundle. Client components receive URLs as props, loader data, or server-action return values:
|
|
589
|
-
|
|
590
|
-
```tsx
|
|
591
|
-
// server
|
|
592
|
-
function BlogIndex(ctx: HandlerContext) {
|
|
593
|
-
return (
|
|
594
|
-
<Nav
|
|
595
|
-
home={ctx.reverse("home")}
|
|
596
|
-
post={ctx.reverse("blogPost", { slug: "my-post" })}
|
|
597
|
-
/>
|
|
598
|
-
);
|
|
599
|
-
}
|
|
600
|
-
```
|
|
601
|
-
|
|
602
|
-
```tsx
|
|
603
|
-
"use client";
|
|
604
|
-
import { Link } from "@rangojs/router/client";
|
|
605
|
-
|
|
606
|
-
export function Nav({ home, post }: { home: string; post: string }) {
|
|
607
|
-
return (
|
|
608
|
-
<nav>
|
|
609
|
-
<Link to={home}>Home</Link>
|
|
610
|
-
<Link to={post}>My Post</Link>
|
|
611
|
-
</nav>
|
|
612
|
-
);
|
|
613
|
-
}
|
|
614
|
-
```
|
|
615
|
-
|
|
616
|
-
For client-side navigation to static paths (no named-route lookup), use `href()` — see below. For URLs tied to named routes, you have two options: import the per-module generated `routes` map and use `useReverse(routes)` for in-module names (see [`/links` skill](./skills/links/SKILL.md)), or generate the URL on the server and pass the string in for cross-module URLs.
|
|
617
|
-
|
|
618
|
-
### `href()` for Path Validation (Client Components)
|
|
619
|
-
|
|
620
|
-
In client components, use `href()` for compile-time path validation on static path strings:
|
|
621
|
-
|
|
622
|
-
```tsx
|
|
623
|
-
"use client";
|
|
624
|
-
import { Link, href } from "@rangojs/router/client";
|
|
625
|
-
|
|
626
|
-
function Nav() {
|
|
627
|
-
return (
|
|
628
|
-
<nav>
|
|
629
|
-
<Link to={href("/")}>Home</Link>
|
|
630
|
-
<Link to={href("/blog")} prefetch="adaptive">
|
|
631
|
-
Blog
|
|
632
|
-
</Link>
|
|
633
|
-
<Link to={href("/about")}>About</Link>
|
|
634
|
-
</nav>
|
|
635
|
-
);
|
|
636
|
-
}
|
|
637
|
-
```
|
|
638
|
-
|
|
639
|
-
`href()` validates that the path matches a registered route pattern at compile time (e.g. `/blog/my-post` matches `/blog/:slug`).
|
|
640
|
-
|
|
641
|
-
### Navigation Hooks
|
|
642
|
-
|
|
643
|
-
```tsx
|
|
644
|
-
"use client";
|
|
645
|
-
import { useNavigation, useRouter } from "@rangojs/router/client";
|
|
646
|
-
|
|
647
|
-
function SearchForm() {
|
|
648
|
-
const router = useRouter();
|
|
649
|
-
const nav = useNavigation();
|
|
650
|
-
|
|
651
|
-
function handleSubmit(query: string) {
|
|
652
|
-
router.push(`/search?q=${encodeURIComponent(query)}`);
|
|
653
|
-
}
|
|
654
|
-
|
|
655
|
-
return <form onSubmit={...}>{nav.state !== "idle" && <Spinner />}</form>;
|
|
656
|
-
}
|
|
657
|
-
```
|
|
658
|
-
|
|
659
|
-
### Scroll Restoration
|
|
660
|
-
|
|
661
|
-
```tsx
|
|
662
|
-
"use client";
|
|
663
|
-
import { ScrollRestoration } from "@rangojs/router/client";
|
|
664
|
-
|
|
665
|
-
function Document({ children }) {
|
|
666
|
-
return (
|
|
667
|
-
<html>
|
|
668
|
-
<body>
|
|
669
|
-
{children}
|
|
670
|
-
<ScrollRestoration />
|
|
671
|
-
</body>
|
|
672
|
-
</html>
|
|
673
|
-
);
|
|
674
|
-
}
|
|
675
|
-
```
|
|
676
|
-
|
|
677
|
-
## Includes (Composable Modules)
|
|
678
|
-
|
|
679
|
-
Split URL patterns into composable modules with `include()`:
|
|
680
|
-
|
|
681
|
-
```tsx
|
|
682
|
-
// src/api/urls.tsx
|
|
683
|
-
import { urls } from "@rangojs/router";
|
|
684
|
-
|
|
685
|
-
export const apiPatterns = urls(({ path }) => [
|
|
686
|
-
path.json("/health", () => ({ status: "ok" }), { name: "health" }),
|
|
687
|
-
path.json("/products", getProducts, { name: "products" }),
|
|
688
|
-
]);
|
|
689
|
-
|
|
690
|
-
// src/urls.tsx
|
|
691
|
-
import { urls } from "@rangojs/router";
|
|
692
|
-
import { apiPatterns } from "./api/urls";
|
|
693
|
-
|
|
694
|
-
export const urlpatterns = urls(({ path, include }) => [
|
|
695
|
-
path("/", HomePage, { name: "home" }),
|
|
696
|
-
include("/api", apiPatterns, { name: "api" }),
|
|
697
|
-
// Mounts apiPatterns under /api: /api/health, /api/products
|
|
698
|
-
]);
|
|
264
|
+
path("/cart", CartPage, { name: "cart" }, () => [
|
|
265
|
+
loader(CartLoader, () => [
|
|
266
|
+
revalidate((ctx) => ctx.isAction(CartActions) || undefined),
|
|
267
|
+
]),
|
|
268
|
+
]),
|
|
699
269
|
```
|
|
700
270
|
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
The `name` option controls how child route names appear globally:
|
|
706
|
-
|
|
707
|
-
| Form | Child names | Generated types | Reverse resolution |
|
|
708
|
-
| ---------------------------------- | ------------------- | ---------------------- | -------------------------------------------------------------------- |
|
|
709
|
-
| `include("/x", p, { name: "ns" })` | `ns.child` | Exported as `ns.child` | `reverse("ns.child")` globally, `reverse(".child")` inside |
|
|
710
|
-
| `include("/x", p, { name: "" })` | `child` (flattened) | Exported as-is | `reverse("child")` globally, `reverse(".child")` inside (root-scope) |
|
|
711
|
-
| `include("/x", p)` | Private scope | Not exported | `reverse(".child")` inside only |
|
|
712
|
-
|
|
713
|
-
Without a `name`, included routes are local to the mounted module. They still match requests and render normally, but their names are hidden from the generated route map and cannot be reversed globally. Use `{ name: "" }` to merge children into the parent namespace without adding a prefix.
|
|
714
|
-
|
|
715
|
-
**`{ name: "" }` is flattening, not isolation.** Flattened routes behave as if defined inline at the include site — dot-local reverse (`.name`) can reach any sibling route at root scope, including routes from other `{ name: "" }` mounts. If you need module-level isolation, omit the `name` option or use a namespace.
|
|
716
|
-
|
|
717
|
-
## Middleware
|
|
718
|
-
|
|
719
|
-
```tsx
|
|
720
|
-
const urlpatterns = urls(({ path, middleware }) => [
|
|
721
|
-
middleware(
|
|
722
|
-
async (ctx, next) => {
|
|
723
|
-
const start = Date.now();
|
|
724
|
-
const response = await next();
|
|
725
|
-
console.log(
|
|
726
|
-
`${ctx.request.method} ${ctx.url.pathname} ${Date.now() - start}ms`,
|
|
727
|
-
);
|
|
728
|
-
return response;
|
|
729
|
-
},
|
|
730
|
-
() => [path("/dashboard", DashboardPage, { name: "dashboard" })],
|
|
731
|
-
),
|
|
732
|
-
]);
|
|
733
|
-
```
|
|
271
|
+
Notice what you didn't write: no API endpoint, no fetch wrapper, and no
|
|
272
|
+
client-cache invalidation call. Actions invalidate the client-side caches
|
|
273
|
+
(history entries, prefetches, HTTP cache key) automatically — a no-op action
|
|
274
|
+
can opt out per invocation with `keepClientCache()`.
|
|
734
275
|
|
|
735
|
-
##
|
|
276
|
+
## 4. Speed
|
|
736
277
|
|
|
737
|
-
|
|
278
|
+
Production traffic. Wrap a segment in `cache()` and the rendered shell —
|
|
279
|
+
including everything the handler fetched — is stored, while every loader on
|
|
280
|
+
it keeps running fresh on each hit. This is where the handler-vs-loader
|
|
281
|
+
choice from step 2 pays off: handler data freezes with the shell, the
|
|
282
|
+
`StockLoader` stays live. Cached shell, live data, one line:
|
|
738
283
|
|
|
739
284
|
```tsx
|
|
740
|
-
const urlpatterns = urls(({ path, cache }) => [
|
|
741
|
-
|
|
742
|
-
path("/
|
|
743
|
-
|
|
285
|
+
const urlpatterns = urls(({ path, layout, loader, loading, cache }) => [
|
|
286
|
+
layout(<ShopLayout />, () => [
|
|
287
|
+
path("/", HomePage, { name: "home" }),
|
|
288
|
+
cache({ ttl: 600, swr: 3600, tags: ["products"] }, () => [
|
|
289
|
+
path("/products/:slug", ProductPage, { name: "product" }, () => [
|
|
290
|
+
loader(StockLoader), // never cached: re-runs on every hit
|
|
291
|
+
loading(<ProductSkeleton />),
|
|
292
|
+
]),
|
|
293
|
+
]),
|
|
744
294
|
]),
|
|
745
295
|
]);
|
|
746
296
|
```
|
|
747
297
|
|
|
748
|
-
|
|
298
|
+
Wire a store once on the router (`MemorySegmentCacheStore` for dev,
|
|
299
|
+
`CFCacheStore` for Cloudflare — see the [`/caching` skill](./skills/caching/SKILL.md)),
|
|
300
|
+
and bust by tag from the mutation that changes the data:
|
|
749
301
|
|
|
750
302
|
```tsx
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
createDocumentCacheMiddleware,
|
|
755
|
-
} from "@rangojs/router/cache";
|
|
756
|
-
|
|
757
|
-
export const router = createRouter({
|
|
758
|
-
document: Document,
|
|
759
|
-
cache: (env) => ({
|
|
760
|
-
store: new CFCacheStore({
|
|
761
|
-
defaults: { ttl: 60, swr: 300 },
|
|
762
|
-
ctx: env.ctx,
|
|
763
|
-
}),
|
|
764
|
-
}),
|
|
765
|
-
})
|
|
766
|
-
.use(createDocumentCacheMiddleware())
|
|
767
|
-
.routes(urlpatterns);
|
|
768
|
-
```
|
|
769
|
-
|
|
770
|
-
Available cache stores:
|
|
771
|
-
|
|
772
|
-
- `CFCacheStore` — Cloudflare edge cache (production)
|
|
773
|
-
- `MemorySegmentCacheStore` — In-memory cache (development/testing)
|
|
774
|
-
|
|
775
|
-
## Pre-rendering
|
|
776
|
-
|
|
777
|
-
Pre-rendering generates route segments at build time. The worker handles all requests — there are no static files served from assets.
|
|
778
|
-
|
|
779
|
-
### Static Segments
|
|
780
|
-
|
|
781
|
-
Use `Static()` for segments rendered once at build time (no params). Works on `path()`, `layout()`, and `parallel()`:
|
|
782
|
-
|
|
783
|
-
```tsx
|
|
784
|
-
import { Static } from "@rangojs/router";
|
|
785
|
-
|
|
786
|
-
export const AboutPage = Static(async () => {
|
|
787
|
-
return <article>...</article>;
|
|
788
|
-
});
|
|
303
|
+
// src/actions/products.ts
|
|
304
|
+
"use server";
|
|
305
|
+
import { updateTag } from "@rangojs/router";
|
|
789
306
|
|
|
790
|
-
export
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
{items.map((i) => (
|
|
795
|
-
<a key={i.slug} href={i.slug}>
|
|
796
|
-
{i.title}
|
|
797
|
-
</a>
|
|
798
|
-
))}
|
|
799
|
-
</nav>
|
|
800
|
-
);
|
|
801
|
-
});
|
|
307
|
+
export async function renameProduct(id: string, name: string) {
|
|
308
|
+
await db.products.rename(id, name);
|
|
309
|
+
await updateTag("products"); // awaitable, read-your-own-writes
|
|
310
|
+
}
|
|
802
311
|
```
|
|
803
312
|
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
Use `Prerender()` for route-scoped pre-rendering. With params, provide `getParams` first, handler second:
|
|
313
|
+
Navigation speed is a `Link` prop away:
|
|
807
314
|
|
|
808
315
|
```tsx
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
async () => {
|
|
813
|
-
const slugs = await getAllBlogSlugs();
|
|
814
|
-
return slugs.map((slug) => ({ slug }));
|
|
815
|
-
},
|
|
816
|
-
async (ctx) => {
|
|
817
|
-
const post = await getPost(ctx.params.slug);
|
|
818
|
-
return <article>{post.content}</article>;
|
|
819
|
-
},
|
|
820
|
-
);
|
|
316
|
+
<Link to={url} prefetch="viewport">
|
|
317
|
+
{product.name}
|
|
318
|
+
</Link>
|
|
821
319
|
```
|
|
822
320
|
|
|
823
|
-
|
|
321
|
+
A fully-prefetched navigation commits a **finished page** — no skeleton, no
|
|
322
|
+
loading flash — and staying correct is the router's job: every action
|
|
323
|
+
invalidates the prefetch caches by default, so a prefetched page can't show
|
|
324
|
+
pre-mutation data.
|
|
824
325
|
|
|
825
|
-
|
|
326
|
+
To move the shell's cost to build time entirely, `Prerender()` bakes it while
|
|
327
|
+
loaders stay live at runtime — same mental model, earlier cache write. See
|
|
328
|
+
the [`/prerender` skill](./skills/prerender/SKILL.md).
|
|
826
329
|
|
|
827
|
-
|
|
828
|
-
import { Prerender, Passthrough } from "@rangojs/router";
|
|
829
|
-
|
|
830
|
-
export const ProductPageDef = Prerender(
|
|
831
|
-
async () => {
|
|
832
|
-
const featured = await db.getFeaturedProducts();
|
|
833
|
-
return featured.map((p) => ({ id: p.id }));
|
|
834
|
-
},
|
|
835
|
-
async (ctx) => {
|
|
836
|
-
const product = await db.getProduct(ctx.params.id);
|
|
837
|
-
return <Product data={product} />;
|
|
838
|
-
},
|
|
839
|
-
);
|
|
840
|
-
|
|
841
|
-
// In route definition:
|
|
842
|
-
path(
|
|
843
|
-
"/products/:id",
|
|
844
|
-
Passthrough(ProductPageDef, async (ctx) => {
|
|
845
|
-
const product = await ctx.env.DB.getProduct(ctx.params.id);
|
|
846
|
-
return <Product data={product} />;
|
|
847
|
-
}),
|
|
848
|
-
);
|
|
849
|
-
```
|
|
330
|
+
## 5. An API, when you need one
|
|
850
331
|
|
|
851
|
-
|
|
332
|
+
Response routes live in the same tree — `path.json()`, `path.text()`,
|
|
333
|
+
`path.xml()`, `path.image()`, `path.stream()`:
|
|
852
334
|
|
|
853
335
|
```tsx
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
},
|
|
859
|
-
async (ctx) => {
|
|
860
|
-
const product = await db.getProduct(ctx.params.id);
|
|
861
|
-
if (!product.published) return ctx.passthrough();
|
|
862
|
-
return <Product data={product} />;
|
|
863
|
-
},
|
|
864
|
-
);
|
|
336
|
+
path("/products/:slug", ProductPage, { name: "product" }),
|
|
337
|
+
path.json("/products/:slug", (ctx) => db.products.find(ctx.params.slug), {
|
|
338
|
+
name: "productJson",
|
|
339
|
+
}),
|
|
865
340
|
```
|
|
866
341
|
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
342
|
+
Same URL: browsers get the page, API clients get JSON, negotiated by
|
|
343
|
+
`Accept` header in the route trie. Handlers return bare values; errors
|
|
344
|
+
serialize as RFC 9457 `application/problem+json`. The payload type is
|
|
345
|
+
inferred from the handler — no codegen:
|
|
870
346
|
|
|
871
347
|
```ts
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
)
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
348
|
+
type Product = RouteResponse<typeof urlpatterns, "productJson">;
|
|
349
|
+
```
|
|
350
|
+
|
|
351
|
+
See the [`/api-client` skill](./skills/api-client/SKILL.md) for a small typed
|
|
352
|
+
client over these endpoints.
|
|
353
|
+
|
|
354
|
+
## Everything else, when you need it
|
|
355
|
+
|
|
356
|
+
That was the core: `path`/`layout`/`include`, names, loaders, actions +
|
|
357
|
+
`revalidate`, `cache`, response routes. The rest is opt-in — reach for it
|
|
358
|
+
when the requirement appears:
|
|
359
|
+
|
|
360
|
+
| I need to… | Skill |
|
|
361
|
+
| ----------------------------------------------- | -------------------------------------------------------------------------------------------- |
|
|
362
|
+
| guard or shape requests (auth, headers) | [`/middleware`](./skills/middleware/SKILL.md) |
|
|
363
|
+
| multi-column layouts, independent slots | [`/parallel`](./skills/parallel/SKILL.md) |
|
|
364
|
+
| open a route as a modal on soft navigation | [`/intercept`](./skills/intercept/SKILL.md) |
|
|
365
|
+
| compose route modules / sub-apps | [`/route`](./skills/route/SKILL.md), [`/composability`](./skills/composability/SKILL.md) |
|
|
366
|
+
| cache a single function or component | [`/use-cache`](./skills/use-cache/SKILL.md), [`/cache-guide`](./skills/cache-guide/SKILL.md) |
|
|
367
|
+
| feed live loaders from a cached shell | [`/shell-manifest`](./skills/shell-manifest/SKILL.md) |
|
|
368
|
+
| edge caching with Cache-Control | [`/document-cache`](./skills/document-cache/SKILL.md) |
|
|
369
|
+
| light/dark mode without FOUC | [`/theme`](./skills/theme/SKILL.md) |
|
|
370
|
+
| analytics / third-party scripts with CSP nonce | [`/scripts`](./skills/scripts/SKILL.md) |
|
|
371
|
+
| locale routing | [`/i18n`](./skills/i18n/SKILL.md) |
|
|
372
|
+
| SSE and WebSockets | [`/streams-and-websockets`](./skills/streams-and-websockets/SKILL.md) |
|
|
373
|
+
| multi-app routing by domain | [`/host-router`](./skills/host-router/SKILL.md) |
|
|
374
|
+
| animate navigations | [`/view-transitions`](./skills/view-transitions/SKILL.md) |
|
|
375
|
+
| test loaders, middleware, handlers, Flight | [`/testing`](./skills/testing/SKILL.md) |
|
|
376
|
+
| see where request time goes | [`/observability`](./skills/observability/SKILL.md) |
|
|
377
|
+
| deploy to Vercel (cache store, tracing, output) | [`/vercel`](./skills/vercel/SKILL.md) |
|
|
378
|
+
| compare Rango with Next.js / TanStack / Waku | [`/comparison`](./skills/comparison/SKILL.md) |
|
|
379
|
+
|
|
380
|
+
The [`/rango` skill](./skills/rango/SKILL.md) is the full catalog and the
|
|
381
|
+
mental model that ties it together.
|
|
382
|
+
|
|
383
|
+
## Reference
|
|
384
|
+
|
|
385
|
+
### Imports and subpaths
|
|
386
|
+
|
|
387
|
+
| Export | Description |
|
|
388
|
+
| ------------------------- | ------------------------------------------------------------------------------------------------------------------------------ |
|
|
389
|
+
| `@rangojs/router` | Server/RSC core and shared types: `createRouter`, `urls`, `createLoader`, `Handler`, `Prerender`, `Meta` |
|
|
390
|
+
| `@rangojs/router/client` | Client: `Link`, `Outlet`, `href`, `useNavigation`, `useLoader`, `MetaTags` |
|
|
391
|
+
| `@rangojs/router/cache` | Cache: `CFCacheStore`, `VercelCacheStore`, `MemorySegmentCacheStore`, `createDocumentCacheMiddleware` |
|
|
392
|
+
| `@rangojs/router/theme` | Theme: `useTheme`, `ThemeProvider`, `ThemeScript` |
|
|
393
|
+
| `@rangojs/router/host` | Host routing: `createHostRouter`, `defineHosts`, `isNoRouteMatchError` |
|
|
394
|
+
| `@rangojs/router/vercel` | Vercel: `createVercelTracing` (phase spans via `@vercel/otel`'s global tracer) |
|
|
395
|
+
| `@rangojs/router/vite` | Vite plugin: `rango()` |
|
|
396
|
+
| `@rangojs/router/testing` | Consumer testing primitives: `runLoader`, `runMiddleware`, `dispatch` (plus `/testing/dom`, `/testing/flight`, `/testing/e2e`) |
|
|
397
|
+
| `@rangojs/router/rsc` | Advanced server pipeline APIs: `createRSCHandler`, request-context access |
|
|
398
|
+
| `@rangojs/router/ssr` | Advanced SSR bridge APIs: `createSSRHandler` |
|
|
399
|
+
|
|
400
|
+
Use only subpaths that are explicitly exported; avoid deep imports.
|
|
401
|
+
|
|
402
|
+
The root entry is conditionally resolved: server-only APIs (`createRouter`,
|
|
403
|
+
`urls`, `redirect`, `Prerender`, `cookies`) run under the `react-server`
|
|
404
|
+
condition and throw guidance errors elsewhere. If you hit a root-entrypoint
|
|
405
|
+
stub error: hooks and components (`Link`, `Outlet`, `useLoader`, `MetaTags`)
|
|
406
|
+
live in `@rangojs/router/client`; cache APIs in `@rangojs/router/cache`;
|
|
407
|
+
host APIs in `@rangojs/router/host`.
|
|
408
|
+
|
|
409
|
+
### Type safety
|
|
410
|
+
|
|
411
|
+
The Vite plugin generates `router.named-routes.gen.ts` automatically (on dev
|
|
412
|
+
startup, HMR, and builds), registering route names, params, and search
|
|
413
|
+
schemas globally via `Rango.GeneratedRouteMap`. That powers `Handler<"name">`,
|
|
414
|
+
`ctx.reverse()`, and `RouteParams<"name">` with no manual registration.
|
|
415
|
+
|
|
416
|
+
For response-aware and path-based utilities (`href()`, `Rango.Path`,
|
|
417
|
+
`RouteResponse`), augment `Rango.RegisteredRoutes` once:
|
|
896
418
|
|
|
897
419
|
```ts
|
|
898
|
-
// Custom factory
|
|
899
|
-
rango({
|
|
900
|
-
buildEnv: async (ctx) => {
|
|
901
|
-
const { getPlatformProxy } = await import("wrangler");
|
|
902
|
-
const proxy = await getPlatformProxy();
|
|
903
|
-
return { env: proxy.env, dispose: proxy.dispose };
|
|
904
|
-
},
|
|
905
|
-
});
|
|
906
|
-
|
|
907
|
-
// Plain object (Node.js)
|
|
908
|
-
rango({ buildEnv: { DATABASE_URL: process.env.DATABASE_URL } });
|
|
909
|
-
```
|
|
910
|
-
|
|
911
|
-
Build-time env applies to both production builds and dev on-demand prerender. Without `buildEnv`, accessing `ctx.env` in a Prerender handler throws with a clear error.
|
|
912
|
-
|
|
913
|
-
## Theme
|
|
914
|
-
|
|
915
|
-
### Router Configuration
|
|
916
|
-
|
|
917
|
-
```tsx
|
|
918
|
-
export const router = createRouter({
|
|
919
|
-
document: Document,
|
|
920
|
-
theme: {
|
|
921
|
-
defaultTheme: "light",
|
|
922
|
-
themes: ["light", "dark", "system"],
|
|
923
|
-
attribute: "class",
|
|
924
|
-
enableSystem: true,
|
|
925
|
-
},
|
|
926
|
-
}).routes(urlpatterns);
|
|
927
|
-
```
|
|
928
|
-
|
|
929
|
-
### Theme Toggle
|
|
930
|
-
|
|
931
|
-
```tsx
|
|
932
|
-
"use client";
|
|
933
|
-
import { useTheme } from "@rangojs/router/theme";
|
|
934
|
-
|
|
935
|
-
function ThemeToggle() {
|
|
936
|
-
const { theme, setTheme, themes } = useTheme();
|
|
937
|
-
return (
|
|
938
|
-
<select value={theme} onChange={(e) => setTheme(e.target.value)}>
|
|
939
|
-
{themes.map((t) => (
|
|
940
|
-
<option key={t}>{t}</option>
|
|
941
|
-
))}
|
|
942
|
-
</select>
|
|
943
|
-
);
|
|
944
|
-
}
|
|
945
|
-
```
|
|
946
|
-
|
|
947
|
-
## Host Routing
|
|
948
|
-
|
|
949
|
-
Route requests to different apps based on domain/subdomain patterns using `@rangojs/router/host`:
|
|
950
|
-
|
|
951
|
-
```tsx
|
|
952
|
-
// worker.rsc.tsx
|
|
953
|
-
import { createHostRouter } from "@rangojs/router/host";
|
|
954
|
-
|
|
955
|
-
const hostRouter = createHostRouter();
|
|
956
|
-
|
|
957
|
-
hostRouter.host(["*.localhost"]).lazy(() => import("./apps/admin/handler.js"));
|
|
958
|
-
hostRouter.host(["localhost"]).lazy(() => import("./apps/site/handler.js"));
|
|
959
|
-
hostRouter.fallback().lazy(() => import("./apps/site/handler.js"));
|
|
960
|
-
|
|
961
|
-
export default {
|
|
962
|
-
async fetch(request, env, ctx) {
|
|
963
|
-
return hostRouter.match(request, { env, ctx });
|
|
964
|
-
},
|
|
965
|
-
};
|
|
966
|
-
```
|
|
967
|
-
|
|
968
|
-
Use `.lazy(() => import("./sub-app"))` to mount a lazily-imported sub-app (a module whose `default` export is a handler or nested host router), and `.map((request) => Response)` for an inline request handler. Only `.lazy()` mounts are imported during build-time discovery; `.map(() => import(...))` is a type error. Each sub-app has its own `createRouter()` and `urls()`. Patterns are matched in registration order — register more specific patterns (subdomains) before catch-alls.
|
|
969
|
-
|
|
970
|
-
The example above is the **Cloudflare** shape, where you own the worker entry. On the **node/vercel** presets rango owns the served entry, so export the `HostRouter` instance instead of a `{ fetch }` object, and point `rango()` at it (a host app has several `createRouter()` sub-apps, so set `hostRouter`; rango also auto-detects a lone `createHostRouter()` file):
|
|
971
|
-
|
|
972
|
-
```tsx
|
|
973
|
-
// worker.rsc.tsx
|
|
974
|
-
export const hostRouter = createHostRouter();
|
|
975
|
-
hostRouter.host(["admin.*"]).lazy(() => import("./apps/admin/handler.js"));
|
|
976
|
-
hostRouter.host(["."]).lazy(() => import("./apps/site/handler.js"));
|
|
977
|
-
export default hostRouter; // the instance — the generated entry calls match()
|
|
978
|
-
|
|
979
|
-
// vite.config.ts
|
|
980
|
-
rango({ preset: "vercel", hostRouter: "./src/worker.rsc.tsx" });
|
|
981
|
-
```
|
|
982
|
-
|
|
983
|
-
On Vercel this is a single function running `hostRouter.match()` for every request. See the `host-router` and `vercel` skills.
|
|
984
|
-
|
|
985
|
-
## Meta Tags
|
|
986
|
-
|
|
987
|
-
Accumulate meta tags across route segments using the built-in `Meta` handle:
|
|
988
|
-
|
|
989
|
-
```tsx
|
|
990
|
-
import { Meta } from "@rangojs/router";
|
|
991
|
-
import type { HandlerContext } from "@rangojs/router";
|
|
992
|
-
|
|
993
|
-
export function BlogPostPage(ctx: HandlerContext) {
|
|
994
|
-
const meta = ctx.use(Meta);
|
|
995
|
-
meta({ title: "My Blog Post" });
|
|
996
|
-
meta({ name: "description", content: "A great blog post" });
|
|
997
|
-
meta({ property: "og:title", content: "My Blog Post" });
|
|
998
|
-
|
|
999
|
-
return <article>...</article>;
|
|
1000
|
-
}
|
|
1001
|
-
```
|
|
1002
|
-
|
|
1003
|
-
Render collected tags in the document with `<MetaTags />` from `@rangojs/router/client`.
|
|
1004
|
-
|
|
1005
|
-
## Scripts
|
|
1006
|
-
|
|
1007
|
-
Inject `<script>` tags (analytics, GTM, widgets) the same way, using the built-in
|
|
1008
|
-
`Script` handle — push a config from a handler, render with `<Scripts />`:
|
|
1009
|
-
|
|
1010
|
-
```tsx
|
|
1011
|
-
import { Script } from "@rangojs/router";
|
|
1012
|
-
import type { HandlerContext } from "@rangojs/router";
|
|
1013
|
-
import { Outlet } from "@rangojs/router/client";
|
|
1014
|
-
|
|
1015
|
-
export function RootLayout(ctx: HandlerContext) {
|
|
1016
|
-
// Inline bootstrap (GTM/GA4/Segment) — rendered with the request CSP nonce.
|
|
1017
|
-
ctx.use(Script)({ id: "gtm", children: gtmBootstrap("GTM-XXXX") });
|
|
1018
|
-
// External async resource (loads on first encounter, deduped by src).
|
|
1019
|
-
ctx.use(Script)({
|
|
1020
|
-
id: "plausible",
|
|
1021
|
-
src: "https://plausible.io/js/script.js",
|
|
1022
|
-
async: true,
|
|
1023
|
-
attributes: { "data-domain": "example.com" },
|
|
1024
|
-
});
|
|
1025
|
-
return <Outlet />;
|
|
1026
|
-
}
|
|
1027
|
-
```
|
|
1028
|
-
|
|
1029
|
-
Render with `<Scripts />` (head) and `<Scripts position="body" />` (body) from
|
|
1030
|
-
`@rangojs/router/client` (both are wired in `DefaultDocument`). The request CSP
|
|
1031
|
-
nonce is applied automatically to document-rendered scripts. `ScriptConfig` is a
|
|
1032
|
-
discriminated union (inline / external-async / external-ordered), and inline +
|
|
1033
|
-
ordered scripts are document-load while async externals are React resources — see
|
|
1034
|
-
the [`/scripts` skill](./skills/scripts/SKILL.md) for the full execution contract
|
|
1035
|
-
and CSP guidance.
|
|
1036
|
-
|
|
1037
|
-
## CLI: `rango generate`
|
|
1038
|
-
|
|
1039
|
-
Route types are generated automatically by the Vite plugin. The CLI is a manual fallback for generating types outside the dev server (e.g. in CI or for IDE support before first `pnpm dev`):
|
|
1040
|
-
|
|
1041
|
-
```bash
|
|
1042
|
-
npx rango generate src/router.tsx
|
|
1043
|
-
npx rango generate src/ # recursive scan
|
|
1044
|
-
npx rango generate src/urls.tsx src/api/ # mix files and directories
|
|
1045
|
-
```
|
|
1046
|
-
|
|
1047
|
-
Auto-detects file type:
|
|
1048
|
-
|
|
1049
|
-
- Files with `createRouter` → `*.named-routes.gen.ts` with global route map
|
|
1050
|
-
- Files with `urls()` → `*.gen.ts` with per-module route names, params, and search types
|
|
1051
|
-
|
|
1052
|
-
## Type Safety
|
|
1053
|
-
|
|
1054
|
-
The Vite plugin automatically generates a `router.named-routes.gen.ts` file that globally registers route names, patterns, and search schemas via `Rango.GeneratedRouteMap`. This powers server-side named-route typing such as `Handler<"name">`, `ctx.reverse()`, `getRequestContext().reverse()`, and `RouteParams<"name">` without any manual route registration. The gen file is updated on dev server startup, HMR, and production builds.
|
|
1055
|
-
|
|
1056
|
-
Use the generated map by default. Augment `Rango.RegisteredRoutes` only when you need the richer `typeof router.routeMap` shape globally, especially for response-aware and path-based utilities.
|
|
1057
|
-
|
|
1058
|
-
```typescript
|
|
1059
420
|
// router.tsx
|
|
1060
421
|
const router = createRouter<AppBindings>({}).routes(urlpatterns);
|
|
1061
422
|
|
|
1062
423
|
declare global {
|
|
1063
424
|
namespace Rango {
|
|
1064
425
|
interface Env extends AppEnv {}
|
|
1065
|
-
interface Vars extends AppVars {}
|
|
1066
426
|
interface RegisteredRoutes extends typeof router.routeMap {}
|
|
1067
427
|
}
|
|
1068
428
|
}
|
|
1069
429
|
```
|
|
1070
430
|
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
- `GeneratedRouteMap` (auto-generated) — use for server-side named-route typing: `Handler<"name">`, `ctx.reverse()`, `Prerender<"name">`
|
|
1074
|
-
- `typeof router.routeMap` — use when you need route entries with response metadata
|
|
1075
|
-
- `RegisteredRoutes` (manual augmentation) — use to expose `typeof router.routeMap` globally for `href()`, `Rango.Path`, `Rango.PathResponse`, and other path/response-aware utilities
|
|
431
|
+
See the [`/typesafety` skill](./skills/typesafety/SKILL.md) for the full
|
|
432
|
+
surface breakdown.
|
|
1076
433
|
|
|
1077
|
-
|
|
1078
|
-
`ctx.reverse()` by default. If you want type-safe local names for a specific
|
|
1079
|
-
module, use `scopedReverse<typeof localPatterns>(ctx.reverse)` or
|
|
1080
|
-
`scopedReverse<routes>(ctx.reverse)` with a generated local route type.
|
|
434
|
+
### CLI
|
|
1081
435
|
|
|
1082
|
-
|
|
436
|
+
Route types are generated by the Vite plugin; the CLI is the manual fallback
|
|
437
|
+
for CI or pre-first-run IDE support:
|
|
1083
438
|
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
|
|
1088
|
-
| `@rangojs/router/cache` | Cache: `CFCacheStore`, `MemorySegmentCacheStore`, `createDocumentCacheMiddleware` |
|
|
1089
|
-
| `@rangojs/router/theme` | Theme: `useTheme`, `ThemeProvider`, `ThemeScript` |
|
|
1090
|
-
| `@rangojs/router/host` | Host routing: `createHostRouter`, `defineHosts` |
|
|
1091
|
-
| `@rangojs/router/vite` | Vite plugin: `rango()` |
|
|
1092
|
-
| `@rangojs/router/rsc` | Advanced server pipeline APIs: `createRSCHandler`, request-context access |
|
|
1093
|
-
| `@rangojs/router/ssr` | Advanced SSR bridge APIs: `createSSRHandler` |
|
|
1094
|
-
| `@rangojs/router/server` | Internal build/runtime utilities for advanced integrations |
|
|
1095
|
-
| `@rangojs/router/build` | Build utilities |
|
|
439
|
+
```bash
|
|
440
|
+
npx rango generate src/router.tsx # global named-route map
|
|
441
|
+
npx rango generate src/ # recursive scan
|
|
442
|
+
```
|
|
1096
443
|
|
|
1097
|
-
|
|
1098
|
-
or components, import from `@rangojs/router/client`; if you need cache or host
|
|
1099
|
-
APIs, use their dedicated subpaths.
|
|
444
|
+
### Examples
|
|
1100
445
|
|
|
1101
|
-
|
|
446
|
+
- [`e2e/mini`](https://github.com/ivogt/vite-rsc/tree/main/packages/rangojs-router/e2e/mini) — single-file demo app
|
|
447
|
+
- [`cloudflare-basic`](https://github.com/ivogt/vite-rsc/tree/main/tests/cloudflare-basic) — Cloudflare Workers with caching, loaders, theme, and pre-rendering
|
|
448
|
+
- [`cloudflare-multi-router`](https://github.com/ivogt/vite-rsc/tree/main/examples/cloudflare-multi-router) — multi-app host routing
|
|
449
|
+
- [`vercel-basic`](https://github.com/ivogt/vite-rsc/tree/main/examples/vercel-basic) — Vercel deployment with `preset: "vercel"`, `VercelCacheStore`, and OTel tracing
|
|
450
|
+
- [`vercel-multi-router`](https://github.com/ivogt/vite-rsc/tree/main/examples/vercel-multi-router) — multi-app host routing on Vercel (single function, routed by Host header)
|
|
1102
451
|
|
|
1103
|
-
|
|
452
|
+
### Going deeper
|
|
1104
453
|
|
|
1105
|
-
- [
|
|
1106
|
-
- [
|
|
454
|
+
- [Why Rango](https://github.com/ivogt/vite-rsc/blob/main/packages/rangojs-router/docs/why-rango.md) — the design rationale, claim by claim
|
|
455
|
+
- [Framework comparison](./skills/comparison/references/framework-comparison.md) — Rango vs Next.js App Router, TanStack Start, and Waku, capability by capability
|
|
456
|
+
- [Docs index](https://github.com/ivogt/vite-rsc/blob/main/packages/rangojs-router/docs/README.md) — architecture, caching, prerender, testing
|
|
457
|
+
- [Execution model](https://github.com/ivogt/vite-rsc/blob/main/packages/rangojs-router/docs/internal/execution-model.md) — the runtime contract
|
|
1107
458
|
|
|
1108
459
|
## License
|
|
1109
460
|
|