|
| 1 | +--- |
| 2 | +title: Streaming |
| 3 | +description: Update head tags dynamically during streaming server-side rendering |
| 4 | +navigation.title: Streaming |
| 5 | +new: true |
| 6 | +--- |
| 7 | + |
| 8 | +::warning |
| 9 | +This API is experimental and may change in future versions. |
| 10 | +:: |
| 11 | + |
| 12 | +Streaming sends HTML progressively. With Unhead's streaming support, head tags update as async content resolves. |
| 13 | + |
| 14 | +## Server |
| 15 | + |
| 16 | +```ts |
| 17 | +import { createStreamableHead, wrapStream } from 'unhead/stream/server' |
| 18 | + |
| 19 | +const { head } = createStreamableHead() |
| 20 | + |
| 21 | +head.push({ |
| 22 | + title: 'My App', |
| 23 | + htmlAttrs: { lang: 'en' } |
| 24 | +}) |
| 25 | + |
| 26 | +const template = '<!DOCTYPE html><html><head></head><body></body></html>' |
| 27 | + |
| 28 | +// Wrap your app stream with head injection |
| 29 | +const fullStream = wrapStream(head, appStream, template) |
| 30 | +return new Response(fullStream) |
| 31 | +``` |
| 32 | + |
| 33 | +## Client |
| 34 | + |
| 35 | +```ts |
| 36 | +import { createStreamableHead } from 'unhead/stream/client' |
| 37 | + |
| 38 | +const head = createStreamableHead() |
| 39 | +``` |
| 40 | + |
| 41 | +The client automatically processes queued entries from streaming. |
| 42 | + |
| 43 | +## API |
| 44 | + |
| 45 | +### createStreamableHead |
| 46 | + |
| 47 | +```ts |
| 48 | +import { createStreamableHead } from 'unhead/stream/server' |
| 49 | + |
| 50 | +function createStreamableHead(options?: { |
| 51 | + streamKey?: string |
| 52 | +}): { |
| 53 | + head: Unhead |
| 54 | + wrapStream: (stream: ReadableStream, template: string) => ReadableStream |
| 55 | +} |
| 56 | +``` |
| 57 | + |
| 58 | +### wrapStream |
| 59 | + |
| 60 | +```ts |
| 61 | +import { wrapStream } from 'unhead/stream/server' |
| 62 | + |
| 63 | +function wrapStream( |
| 64 | + head: Unhead, |
| 65 | + stream: ReadableStream<Uint8Array>, |
| 66 | + template: string |
| 67 | +): ReadableStream<Uint8Array> |
| 68 | +``` |
| 69 | + |
| 70 | +Wraps a stream with shell rendering and template injection. |
| 71 | + |
| 72 | +### renderSSRHeadShell / renderSSRHeadSuspenseChunk |
| 73 | + |
| 74 | +For manual control without `wrapStream`: |
| 75 | + |
| 76 | +```ts |
| 77 | +import { renderSSRHeadShell, renderSSRHeadSuspenseChunk } from 'unhead/stream/server' |
| 78 | +
|
| 79 | +// Render initial shell |
| 80 | +res.write(renderSSRHeadShell(head, template)) |
| 81 | +
|
| 82 | +// After each async chunk, emit head updates |
| 83 | +for await (const chunk of appStream) { |
| 84 | + res.write(chunk) |
| 85 | + const update = renderSSRHeadSuspenseChunk(head) |
| 86 | + if (update) res.write(`<script>${update}</script>`) |
| 87 | +} |
| 88 | +
|
| 89 | +res.write('</body></html>') |
| 90 | +``` |
0 commit comments