Skip to content

Commit 238ea4a

Browse files
feat: early hints (#7324)
1 parent f08ef9d commit 238ea4a

40 files changed

Lines changed: 2981 additions & 876 deletions
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
---
2+
'@tanstack/start-server-core': patch
3+
'@tanstack/react-start-server': patch
4+
'@tanstack/solid-start-server': patch
5+
'@tanstack/react-start': patch
6+
'@tanstack/solid-start': patch
7+
---
8+
9+
Add experimental HTTP 103 Early Hints support to Start server handlers.

‎docs/start/config.json‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -137,6 +137,10 @@
137137
"label": "Server Entry Point",
138138
"to": "framework/react/guide/server-entry-point"
139139
},
140+
{
141+
"label": "Early Hints",
142+
"to": "framework/react/guide/early-hints"
143+
},
140144
{
141145
"label": "CDN Asset URLs",
142146
"to": "framework/react/guide/cdn-asset-urls"
@@ -254,6 +258,10 @@
254258
"label": "Server Entry Point",
255259
"to": "framework/solid/guide/server-entry-point"
256260
},
261+
{
262+
"label": "Early Hints",
263+
"to": "framework/solid/guide/early-hints"
264+
},
257265
{
258266
"label": "Client Entry Point",
259267
"to": "framework/solid/guide/client-entry-point"
Lines changed: 266 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,266 @@
1+
---
2+
id: early-hints
3+
title: Early Hints
4+
---
5+
6+
# Early Hints
7+
8+
> **Experimental:** Early Hints are experimental and subject to change.
9+
10+
HTTP `103 Early Hints` lets a 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.
11+
12+
Early Hints are runtime-specific. Start does not send them automatically because each deployment platform exposes a different API for writing informational responses.
13+
14+
## Basic Usage
15+
16+
Add `onEarlyHints` in `src/server.ts` and send `event.links` through your runtime's Early Hints API. Browsers generally process only the first `103` response for a navigation, so write at most one Early Hints response per request.
17+
18+
```tsx
19+
// src/server.ts
20+
import handler, { createServerEntry } from '@tanstack/react-start/server-entry'
21+
22+
export default createServerEntry({
23+
fetch(request) {
24+
return handler.fetch(request, {
25+
onEarlyHints: ({ phase, links }) => {
26+
if (phase !== 'static' || !links.length) return
27+
28+
// Send `links` with your runtime-specific 103 API.
29+
},
30+
})
31+
},
32+
})
33+
```
34+
35+
Start can call `onEarlyHints` more than once for a request. `hints` and `links` only contain values that were not emitted in earlier phases of the same request. `allHints` and `allLinks` contain all deduped values collected so far. The `dynamic` phase can run with empty `hints` and `links`, so it can be used as a post-load signal.
36+
37+
For the earliest possible hints, write one `103` response during the `static` phase. For redirect-safe or loader-aware hints, wait for the `dynamic` phase and write one response with `allLinks`.
38+
39+
## Phases
40+
41+
`onEarlyHints` can run in two phases:
42+
43+
| Phase | When it runs | What it contains |
44+
| --------- | ------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------- |
45+
| `static` | After route matching, before the router loads the route | Manifest-managed assets for the matched routes |
46+
| `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 |
47+
48+
The `static` phase is the earliest useful point. It can run before route `beforeLoad` functions, so it may send hints for a request that later redirects. If you want redirect-safe hints only, send hints only when `phase === 'dynamic'`.
49+
50+
```tsx
51+
onEarlyHints: ({ phase, allLinks }) => {
52+
if (phase !== 'dynamic') return
53+
54+
// Send one redirect-safe 103 with static and dynamic links.
55+
// Use `allLinks` with your runtime-specific 103 API.
56+
}
57+
```
58+
59+
## Event Shape
60+
61+
The callback receives an `EarlyHintsEvent`:
62+
63+
```ts
64+
type EarlyHintsEvent = {
65+
phase: 'static' | 'dynamic'
66+
hints: ReadonlyArray<EarlyHint>
67+
links: Array<string>
68+
allHints: ReadonlyArray<EarlyHint>
69+
allLinks: Array<string>
70+
}
71+
```
72+
73+
`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.
74+
75+
`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.
76+
77+
## Supported Links
78+
79+
Start emits Early Hints for link relations that map cleanly to HTTP `Link` headers:
80+
81+
- `preload`
82+
- `modulepreload`
83+
- `preconnect`
84+
- `dns-prefetch`
85+
86+
Route `head().links` entries with `rel: 'stylesheet'` are converted to `rel=preload; as=style` for Early Hints.
87+
88+
Start serializes these attributes when present:
89+
90+
- `href`
91+
- `rel`
92+
- `as`
93+
- `crossOrigin`
94+
- `type`
95+
- `integrity`
96+
- `referrerPolicy`
97+
- `fetchPriority`
98+
99+
Other head tags, inline styles, route scripts, and metadata are not converted into Early Hints.
100+
HTML 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.
101+
102+
## Static Hints and `transformAssets`
103+
104+
Static Early Hints are collected from the final Start manifest resolved for the request. This means they follow the result of [`transformAssets`](./cdn-asset-urls):
105+
106+
- CDN URL rewrites are reflected in Early Hints.
107+
- `crossOrigin` returned from `transformAssets` is reflected in Early Hints.
108+
- Per-request transforms with `cache: false` are reflected in Early Hints for that request.
109+
- Inlined CSS assets are skipped when Start's inline CSS build option inlines them into the HTML.
110+
111+
## Dynamic Hints
112+
113+
Dynamic Early Hints come from route `head().links` after loaders have run:
114+
115+
```tsx
116+
export const Route = createFileRoute('/posts/$postId')({
117+
loader: async ({ params }) => getPost(params.postId),
118+
head: ({ loaderData }) => ({
119+
links: [
120+
{
121+
rel: 'preload',
122+
href: loaderData.heroImageUrl,
123+
as: 'image',
124+
},
125+
],
126+
}),
127+
})
128+
```
129+
130+
The `dynamic` phase is skipped when `router.load()` produces a redirect.
131+
132+
## Final `Link` Headers and CDNs
133+
134+
You can also attach the same serialized values to the final HTML response as HTTP `Link` headers. A final `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 somewhat earlier.
135+
136+
Final `Link` headers are also useful for CDNs that generate their own Early Hints. For example, [Cloudflare Early Hints](https://developers.cloudflare.com/cache/advanced-configuration/early-hints/) can read `Link` headers from HTML responses, cache them, and emit `103` responses for later requests.
137+
138+
Start does not add final `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.
139+
140+
Final `Link` headers are most useful when:
141+
142+
- You need a fallback for runtimes that cannot write `103` responses
143+
- Your CDN can generate Early Hints from final response `Link` headers
144+
145+
Good links to include are public and cache-stable for the response's cache boundary, such as:
146+
147+
- Static route JavaScript and CSS assets
148+
- Public font, image, style, or fetch preloads with stable URLs
149+
- Public preconnect origins
150+
151+
Avoid or filter links before they reach a shared cache or CDN when they are:
152+
153+
- Authenticated, private, or user-specific
154+
- Signed, expiring, or otherwise short-lived
155+
- Derived from cookies, headers, query strings, A/B tests, or user data, unless the cache key varies on the same inputs
156+
- Unsafe to replay before your app authorizes the request
157+
158+
Cloudflare 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.
159+
160+
Because of those cache semantics, prefer public static links for CDN-generated Early Hints. Use `allLinks` only when every dynamic `head().links` entry is public and cache-stable for the request URI.
161+
162+
This example appends static links to the final HTML response. It gives non-`103` runtimes a fallback and lets CDNs such as Cloudflare generate Early Hints from public route assets:
163+
164+
```tsx
165+
// src/server.ts
166+
import handler, { createServerEntry } from '@tanstack/react-start/server-entry'
167+
168+
export default createServerEntry({
169+
async fetch(request) {
170+
let finalLinks: Array<string> = []
171+
172+
const response = await handler.fetch(request, {
173+
onEarlyHints: ({ phase, links }) => {
174+
if (phase === 'static') {
175+
finalLinks = links
176+
}
177+
},
178+
})
179+
180+
if (
181+
!finalLinks.length ||
182+
!response.headers.get('content-type')?.includes('text/html')
183+
) {
184+
return response
185+
}
186+
187+
const headers = new Headers(response.headers)
188+
189+
for (const link of finalLinks) {
190+
headers.append('Link', link)
191+
}
192+
193+
return new Response(response.body, {
194+
status: response.status,
195+
statusText: response.statusText,
196+
headers,
197+
})
198+
},
199+
})
200+
```
201+
202+
If your dynamic links are also public and cache-stable, collect `allLinks` in the `dynamic` phase instead of `links` in the `static` phase.
203+
204+
## Runtime Example: Node
205+
206+
If your runtime exposes Node's `ServerResponse`, call `writeEarlyHints` with `links`. This example sends the earliest `static` hints:
207+
208+
```tsx
209+
// src/server.ts
210+
import handler, { createServerEntry } from '@tanstack/react-start/server-entry'
211+
import type { ServerResponse } from 'node:http'
212+
213+
export default createServerEntry({
214+
fetch(request) {
215+
return handler.fetch(request, {
216+
onEarlyHints: ({ phase, links }) => {
217+
if (phase !== 'static' || !links.length) return
218+
219+
const response = getNodeResponseSomehow(request) as
220+
| ServerResponse
221+
| undefined
222+
223+
response?.writeEarlyHints({ link: links })
224+
},
225+
})
226+
},
227+
})
228+
```
229+
230+
Replace `getNodeResponseSomehow` with the API your adapter exposes.
231+
232+
## Runtime Example: srvx / Nitro on Node
233+
234+
Nitro 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:
235+
236+
```tsx
237+
// src/server.ts
238+
import handler from '@tanstack/react-start/server-entry'
239+
import type { ServerRequest } from 'srvx'
240+
241+
export default {
242+
fetch(request: Request) {
243+
const serverRequest = request as ServerRequest
244+
245+
return handler.fetch(request, {
246+
onEarlyHints: ({ phase, allLinks }) => {
247+
if (phase !== 'dynamic') return
248+
249+
const response = serverRequest.runtime?.node?.res
250+
251+
if (response?.writeEarlyHints && allLinks.length) {
252+
response.writeEarlyHints({ link: allLinks })
253+
}
254+
},
255+
})
256+
},
257+
}
258+
```
259+
260+
## Limitations
261+
262+
- Early Hints are skipped in the Start dev server.
263+
- Start does not mutate the final response `Link` header.
264+
- Browsers generally process only the first `103` response for a navigation.
265+
- Static hints can be sent before `beforeLoad` redirects are known.
266+
- The runtime or proxy in front of your app must support HTTP `103` responses.
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
ref: docs/start/framework/react/guide/early-hints.md
3+
replace:
4+
{ '@tanstack/react-start': '@tanstack/solid-start', 'React': 'SolidJS' }
5+
---
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
# Generated certificates
2+
.tmp/
3+
*.pem
4+
*.key
5+
*.crt
6+
ca.key
7+
ca.crt
8+
cert.pem
9+
key.pem
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
{
2+
"name": "tanstack-react-start-e2e-early-hints",
3+
"private": true,
4+
"sideEffects": false,
5+
"type": "module",
6+
"scripts": {
7+
"dev": "vite dev --port 3000",
8+
"dev:e2e": "vite dev",
9+
"build": "vite build",
10+
"preview": "vite preview",
11+
"gen-certs": "node --import tsx tests/gen-certs.ts",
12+
"start": "pnpm gen-certs && srvx --prod --tls --cert=tests/.tmp/tls/server.crt --key=tests/.tmp/tls/server.key -s ../client dist/server/server.js",
13+
"test:e2e": "rm -rf port*.txt; playwright test --project=chromium"
14+
},
15+
"dependencies": {
16+
"@tanstack/react-router": "workspace:^",
17+
"@tanstack/react-start": "workspace:^",
18+
"react": "^19.0.0",
19+
"react-dom": "^19.0.0"
20+
},
21+
"devDependencies": {
22+
"@playwright/test": "^1.50.1",
23+
"@tanstack/router-e2e-utils": "workspace:^",
24+
"@types/node": "^22.10.2",
25+
"@types/node-forge": "^1.3.14",
26+
"@types/react": "^19.0.8",
27+
"@types/react-dom": "^19.0.3",
28+
"@vitejs/plugin-react": "^6.0.1",
29+
"node-forge": "^1.3.1",
30+
"srvx": "0.11.15",
31+
"tsx": "4.20.3",
32+
"typescript": "^6.0.2",
33+
"vite": "^8.0.0"
34+
}
35+
}
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
import { defineConfig, devices } from '@playwright/test'
2+
import { getTestServerPort } from '@tanstack/router-e2e-utils'
3+
import packageJson from './package.json' with { type: 'json' }
4+
5+
const PORT = await getTestServerPort(packageJson.name)
6+
const baseURL = `https://localhost:${PORT}`
7+
8+
export default defineConfig({
9+
testDir: './tests',
10+
workers: 1,
11+
reporter: [['line']],
12+
13+
use: {
14+
baseURL,
15+
ignoreHTTPSErrors: true,
16+
},
17+
18+
webServer: {
19+
command: `pnpm build && pnpm start`,
20+
url: baseURL,
21+
reuseExistingServer: !process.env.CI,
22+
stdout: 'pipe',
23+
ignoreHTTPSErrors: true,
24+
env: {
25+
PORT: String(PORT),
26+
},
27+
},
28+
29+
projects: [
30+
{
31+
name: 'chromium',
32+
use: {
33+
...devices['Desktop Chrome'],
34+
},
35+
},
36+
],
37+
})

0 commit comments

Comments
 (0)