react-router 8.3.1 → 8.5.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/CHANGELOG.md +83 -0
- package/dist/development/dom-export.d.ts +2 -1
- package/dist/development/dom-export.js +1 -1
- package/dist/development/index-react-server-client.js +2 -2
- package/dist/development/index-react-server.d.ts +601 -189
- package/dist/development/index-react-server.js +100 -48
- package/dist/development/index.d.ts +10 -9
- package/dist/development/index.js +6 -5
- package/dist/development/lib/actions.js +1 -1
- package/dist/development/lib/components.js +66 -10
- package/dist/development/lib/context.d.ts +19 -6
- package/dist/development/lib/context.js +11 -3
- package/dist/development/lib/dom/dom.d.ts +3 -0
- package/dist/development/lib/dom/dom.js +1 -1
- package/dist/development/lib/dom/global.d.ts +35 -0
- package/dist/development/lib/dom/lib.d.ts +34 -9
- package/dist/development/lib/dom/lib.js +30 -37
- package/dist/development/lib/dom/server.d.ts +6 -1
- package/dist/development/lib/dom/server.js +41 -15
- package/dist/development/lib/dom/ssr/components.js +26 -31
- package/dist/development/lib/dom/ssr/data.js +1 -1
- package/dist/development/lib/dom/ssr/entry.d.ts +13 -2
- package/dist/development/lib/dom/ssr/errorBoundaries.js +1 -1
- package/dist/development/lib/dom/ssr/fallback.js +1 -1
- package/dist/development/lib/dom/ssr/fog-of-war.d.ts +3 -2
- package/dist/development/lib/dom/ssr/fog-of-war.js +46 -22
- package/dist/development/lib/dom/ssr/hydration.d.ts +3 -1
- package/dist/development/lib/dom/ssr/hydration.js +6 -4
- package/dist/development/lib/dom/ssr/invariant.js +1 -1
- package/dist/development/lib/dom/ssr/links.js +1 -1
- package/dist/development/lib/dom/ssr/markup.js +5 -2
- package/dist/development/lib/dom/ssr/route-discovery.d.ts +120 -0
- package/dist/development/lib/dom/ssr/route-discovery.js +415 -0
- package/dist/development/lib/dom/ssr/routeModules.js +1 -1
- package/dist/development/lib/dom/ssr/routes-test-stub.js +2 -2
- package/dist/development/lib/dom/ssr/routes.d.ts +2 -2
- package/dist/development/lib/dom/ssr/routes.js +8 -8
- package/dist/development/lib/dom/ssr/server.js +4 -2
- package/dist/development/lib/dom/ssr/single-fetch.d.ts +28 -2
- package/dist/development/lib/dom/ssr/single-fetch.js +80 -71
- package/dist/development/lib/dom-export/dom-router-provider.js +1 -1
- package/dist/development/lib/dom-export/hydrated-router.d.ts +28 -0
- package/dist/development/lib/dom-export/hydrated-router.js +33 -12
- package/dist/development/lib/errors.js +1 -1
- package/dist/development/lib/hooks.d.ts +3 -3
- package/dist/development/lib/hooks.js +52 -47
- package/dist/development/lib/href.js +1 -1
- package/dist/development/lib/router/history.js +1 -1
- package/dist/development/lib/router/instrumentation.js +1 -1
- package/dist/development/lib/router/matcher-route-pattern.d.ts +2 -0
- package/dist/development/lib/router/matcher-route-pattern.js +216 -0
- package/dist/development/lib/router/matcher-route-pattern.preload.d.ts +20 -0
- package/dist/development/lib/router/matcher-route-pattern.preload.js +36 -0
- package/dist/development/lib/router/matcher.d.ts +2 -0
- package/dist/development/lib/router/matcher.js +29 -0
- package/dist/development/lib/router/navigation.js +1 -1
- package/dist/development/lib/router/router.d.ts +19 -7
- package/dist/development/lib/router/router.js +235 -128
- package/dist/development/lib/router/url.js +1 -1
- package/dist/development/lib/router/utils.d.ts +30 -5
- package/dist/development/lib/router/utils.js +8 -5
- package/dist/development/lib/rsc/browser.js +3 -2
- package/dist/development/lib/rsc/errorBoundaries.js +1 -1
- package/dist/development/lib/rsc/html-stream/browser.js +1 -1
- package/dist/development/lib/rsc/html-stream/server.js +25 -15
- package/dist/development/lib/rsc/route-modules.js +1 -1
- package/dist/development/lib/rsc/server.rsc.d.ts +10 -2
- package/dist/development/lib/rsc/server.ssr.js +25 -21
- package/dist/development/lib/server-runtime/build.d.ts +14 -0
- package/dist/development/lib/server-runtime/cookies.js +1 -1
- package/dist/development/lib/server-runtime/crypto.js +1 -1
- package/dist/development/lib/server-runtime/data.js +1 -1
- package/dist/development/lib/server-runtime/dev.js +1 -1
- package/dist/development/lib/server-runtime/entry.js +1 -1
- package/dist/development/lib/server-runtime/errors.js +1 -1
- package/dist/development/lib/server-runtime/headers.js +1 -1
- package/dist/development/lib/server-runtime/invariant.js +1 -1
- package/dist/development/lib/server-runtime/mode.js +1 -1
- package/dist/development/lib/server-runtime/routeMatching.js +3 -4
- package/dist/development/lib/server-runtime/routes.d.ts +1 -1
- package/dist/development/lib/server-runtime/routes.js +1 -1
- package/dist/development/lib/server-runtime/server.js +18 -9
- package/dist/development/lib/server-runtime/serverHandoff.d.ts +17 -0
- package/dist/development/lib/server-runtime/serverHandoff.js +1 -1
- package/dist/development/lib/server-runtime/sessions/cookieStorage.js +1 -1
- package/dist/development/lib/server-runtime/sessions/memoryStorage.js +1 -1
- package/dist/development/lib/server-runtime/sessions.js +1 -1
- package/dist/development/lib/server-runtime/single-fetch.js +1 -1
- package/dist/development/lib/server-runtime/urls.js +1 -1
- package/dist/development/lib/server-runtime/warnings.js +1 -1
- package/dist/development/lib/types/internal.js +1 -1
- package/dist/development/lib/types/route-data.d.ts +2 -2
- package/dist/development/lib/types/route-module-annotations.d.ts +1 -1
- package/dist/development/route-pattern.d.ts +3 -0
- package/dist/development/route-pattern.js +12 -0
- package/dist/development/vendor/turbo-stream-v2/flatten.js +1 -1
- package/dist/development/vendor/turbo-stream-v2/turbo-stream.js +1 -1
- package/dist/development/vendor/turbo-stream-v2/unflatten.js +1 -1
- package/dist/development/vendor/turbo-stream-v2/utils.js +1 -1
- package/dist/production/dom-export.d.ts +2 -1
- package/dist/production/dom-export.js +1 -1
- package/dist/production/index-react-server-client.js +2 -2
- package/dist/production/index-react-server.d.ts +601 -189
- package/dist/production/index-react-server.js +100 -48
- package/dist/production/index.d.ts +10 -9
- package/dist/production/index.js +6 -5
- package/dist/production/lib/actions.js +1 -1
- package/dist/production/lib/components.js +66 -10
- package/dist/production/lib/context.d.ts +19 -6
- package/dist/production/lib/context.js +11 -3
- package/dist/production/lib/dom/dom.d.ts +3 -0
- package/dist/production/lib/dom/dom.js +1 -1
- package/dist/production/lib/dom/global.d.ts +35 -0
- package/dist/production/lib/dom/lib.d.ts +34 -9
- package/dist/production/lib/dom/lib.js +30 -37
- package/dist/production/lib/dom/server.d.ts +6 -1
- package/dist/production/lib/dom/server.js +41 -15
- package/dist/production/lib/dom/ssr/components.js +26 -31
- package/dist/production/lib/dom/ssr/data.js +1 -1
- package/dist/production/lib/dom/ssr/entry.d.ts +13 -2
- package/dist/production/lib/dom/ssr/errorBoundaries.js +1 -1
- package/dist/production/lib/dom/ssr/fallback.js +1 -1
- package/dist/production/lib/dom/ssr/fog-of-war.d.ts +3 -2
- package/dist/production/lib/dom/ssr/fog-of-war.js +46 -22
- package/dist/production/lib/dom/ssr/hydration.d.ts +3 -1
- package/dist/production/lib/dom/ssr/hydration.js +6 -4
- package/dist/production/lib/dom/ssr/invariant.js +1 -1
- package/dist/production/lib/dom/ssr/links.js +1 -1
- package/dist/production/lib/dom/ssr/markup.js +5 -2
- package/dist/production/lib/dom/ssr/route-discovery.d.ts +120 -0
- package/dist/production/lib/dom/ssr/route-discovery.js +415 -0
- package/dist/production/lib/dom/ssr/routeModules.js +1 -1
- package/dist/production/lib/dom/ssr/routes-test-stub.js +2 -2
- package/dist/production/lib/dom/ssr/routes.d.ts +2 -2
- package/dist/production/lib/dom/ssr/routes.js +8 -8
- package/dist/production/lib/dom/ssr/server.js +4 -2
- package/dist/production/lib/dom/ssr/single-fetch.d.ts +28 -2
- package/dist/production/lib/dom/ssr/single-fetch.js +80 -71
- package/dist/production/lib/dom-export/dom-router-provider.js +1 -1
- package/dist/production/lib/dom-export/hydrated-router.d.ts +28 -0
- package/dist/production/lib/dom-export/hydrated-router.js +33 -12
- package/dist/production/lib/errors.js +1 -1
- package/dist/production/lib/hooks.d.ts +3 -3
- package/dist/production/lib/hooks.js +51 -46
- package/dist/production/lib/href.js +1 -1
- package/dist/production/lib/router/history.js +1 -1
- package/dist/production/lib/router/instrumentation.js +1 -1
- package/dist/production/lib/router/matcher-route-pattern.d.ts +2 -0
- package/dist/production/lib/router/matcher-route-pattern.js +216 -0
- package/dist/production/lib/router/matcher-route-pattern.preload.d.ts +20 -0
- package/dist/production/lib/router/matcher-route-pattern.preload.js +36 -0
- package/dist/production/lib/router/matcher.d.ts +2 -0
- package/dist/production/lib/router/matcher.js +29 -0
- package/dist/production/lib/router/navigation.js +1 -1
- package/dist/production/lib/router/router.d.ts +19 -7
- package/dist/production/lib/router/router.js +235 -128
- package/dist/production/lib/router/url.js +1 -1
- package/dist/production/lib/router/utils.d.ts +30 -5
- package/dist/production/lib/router/utils.js +8 -5
- package/dist/production/lib/rsc/browser.js +3 -2
- package/dist/production/lib/rsc/errorBoundaries.js +1 -1
- package/dist/production/lib/rsc/html-stream/browser.js +1 -1
- package/dist/production/lib/rsc/html-stream/server.js +25 -15
- package/dist/production/lib/rsc/route-modules.js +1 -1
- package/dist/production/lib/rsc/server.rsc.d.ts +10 -2
- package/dist/production/lib/rsc/server.ssr.js +25 -21
- package/dist/production/lib/server-runtime/build.d.ts +14 -0
- package/dist/production/lib/server-runtime/cookies.js +1 -1
- package/dist/production/lib/server-runtime/crypto.js +1 -1
- package/dist/production/lib/server-runtime/data.js +1 -1
- package/dist/production/lib/server-runtime/dev.js +1 -1
- package/dist/production/lib/server-runtime/entry.js +1 -1
- package/dist/production/lib/server-runtime/errors.js +1 -1
- package/dist/production/lib/server-runtime/headers.js +1 -1
- package/dist/production/lib/server-runtime/invariant.js +1 -1
- package/dist/production/lib/server-runtime/mode.js +1 -1
- package/dist/production/lib/server-runtime/routeMatching.js +3 -4
- package/dist/production/lib/server-runtime/routes.d.ts +1 -1
- package/dist/production/lib/server-runtime/routes.js +1 -1
- package/dist/production/lib/server-runtime/server.js +18 -9
- package/dist/production/lib/server-runtime/serverHandoff.d.ts +17 -0
- package/dist/production/lib/server-runtime/serverHandoff.js +1 -1
- package/dist/production/lib/server-runtime/sessions/cookieStorage.js +1 -1
- package/dist/production/lib/server-runtime/sessions/memoryStorage.js +1 -1
- package/dist/production/lib/server-runtime/sessions.js +1 -1
- package/dist/production/lib/server-runtime/single-fetch.js +1 -1
- package/dist/production/lib/server-runtime/urls.js +1 -1
- package/dist/production/lib/server-runtime/warnings.js +1 -1
- package/dist/production/lib/types/internal.js +1 -1
- package/dist/production/lib/types/route-data.d.ts +2 -2
- package/dist/production/lib/types/route-module-annotations.d.ts +1 -1
- package/dist/production/route-pattern.d.ts +3 -0
- package/dist/production/route-pattern.js +12 -0
- package/dist/production/vendor/turbo-stream-v2/flatten.js +1 -1
- package/dist/production/vendor/turbo-stream-v2/turbo-stream.js +1 -1
- package/dist/production/vendor/turbo-stream-v2/unflatten.js +1 -1
- package/dist/production/vendor/turbo-stream-v2/utils.js +1 -1
- package/docs/explanation/lazy-route-discovery.md +4 -0
- package/docs/explanation/sessions-and-cookies.md +108 -4
- package/docs/how-to/custom-fetch.md +218 -0
- package/docs/how-to/data-strategy.md +23 -1
- package/docs/how-to/fetchers.md +6 -1
- package/docs/how-to/middleware.md +4 -1
- package/docs/how-to/optimize-revalidation.md +178 -5
- package/docs/how-to/pre-rendering.md +23 -1
- package/docs/how-to/react-server-components.md +26 -3
- package/docs/how-to/resource-routes.md +3 -0
- package/docs/how-to/route-discovery.md +145 -0
- package/docs/how-to/spa.md +2 -0
- package/docs/how-to/view-transitions.md +80 -13
- package/docs/start/data/actions.md +2 -1
- package/docs/start/data/route-object.md +21 -6
- package/docs/start/framework/actions.md +4 -2
- package/docs/start/framework/navigating.md +5 -9
- package/docs/start/framework/rendering.md +37 -0
- package/docs/start/framework/route-module.md +32 -5
- package/docs/upgrading/future.md +68 -0
- package/package.json +19 -1
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
|
|
2
2
|
import { DataWithResponseInit, RouterContextProvider } from "../router/utils.js";
|
|
3
|
+
import { ClientActionFunctionArgs, ClientLoaderFunctionArgs } from "../dom/ssr/routeModules.js";
|
|
4
|
+
import { Serializable } from "../server-runtime/single-fetch.js";
|
|
3
5
|
import { Equal, Func, IsAny } from "./utils.js";
|
|
4
6
|
import { RouteModule } from "./route-module.js";
|
|
5
7
|
import { unstable_SerializesTo } from "./serializes-to.js";
|
|
6
|
-
import { Serializable } from "../server-runtime/single-fetch.js";
|
|
7
|
-
import { ClientActionFunctionArgs, ClientLoaderFunctionArgs } from "../dom/ssr/routeModules.js";
|
|
8
8
|
|
|
9
9
|
//#region lib/types/route-data.d.ts
|
|
10
10
|
type Serialize<T> = T extends unstable_SerializesTo<infer To> ? To : T extends Serializable ? T : T extends ((...args: any[]) => unknown) ? undefined : T extends Promise<infer U> ? Promise<Serialize<U>> : T extends Map<infer K, infer V> ? Map<Serialize<K>, Serialize<V>> : T extends ReadonlyMap<infer K, infer V> ? ReadonlyMap<Serialize<K>, Serialize<V>> : T extends Set<infer U> ? Set<Serialize<U>> : T extends ReadonlySet<infer U> ? ReadonlySet<Serialize<U>> : T extends [] ? [] : T extends readonly [infer F, ...infer R] ? [Serialize<F>, ...Serialize<R>] : T extends Array<infer U> ? Array<Serialize<U>> : T extends readonly unknown[] ? readonly Serialize<T[number]>[] : T extends Record<any, any> ? { [K in keyof T]: Serialize<T[K]> } : undefined;
|
|
@@ -2,10 +2,10 @@
|
|
|
2
2
|
import { Location } from "../router/history.js";
|
|
3
3
|
import { DataStrategyResult, MiddlewareNextFunction } from "../router/utils.js";
|
|
4
4
|
import { LinkDescriptor } from "../router/links.js";
|
|
5
|
+
import { MetaDescriptor } from "../dom/ssr/routeModules.js";
|
|
5
6
|
import { Func, Pretty } from "./utils.js";
|
|
6
7
|
import { RouteModule } from "./route-module.js";
|
|
7
8
|
import { ClientDataFunctionArgs, GetLoaderData, ServerDataFrom, ServerDataFunctionArgs } from "./route-data.js";
|
|
8
|
-
import { MetaDescriptor } from "../dom/ssr/routeModules.js";
|
|
9
9
|
|
|
10
10
|
//#region lib/types/route-module-annotations.d.ts
|
|
11
11
|
type MaybePromise<T> = T | Promise<T>;
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* react-router v8.5.0
|
|
3
|
+
*
|
|
4
|
+
* Copyright (c) Remix Software Inc.
|
|
5
|
+
*
|
|
6
|
+
* This source code is licensed under the MIT license found in the
|
|
7
|
+
* LICENSE.md file in the root directory of this source tree.
|
|
8
|
+
*
|
|
9
|
+
* @license MIT
|
|
10
|
+
*/
|
|
11
|
+
import { unstable_preloadRoutePattern } from "./lib/router/matcher-route-pattern.preload.js";
|
|
12
|
+
export { unstable_preloadRoutePattern };
|
|
@@ -76,3 +76,7 @@ When using lazy route discovery, ensure your deployment setup handles manifest r
|
|
|
76
76
|
- **Route Handling** - Ensure `/__manifest` requests reach your React Router handler
|
|
77
77
|
- **CDN Caching** - If using CDN/edge caching, include `version` and `paths` query parameters in your cache key for the manifest endpoint
|
|
78
78
|
- **Multiple Applications** - Use a custom `manifestPath` if running multiple React Router applications on the same domain
|
|
79
|
+
|
|
80
|
+
## Application-Controlled Discovery
|
|
81
|
+
|
|
82
|
+
Use the experimental `unstable_useRouteDiscovery` hook to discover selected destinations, complete the route tree after startup, or control manifest-mismatch recovery. See [Application-Controlled Route Discovery](../how-to/route-discovery).
|
|
@@ -59,28 +59,130 @@ The input/output to a session storage object are HTTP cookies. `getSession()` re
|
|
|
59
59
|
|
|
60
60
|
You'll use methods to get access to sessions in your `loader` and `action` functions.
|
|
61
61
|
|
|
62
|
-
|
|
62
|
+
### Session API
|
|
63
|
+
|
|
64
|
+
After retrieving a session with `getSession()`, the returned session object has a handful of methods and properties:
|
|
63
65
|
|
|
64
66
|
```tsx
|
|
65
67
|
export async function action({
|
|
66
68
|
request,
|
|
67
|
-
}:
|
|
69
|
+
}: Route.ActionArgs) {
|
|
68
70
|
const session = await getSession(
|
|
69
71
|
request.headers.get("Cookie"),
|
|
70
72
|
);
|
|
73
|
+
|
|
71
74
|
session.get("foo");
|
|
72
75
|
session.has("bar");
|
|
73
76
|
// etc.
|
|
77
|
+
|
|
78
|
+
return redirect("/", {
|
|
79
|
+
headers: {
|
|
80
|
+
"Set-Cookie": await commitSession(session),
|
|
81
|
+
},
|
|
82
|
+
});
|
|
74
83
|
}
|
|
75
84
|
```
|
|
76
85
|
|
|
77
|
-
|
|
86
|
+
<docs-warning>Every time you modify session data, you must `commitSession()` or your changes will be lost. When using cookie session storage, you must also send the `Set-Cookie` header it returns in your response.</docs-warning>
|
|
87
|
+
|
|
88
|
+
See the [Session API][session-api] for all methods and properties available on the session object.
|
|
89
|
+
|
|
90
|
+
#### `session.has(key)`
|
|
91
|
+
|
|
92
|
+
Returns `true` if the session has a value (or an unread flash value) for the given `key`. This does not consume flash values.
|
|
93
|
+
|
|
94
|
+
```ts
|
|
95
|
+
session.has("userId");
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
#### `session.set(key, value)`
|
|
99
|
+
|
|
100
|
+
Sets a session value for use in subsequent requests:
|
|
101
|
+
|
|
102
|
+
```ts
|
|
103
|
+
session.set("userId", "1234");
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
#### `session.flash(key, value)`
|
|
107
|
+
|
|
108
|
+
Sets a session value that is only valid until the next `session.get()` for that key. After that, it's gone. Most useful for "flash messages" and server-side form validation messages:
|
|
109
|
+
|
|
110
|
+
```ts
|
|
111
|
+
session.flash(
|
|
112
|
+
"globalMessage",
|
|
113
|
+
"Project successfully archived",
|
|
114
|
+
);
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
A flash value is typically set in an `action` before a redirect, then read in the `loader` of the page being redirected to:
|
|
118
|
+
|
|
119
|
+
```tsx filename=app/routes/projects.tsx
|
|
120
|
+
export async function action({
|
|
121
|
+
request,
|
|
122
|
+
}: Route.ActionArgs) {
|
|
123
|
+
const session = await getSession(
|
|
124
|
+
request.headers.get("Cookie"),
|
|
125
|
+
);
|
|
126
|
+
// ...archive the project
|
|
127
|
+
session.flash(
|
|
128
|
+
"globalMessage",
|
|
129
|
+
"Project successfully archived",
|
|
130
|
+
);
|
|
131
|
+
return redirect("/projects", {
|
|
132
|
+
headers: {
|
|
133
|
+
"Set-Cookie": await commitSession(session),
|
|
134
|
+
},
|
|
135
|
+
});
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
export async function loader({
|
|
139
|
+
request,
|
|
140
|
+
}: Route.LoaderArgs) {
|
|
141
|
+
const session = await getSession(
|
|
142
|
+
request.headers.get("Cookie"),
|
|
143
|
+
);
|
|
144
|
+
// Reading a flash value removes it from the session
|
|
145
|
+
const message = session.get("globalMessage");
|
|
146
|
+
|
|
147
|
+
return data(
|
|
148
|
+
{ message },
|
|
149
|
+
{
|
|
150
|
+
headers: {
|
|
151
|
+
// Commit the session so the flash value is removed
|
|
152
|
+
"Set-Cookie": await commitSession(session),
|
|
153
|
+
},
|
|
154
|
+
},
|
|
155
|
+
);
|
|
156
|
+
}
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
Flash values are read with `session.get()` using the same key they were set with. Reading a flash value removes it from the session, so you must still `commitSession()` after reading it; otherwise the flash value will be read again on the next request.
|
|
160
|
+
|
|
161
|
+
Avoid using the same key for both `session.set()` and `session.flash()`. `session.get()` returns the regular value first, so the flash value would never be read or removed.
|
|
162
|
+
|
|
163
|
+
You can type flash values separately from regular session values with the second generic on your session storage, like the `SessionFlashData` type in [Using Sessions](#using-sessions).
|
|
164
|
+
|
|
165
|
+
#### `session.get(key)`
|
|
166
|
+
|
|
167
|
+
Accesses a session value from a previous request:
|
|
168
|
+
|
|
169
|
+
```ts
|
|
170
|
+
session.get("name");
|
|
171
|
+
```
|
|
172
|
+
|
|
173
|
+
#### `session.unset(key)`
|
|
174
|
+
|
|
175
|
+
Removes a value from the session. This does not remove pending flash values; those are only removed when read with `session.get()`.
|
|
176
|
+
|
|
177
|
+
```ts
|
|
178
|
+
session.unset("name");
|
|
179
|
+
```
|
|
78
180
|
|
|
79
181
|
### Login form example
|
|
80
182
|
|
|
81
183
|
A login form might look something like this:
|
|
82
184
|
|
|
83
|
-
```tsx filename=app/routes/login.tsx lines=[4-7,12-14,16,22,
|
|
185
|
+
```tsx filename=app/routes/login.tsx lines=[4-7,12-14,16,22-23,26,35-37,48-49,54,59,64]
|
|
84
186
|
import { data, redirect } from "react-router";
|
|
85
187
|
import type { Route } from "./+types/login";
|
|
86
188
|
|
|
@@ -102,6 +204,7 @@ export async function loader({
|
|
|
102
204
|
}
|
|
103
205
|
|
|
104
206
|
return data(
|
|
207
|
+
// Read and unset the flash message set by the route action.
|
|
105
208
|
{ error: session.get("error") },
|
|
106
209
|
{
|
|
107
210
|
headers: {
|
|
@@ -127,6 +230,7 @@ export async function action({
|
|
|
127
230
|
);
|
|
128
231
|
|
|
129
232
|
if (userId == null) {
|
|
233
|
+
// Set a single-use flash message to be read by the route loader.
|
|
130
234
|
session.flash("error", "Invalid username/password");
|
|
131
235
|
|
|
132
236
|
// Redirect back to the login page with errors.
|
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: Custom Fetch
|
|
3
|
+
unstable: true
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Custom Fetch
|
|
7
|
+
|
|
8
|
+
[MODES: framework]
|
|
9
|
+
|
|
10
|
+
<docs-warning>This feature is experimental and may change in minor or patch releases. It is not supported in RSC Framework Mode.</docs-warning>
|
|
11
|
+
|
|
12
|
+
The `unstable_fetch` prop on [`HydratedRouter`](../api/framework-routers/HydratedRouter) lets you customize the JavaScript-issued requests React Router makes for server loader/action data and lazy route discovery. Use it to add headers, customize fetch options, or apply a request policy based on the operation that initiated the request.
|
|
13
|
+
|
|
14
|
+
This is a Framework Mode API. In Data Mode, you control fetching in your loaders/actions or through a [`dataStrategy`](./data-strategy#request-metadata-unstable).
|
|
15
|
+
|
|
16
|
+
## Setup
|
|
17
|
+
|
|
18
|
+
If you don't have an [`app/entry.client.tsx`](../api/framework-conventions/entry.client.tsx), reveal the default entry:
|
|
19
|
+
|
|
20
|
+
```shellscript nonumber
|
|
21
|
+
npx react-router reveal entry.client
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
Pass a custom implementation to `HydratedRouter`:
|
|
25
|
+
|
|
26
|
+
```tsx filename=app/entry.client.tsx
|
|
27
|
+
import { startTransition, StrictMode } from "react";
|
|
28
|
+
import { hydrateRoot } from "react-dom/client";
|
|
29
|
+
import {
|
|
30
|
+
HydratedRouter,
|
|
31
|
+
type unstable_RouterFetch,
|
|
32
|
+
} from "react-router/dom";
|
|
33
|
+
|
|
34
|
+
const customFetch: unstable_RouterFetch = (
|
|
35
|
+
request,
|
|
36
|
+
context,
|
|
37
|
+
) => {
|
|
38
|
+
console.log(context.type, request.method, request.url);
|
|
39
|
+
return fetch(request);
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
startTransition(() => {
|
|
43
|
+
hydrateRoot(
|
|
44
|
+
document,
|
|
45
|
+
<StrictMode>
|
|
46
|
+
<HydratedRouter unstable_fetch={customFetch} />
|
|
47
|
+
</StrictMode>,
|
|
48
|
+
);
|
|
49
|
+
});
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
The callback receives a constructed `Request`, including its URL, headers, body, and abort signal, and must return a `Promise<Response>`. Pass that request to the browser's `fetch` to preserve those settings, including cancellation.
|
|
53
|
+
|
|
54
|
+
`HydratedRouter` creates a singleton router and reads `unstable_fetch` only during initialization. Changing the prop later has no effect. If your implementation needs changing values such as authentication tokens, read current application state inside the callback instead of capturing values from a component render.
|
|
55
|
+
|
|
56
|
+
## Request Context
|
|
57
|
+
|
|
58
|
+
The [`unstable_RouterFetchContext`](https://api.reactrouter.com/v8/types/react-router.dom.unstable_RouterFetchContext.html) type is exported from `react-router/dom` and has the following shape:
|
|
59
|
+
|
|
60
|
+
```ts
|
|
61
|
+
import type { NavigationType } from "react-router";
|
|
62
|
+
|
|
63
|
+
type unstable_RouterFetchContext =
|
|
64
|
+
| { type: "manifest" }
|
|
65
|
+
| {
|
|
66
|
+
type: "navigation";
|
|
67
|
+
fetcherKey: string | null;
|
|
68
|
+
navigationType: NavigationType;
|
|
69
|
+
}
|
|
70
|
+
| {
|
|
71
|
+
type: "initialization" | "fetcher" | "revalidation";
|
|
72
|
+
fetcherKey: string | null;
|
|
73
|
+
navigationType: null;
|
|
74
|
+
};
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
`type` identifies the operation that initiated the request:
|
|
78
|
+
|
|
79
|
+
- `"manifest"`: Lazy route discovery requests. These have no `fetcherKey` or `navigationType`.
|
|
80
|
+
- `"initialization"`: Data loading during router initialization, such as initial loader requests in API-only Mode.
|
|
81
|
+
- `"navigation"`: Data requests initiated by a navigation, including action submissions and the subsequent loader revalidation.
|
|
82
|
+
- `"fetcher"`: Requests initiated by a fetcher, including the loader revalidation after a fetcher action.
|
|
83
|
+
- `"revalidation"`: Requests initiated by an explicit revalidation, such as `useRevalidator().revalidate()`.
|
|
84
|
+
|
|
85
|
+
`fetcherKey` identifies the fetcher targeted by a data request, or is `null` for route loader/action requests. A fetcher reloaded as part of a navigation or explicit revalidation retains that initiating `type` and also includes its fetcher key. Fetchers reloaded after an initialization redirect likewise retain the `"initialization"` type and include their fetcher key.
|
|
86
|
+
|
|
87
|
+
`navigationType` is `"PUSH"`, `"REPLACE"`, or `"POP"` for navigation-initiated data requests, including fetchers reloaded by that navigation. It is `null` for initialization, standalone fetcher operations, and explicit revalidation. This is the history action for the in-flight navigation, not the previously committed location.
|
|
88
|
+
|
|
89
|
+
## Examples
|
|
90
|
+
|
|
91
|
+
Each example below can be passed to `HydratedRouter` as its `unstable_fetch` prop.
|
|
92
|
+
|
|
93
|
+
### Authentication and Custom Headers
|
|
94
|
+
|
|
95
|
+
Read the current token at request time so token changes don't require replacing the callback:
|
|
96
|
+
|
|
97
|
+
```ts
|
|
98
|
+
import type { unstable_RouterFetch } from "react-router/dom";
|
|
99
|
+
import { authStore } from "./auth";
|
|
100
|
+
|
|
101
|
+
const customFetch: unstable_RouterFetch = (request) => {
|
|
102
|
+
let headers = new Headers(request.headers);
|
|
103
|
+
let token = authStore.getAccessToken();
|
|
104
|
+
|
|
105
|
+
if (token) {
|
|
106
|
+
headers.set("Authorization", `Bearer ${token}`);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
headers.set("X-App-Version", "1.0");
|
|
110
|
+
return fetch(request, { headers });
|
|
111
|
+
};
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
Here, `authStore` is your application's authentication store. Only send credentials to trusted origins. Adding custom headers to cross-origin requests may require a CORS preflight and corresponding server configuration.
|
|
115
|
+
|
|
116
|
+
### Cross-Origin Credentials
|
|
117
|
+
|
|
118
|
+
In [API-only Mode](../start/framework/rendering#using-a-separate-api-origin), use `unstable_apiServerOrigin` to configure a separate API origin. React Router applies that origin before calling your custom fetch, and also uses it for native data prefetches.
|
|
119
|
+
|
|
120
|
+
The origin setting does not enable cross-origin cookies. If you need them, customize the credential policy for the trusted API origin:
|
|
121
|
+
|
|
122
|
+
```ts
|
|
123
|
+
import type { unstable_RouterFetch } from "react-router/dom";
|
|
124
|
+
|
|
125
|
+
const customFetch: unstable_RouterFetch = (request) => {
|
|
126
|
+
let isApiRequest =
|
|
127
|
+
new URL(request.url).origin ===
|
|
128
|
+
"https://api.example.com";
|
|
129
|
+
|
|
130
|
+
return fetch(request, {
|
|
131
|
+
credentials: isApiRequest
|
|
132
|
+
? "include"
|
|
133
|
+
: request.credentials,
|
|
134
|
+
});
|
|
135
|
+
};
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
The API server must allow credentialed CORS requests from your client origin. Browser cookie policies still apply. Native data prefetches do not use this callback, so don't rely on it to configure their credentials.
|
|
139
|
+
|
|
140
|
+
### Back/Forward Traversal Cache
|
|
141
|
+
|
|
142
|
+
Use `navigationType` to prefer the browser's HTTP cache when navigating back or forward, while retaining the normal cache policy for other requests:
|
|
143
|
+
|
|
144
|
+
```ts
|
|
145
|
+
import type { unstable_RouterFetch } from "react-router/dom";
|
|
146
|
+
|
|
147
|
+
const customFetch: unstable_RouterFetch = (
|
|
148
|
+
request,
|
|
149
|
+
context,
|
|
150
|
+
) => {
|
|
151
|
+
let isTraversal =
|
|
152
|
+
import.meta.env.PROD &&
|
|
153
|
+
request.method === "GET" &&
|
|
154
|
+
context.type === "navigation" &&
|
|
155
|
+
context.navigationType === "POP";
|
|
156
|
+
|
|
157
|
+
return fetch(request, {
|
|
158
|
+
cache: isTraversal ? "force-cache" : "default",
|
|
159
|
+
});
|
|
160
|
+
};
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
This example enables the policy in production only. It includes GET requests for fetchers reloaded by a back/forward navigation, but not standalone fetcher loads or explicit revalidations.
|
|
164
|
+
|
|
165
|
+
The [`force-cache` policy](https://fetch.spec.whatwg.org/#concept-request-cache-mode) uses a matching HTTP cache entry even if it is stale, falling back to the network when no entry exists. Your server's responses must be cacheable; `Cache-Control: no-store` responses aren't stored.
|
|
166
|
+
|
|
167
|
+
This is not a router-managed data cache. React Router still performs its request and response decoding, and this policy adds no mutation or authentication invalidation guarantees. Only use it when serving potentially stale data is appropriate for your application.
|
|
168
|
+
|
|
169
|
+
### Retrying Safe Requests
|
|
170
|
+
|
|
171
|
+
You can retry a safe GET after a network failure without retrying action submissions or canceled requests:
|
|
172
|
+
|
|
173
|
+
```ts
|
|
174
|
+
import type { unstable_RouterFetch } from "react-router/dom";
|
|
175
|
+
|
|
176
|
+
const customFetch: unstable_RouterFetch = async (
|
|
177
|
+
request,
|
|
178
|
+
) => {
|
|
179
|
+
if (request.method !== "GET") {
|
|
180
|
+
return fetch(request);
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
try {
|
|
184
|
+
return await fetch(request.clone());
|
|
185
|
+
} catch (error) {
|
|
186
|
+
if (
|
|
187
|
+
request.signal.aborted ||
|
|
188
|
+
(error instanceof Error &&
|
|
189
|
+
error.name === "AbortError")
|
|
190
|
+
) {
|
|
191
|
+
throw error;
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
// Retry once, retaining the original abort signal.
|
|
195
|
+
return fetch(request);
|
|
196
|
+
}
|
|
197
|
+
};
|
|
198
|
+
```
|
|
199
|
+
|
|
200
|
+
This assumes your GET endpoints are safe to repeat. It retries a rejected fetch, not HTTP error responses such as `500`. Don't automatically retry mutations: the server may have processed an action even when the client didn't receive its response.
|
|
201
|
+
|
|
202
|
+
## Limitations
|
|
203
|
+
|
|
204
|
+
### Requests Outside Custom Fetch
|
|
205
|
+
|
|
206
|
+
Custom fetch does not intercept the initial document request, server-side loader execution, static assets, or fetches you write in your own application code, including in `clientLoader`/`clientAction`. Calls to their `serverLoader`/`serverAction` helpers do use custom fetch when they issue server data requests.
|
|
207
|
+
|
|
208
|
+
Data prefetches from `<Link prefetch>`, `<NavLink prefetch>`, and [`PrefetchPageLinks`](../api/components/PrefetchPageLinks) use native `<link rel="prefetch">` elements and bypass custom fetch. If a request requires custom headers or other transformations, use `prefetch="none"` on links and avoid rendering `PrefetchPageLinks` for those routes.
|
|
209
|
+
|
|
210
|
+
### Inspecting Request Bodies
|
|
211
|
+
|
|
212
|
+
If you need a form field such as `intent` to choose request headers, read it from `await request.clone().formData()` for form-encoded submissions, then send the original request. Reading `request.formData()` directly consumes the body so it can't subsequently be sent unchanged.
|
|
213
|
+
|
|
214
|
+
Only parse bodies with a compatible encoding. Cloning and reading a body can buffer data, so avoid doing this unnecessarily, especially for large file uploads. Adding headers or changing fetch options does not require reading the body.
|
|
215
|
+
|
|
216
|
+
### Response Compatibility
|
|
217
|
+
|
|
218
|
+
Return the response from `fetch` unchanged. You can inspect its status and headers, but you should not consume its body or try to decode, modify, or re-encode it. React Router handles response decoding and expects its manifest/data protocol, including Turbo Stream-encoded loader/action data.
|
|
@@ -23,7 +23,9 @@ A custom `dataStrategy` receives the `loader`/`action` arguments (`request`, `pa
|
|
|
23
23
|
|
|
24
24
|
- `matches`: An array of `DataStrategyMatch` instances for the routes matched by the current `request`
|
|
25
25
|
- `runClientMiddleware`: A helper function to run the middleware for the matched routes
|
|
26
|
-
- `fetcherKey`: The fetcher
|
|
26
|
+
- `fetcherKey`: The key of the fetcher targeted by this execution, or `null` for route loader/action executions. Fetchers reloaded by a navigation or explicit revalidation also provide their key.
|
|
27
|
+
- `unstable_initiator`: The operation that initiated this execution (see [Request Metadata](#request-metadata-unstable))
|
|
28
|
+
- `unstable_navigationType`: The history action for a navigation-initiated execution, or `null` for other executions
|
|
27
29
|
|
|
28
30
|
A `DataStrategyMatch` is a normal route match plus a few additional fields:
|
|
29
31
|
|
|
@@ -77,6 +79,26 @@ interface DataStrategyResult {
|
|
|
77
79
|
}
|
|
78
80
|
```
|
|
79
81
|
|
|
82
|
+
### Request Metadata (unstable)
|
|
83
|
+
|
|
84
|
+
<docs-warning>`unstable_initiator` and `unstable_navigationType` are experimental and may change in minor or patch releases.</docs-warning>
|
|
85
|
+
|
|
86
|
+
`unstable_initiator` identifies why the data strategy is running:
|
|
87
|
+
|
|
88
|
+
- `"initialization"`: Initial router data loading
|
|
89
|
+
- `"navigation"`: A navigation, including action submissions and subsequent loader revalidation
|
|
90
|
+
- `"fetcher"`: A fetcher operation, including loader revalidation after a fetcher action
|
|
91
|
+
- `"revalidation"`: Explicit revalidation, such as `useRevalidator().revalidate()`
|
|
92
|
+
- `"static"`: Execution by `createStaticHandler` on the server
|
|
93
|
+
|
|
94
|
+
Requests that reload fetchers during a navigation or explicit revalidation retain that initiator while providing the targeted `fetcherKey`. Don't use `fetcherKey` alone to determine what initiated the execution.
|
|
95
|
+
|
|
96
|
+
`unstable_navigationType` is `"PUSH"`, `"REPLACE"`, or `"POP"` for navigation-initiated executions, including fetchers reloaded by that navigation. It is `null` for initialization, standalone fetcher operations, explicit revalidation, and static handler executions. It describes the in-flight navigation rather than the previously committed location.
|
|
97
|
+
|
|
98
|
+
You can use this metadata to choose a loading or caching policy. For example, a Data Mode `dataStrategy` can distinguish back/forward navigations with `unstable_initiator === "navigation" && unstable_navigationType === "POP"`. Your strategy remains responsible for executing the appropriate handlers and returning their results.
|
|
99
|
+
|
|
100
|
+
Framework Mode exposes equivalent request metadata through [`unstable_fetch`](./custom-fetch#request-context), which customizes server requests without replacing loader/action execution.
|
|
101
|
+
|
|
80
102
|
### Calling Route Middleware
|
|
81
103
|
|
|
82
104
|
If you are using `middleware` on your routes, you need to leverage the `callClientMiddleware` helper function to execute `middleware` around your handlers:
|
package/docs/how-to/fetchers.md
CHANGED
|
@@ -85,7 +85,7 @@ export default function Component() {
|
|
|
85
85
|
|
|
86
86
|
### 3. Submit the form
|
|
87
87
|
|
|
88
|
-
If you submit the form now, the fetcher will call the action and revalidate the route data automatically.
|
|
88
|
+
If you submit the form now, the fetcher will call the action and revalidate the route data automatically. See [Revalidation Optimization](./optimize-revalidation) to skip that reload for a route or a single submission.
|
|
89
89
|
|
|
90
90
|
### 4. Render pending state
|
|
91
91
|
|
|
@@ -305,3 +305,8 @@ Fetchers can be submitted programmatically with `fetcher.submit`:
|
|
|
305
305
|
```
|
|
306
306
|
|
|
307
307
|
Note the input event's form is passed as the first argument to `fetcher.submit`. The fetcher will use that form to submit the request, reading its attributes and serializing the data from its elements.
|
|
308
|
+
|
|
309
|
+
`fetcher.submit` accepts the same [`defaultShouldRevalidate`][fetcher-submit-options] option as [`<Form>`][form]. Pass `false` to skip loader revalidation for that submission. See [Revalidation Optimization](./optimize-revalidation) for how that interacts with route-level `shouldRevalidate`.
|
|
310
|
+
|
|
311
|
+
[fetcher-submit-options]: https://api.reactrouter.com/v8/interfaces/react-router.FetcherSubmitOptions.html#defaultshouldrevalidate
|
|
312
|
+
[form]: ../api/components/Form#defaultshouldrevalidate
|
|
@@ -358,7 +358,9 @@ In theory, we could have leveraged [`AsyncLocalStorage`][asynclocalstorage] dire
|
|
|
358
358
|
|
|
359
359
|
That said, this API still works great with React Router middleware and can be used in place of, or alongside of the `context` API:
|
|
360
360
|
|
|
361
|
-
<docs-info>[`AsyncLocalStorage`][asynclocalstorage] is _especially_ powerful when using [React Server Components](../how-to/react-server-components) because it allows you to provide information from `middleware` to your Server Components and
|
|
361
|
+
<docs-info>[`AsyncLocalStorage`][asynclocalstorage] is _especially_ powerful when using [React Server Components](../how-to/react-server-components) because it allows you to provide information from `middleware` to your Server Components and route actions because they run in the same server execution context 🤯</docs-info>
|
|
362
|
+
|
|
363
|
+
<docs-warning>Do not rely on route middleware to provide access control for React Server Functions. Server Functions are not inherently associated with a route, and a client can call the same Server Function through a URL with different middleware. Server Functions must perform all of their own access control checks. Use a route `action` instead when you want middleware-driven access control.</docs-warning>
|
|
362
364
|
|
|
363
365
|
```tsx filename=app/user-context.ts
|
|
364
366
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
@@ -633,6 +635,7 @@ export async function loader({
|
|
|
633
635
|
[server-client]: #server-vs-client-middleware
|
|
634
636
|
[framework-action]: ../start/framework/route-module#action
|
|
635
637
|
[framework-loader]: ../start/framework/route-module#loader
|
|
638
|
+
[getloadcontext]: ../api/other-api/adapter#react-routerexpress
|
|
636
639
|
[datastrategy]: ../api/data-routers/createBrowserRouter#optsdatastrategy
|
|
637
640
|
[cms-redirect]: #cms-redirect-on-404
|
|
638
641
|
[createContext]: ../api/utils/createContext
|