Skip to content
Source
Sign inSign up
TanStack/router
Open History to see the last commit

early-hints.md

285 lines11.5 KB

1---
2id: early-hints
3title: Early Hints
4---
5​
6> **Experimental:** Early Hints are experimental and subject to change.
7​
8HTTP `103 Early Hints` lets your server tell the browser about important resources before the final HTML response is ready. TanStack Start can collect route assets and route `head().links`, then call your server entry so your runtime can send `103` responses.
9​
10Start does not send Early Hints automatically. Each deployment platform exposes a different API for writing informational responses, so your server entry decides how to send them.
11​
12## Choose How to Send Hints
13​
14Most apps should choose one of these patterns.
15​
16| Goal | Use | Tradeoff |
17| --------------------------------- | ----------------------------------------------- | ------------------------------------------- |
18| Send hints as early as possible | `phase === 'static'` with `links` | May send hints for a request that redirects |
19| Send only redirect-safe hints | `phase === 'dynamic'` with `allLinks` | Runs later, after route loading completes |
20| Let a CDN generate Early Hints | `responseLinkHeader` | Only safe for public, cache-stable links |
21| Support runtimes without HTTP 103 | `responseLinkHeader` as a preload hint fallback | Does not hide server think time like `103` |
22​
23Browsers generally process only the first `103` response for a navigation. Write at most one Early Hints response per request.
24​
25## Send Early Hints From Your Server Entry
26​
27Add `onEarlyHints` in `src/server.ts`, then pass the serialized `links` to your runtime's Early Hints API.
28​
29This example sends the earliest static hints:
30​
31```tsx
32// src/server.ts
33import handler, { createServerEntry } from '@tanstack/react-start/server-entry'
34​
35export default createServerEntry({
36 fetch(request) {
37 return handler.fetch(request, {
38 onEarlyHints: ({ phase, links }) => {
39 if (phase !== 'static' || !links.length) return
40​
41 // Send `links` with your runtime-specific 103 API.
42 },
43 })
44 },
45})
46```
47​
48Start can call `onEarlyHints` more than once for a request. `links` only contains values that were not emitted in an earlier phase. `allLinks` contains all deduped values collected so far.
49​
50## Choose When to Send Hints
51​
52`onEarlyHints` can run in two phases.
53​
54| Phase | When it runs | What it contains |
55| --------- | ------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------- |
56| `static` | After route matching, before the router loads the route | Manifest-managed assets for the matched routes |
57| `dynamic` | After `router.load()` completes, unless the request redirects | Supported links returned by route `head()` functions, or an empty array when all hints were already emitted |
58​
59Use `static` when you want the browser to start loading known route assets as soon as possible. Static hints can run before route `beforeLoad` functions, so they may be sent for a request that later redirects.
60​
61Use `dynamic` when hints must be redirect-safe or loader-aware. If you want one `103` response that includes both static route assets and dynamic route `head()` links, wait for `dynamic` and send `allLinks`.
62​
63```tsx
64onEarlyHints: ({ phase, allLinks }) => {
65 if (phase !== 'dynamic' || !allLinks.length) return
66​
67 // Send one redirect-safe 103 with static and dynamic links.
68 // Use `allLinks` with your runtime-specific 103 API.
70```
71​
72The `dynamic` phase can run with empty `links`, so it can also be used as a post-load signal.
73​
74## Add Dynamic Hints From Route Head
75​
76Dynamic Early Hints come from supported route `head().links` entries after loaders have run.
77​
78```tsx
79import { createFileRoute } from '@tanstack/react-router'
80​
81export const Route = createFileRoute('/posts/$postId')({
82 loader: async ({ params }) => getPost(params.postId),
83 head: ({ loaderData }) => ({
84 links: [
85 {
86 rel: 'preload',
87 href: loaderData.heroImageUrl,
88 as: 'image',
89 },
90 ],
91 }),
92})
93```
94​
95The `dynamic` phase is skipped when `router.load()` produces a redirect.
96​
97Route `head().links` entries with `rel: 'stylesheet'` are converted to `rel=preload; as=style` for Early Hints. This includes stylesheets you import with `?url` and return from route `head()`. See [CSS Styling](./css-styling#know-when-css-is-discovered) for how CSS import patterns affect when Start discovers stylesheets.
98​
99## Use Response Link Headers as a Fallback
100​
101You can also attach collected hints to the final HTML response's HTTP `Link` header.
102​
103A response `Link` header does not hide server think time like a `103` response does, but the browser receives it before parsing the HTML body, so it can still start supported preloads and preconnects earlier than it would from HTML alone.
104​
105Response `Link` headers are most useful when:
106​
107- Your runtime cannot write `103` responses.
108- Your CDN can generate Early Hints from response `Link` headers.
109​
110Start does not add response `Link` headers automatically. It cannot know whether those headers will be used only by the browser for the current response, stored by a shared cache, or replayed later as CDN-generated Early Hints.
111​
112This example appends all collected static and dynamic links to non-redirect HTML responses:
113​
114```tsx
115// src/server.ts
116import handler, { createServerEntry } from '@tanstack/react-start/server-entry'
117​
118export default createServerEntry({
119 fetch(request) {
120 return handler.fetch(request, {
121 responseLinkHeader: true,
122 })
123 },
124})
125```
126​
127## Filter Links Before Sending Them to a CDN
128​
129Some CDNs can read response `Link` headers, cache them, and emit their own `103` responses for later requests. For example, [Cloudflare Early Hints](https://developers.cloudflare.com/cache/advanced-configuration/early-hints/) can use `Link` headers from HTML responses.
130​
131Only let a shared cache or CDN replay links that are public and cache-stable for the response's cache boundary.
132​
133Good links to include are:
134​
135- Static route JavaScript and CSS assets.
136- Public font, image, style, or fetch preloads with stable URLs.
137- Public preconnect origins.
138​
139Avoid or filter links when they are:
140​
141- Authenticated, private, or user-specific.
142- Signed, expiring, or otherwise short-lived.
143- Derived from cookies, headers, query strings, A/B tests, or user data, unless the cache key varies on the same inputs.
144- Unsafe to replay before your app authorizes the request.
145​
146Cloudflare documents several important caveats: its Early Hints cache ignores query strings, it can emit cached hints before reaching your origin or Worker, and it only generates hints from selected final response status codes and `Link` relations.
147​
148Because of those cache semantics, use response `Link` headers only when every emitted static or dynamic link is public and cache-stable for the request URI. Use `responseLinkHeader.filter` to remove links that are not safe for your cache boundary.
149​
150For example, this keeps only static manifest assets:
151​
152```tsx
153handler.fetch(request, {
154 responseLinkHeader: {
155 filter: ({ phase }) => phase === 'static',
156 },
157})
158```
159​
160## How CDN Asset Rewrites Affect Hints
161​
162Static Early Hints are collected from the final Start manifest resolved for the request. This means they follow the result of [`transformAssets`](./cdn-asset-urls):
163​
164- CDN URL rewrites are reflected in Early Hints.
165- `crossOrigin` returned from `transformAssets` is reflected in Early Hints.
166- JavaScript hints follow the client output format: `modulepreload` for module output, or `preload; as=script` for IIFE output.
167- JavaScript hints carry `fetchpriority=low`, matching the generated HTML preload links, so they don't compete with render-blocking stylesheets.
168- Per-request transforms with `cache: false` are reflected in Early Hints for that request.
169- Inlined CSS assets are skipped when Start's [CSS inlining](./css-styling#inline-route-css-in-production) build option inlines them into the HTML.
170​
171## Event Shape
172​
173The callback receives an `EarlyHintsEvent`:
174​
175```ts
176type EarlyHintsEvent = {
177 phase: 'static' | 'dynamic'
178 hints: ReadonlyArray<EarlyHint>
179 links: Array<string>
180 allHints: ReadonlyArray<EarlyHint>
181 allLinks: Array<string>
183```
184​
185`hints` is the structured form for the current phase. `links` is the serialized HTTP `Link` header form for the current phase. Both are deduped across phases, contain only new values, and are index-aligned.
186​
187`allHints` and `allLinks` contain all deduped values collected so far for the request. They are also index-aligned, and are useful when you want to write one combined `103` response during the `dynamic` phase.
188​
189The `responseLinkHeader.filter` callback receives entries with this shape:
190​
191```ts
192type ResponseLinkHeaderEntry = {
193 phase: 'static' | 'dynamic'
194 hint: EarlyHint
195 link: string
197```
198​
199## Supported Links
200​
201Start emits Early Hints for link relations that map cleanly to HTTP `Link` headers:
202​
203- `preload`
204- `modulepreload`
205- `preconnect`
206- `dns-prefetch`
207​
208Start serializes these attributes when present:
209​
210- `href`
211- `rel`
212- `as`
213- `crossOrigin`
214- `type`
215- `integrity`
216- `referrerPolicy`
217- `fetchPriority`
218​
219Other head tags, inline styles, route scripts, and metadata are not converted into Early Hints.
220​
221HTML Early Hints processing does not apply `media`, `imageSrcSet`, or `imageSizes` until the final document exists, so Start does not serialize those attributes into `103` links.
222​
223## Runtime Example: Node
224​
225If your runtime exposes Node's `ServerResponse`, call `writeEarlyHints` with `links`. This example sends the earliest `static` hints:
226​
227```tsx
228// src/server.ts
229import handler, { createServerEntry } from '@tanstack/react-start/server-entry'
230import type { ServerResponse } from 'node:http'
231​
232export default createServerEntry({
233 fetch(request) {
234 return handler.fetch(request, {
235 onEarlyHints: ({ phase, links }) => {
236 if (phase !== 'static' || !links.length) return
237​
238 const response = getNodeResponseSomehow(request) as
239 | ServerResponse
240 | undefined
241​
242 response?.writeEarlyHints({ link: links })
243 },
244 })
245 },
246})
247```
248​
249Replace `getNodeResponseSomehow` with the API your adapter exposes.
250​
251## Runtime Example: srvx / Nitro on Node
252​
253Nitro uses [srvx](https://srvx.h3.dev/) under the hood for Node deployments. srvx exposes the native Node response on the request runtime context. This example waits for `dynamic` to send one redirect-safe response with both static and dynamic links:
254​
255```tsx
256// src/server.ts
257import handler from '@tanstack/react-start/server-entry'
258import type { ServerRequest } from 'srvx'
259​
260export default {
261 fetch(request: Request) {
262 const serverRequest = request as ServerRequest
263​
264 return handler.fetch(request, {
265 onEarlyHints: ({ phase, allLinks }) => {
266 if (phase !== 'dynamic') return
267​
268 const response = serverRequest.runtime?.node?.res
269​
270 if (response?.writeEarlyHints && allLinks.length) {
271 response.writeEarlyHints({ link: allLinks })
272 }
273 },
274 })
275 },
277```
278​
279## Limitations
280​
281- Early Hints are skipped in the Start dev server.
282- Start only mutates the response `Link` header when `responseLinkHeader` is enabled.
283- Browsers generally process only the first `103` response for a navigation.
284- Static hints can be sent before `beforeLoad` redirects are known.
285- The runtime or proxy in front of your app must support HTTP `103` responses.