Open History to see the last commit
1'use client'
2β
3import { environmentManager } from '@tanstack/react-query'
4import { useServerInsertedHTML } from 'next/navigation'
5import * as React from 'react'
6import { htmlEscapeJsonString } from './htmlescape'
7β
8const serializedSymbol = Symbol('serialized')
9β
10interface DataTransformer {
11 serialize: (object: any) => any
12 deserialize: (object: any) => any
13}
14β
15type Serialized<TData> = unknown & {
16 [serializedSymbol]: TData
17}
18β
19interface TypedDataTransformer<TData> {
20 serialize: (obj: TData) => Serialized<TData>
21 deserialize: (obj: Serialized<TData>) => TData
22}
23β
24interface HydrationStreamContext<TShape> {
25 id: string
26 stream: {
27 /**
28 * **Server method** Push a new entry to the stream Will be ignored on the
29 * client
30 */
31 push: (...shape: Array<TShape>) => void
32 }
33}
34β
35/** The props of the `Provider` returned by `createHydrationStreamProvider`. */
36export interface HydrationStreamProviderProps<TShape> {
37 /** The children to render inside the stream provider. */
38 children: React.ReactNode
39 /**
40 * Optional transformer to serialize/deserialize the data Example devalue,
41 * superjson et al
42 */
43 transformer?: DataTransformer
44 /** **Client method** Called in the browser when new entries are received */
45 onEntries: (entries: Array<TShape>) => void
46 /** **Server method** onFlush is called on the server when the cache is flushed */
47 onFlush?: () => Array<TShape>
48 /**
49 * A nonce that'll allow the inline script to be executed when Content
50 * Security Policy is enforced
51 */
52 nonce?: string
53}
54β
55/**
56 * Creates a provider that streams entries (e.g. dehydrated query state) from
57 * the server to the client while the page streams in, and the context it shares
58 * the stream through.
59 *
60 * @returns The `Provider` component and its `context`.
61 */
62export function createHydrationStreamProvider<TShape>() {
63 const StreamContext = React.createContext<HydrationStreamContext<TShape>>(
64 null as any,
65 )
66 /**
67 * 1. (Happens on server): the callback registered with `useServerInsertedHTML()`
68 * is called **on the server** whenever Next.js inserts HTML into the
69 * streamed response.
70 *
71 * - This means that we might have some new entries in the cache that needs to
72 * be flushed.
73 * - We pass these to the client by inserting a `<script>`-tag where we do
74 * `window[id].push(serializedVersionOfCache)`.
75 * 2. (Happens in browser) In `useEffect()`:
76 *
77 * - We check if `window[id]` is set to an array and call `push()` on all the
78 * entries which will call `onEntries()` with the new entries.
79 * - We replace `window[id]` with a `push()`-method that will be called whenever
80 * new entries are received.
81 *
82 * @param props - The `children` to render, the `onEntries`/`onFlush`
83 * callbacks, and the optional `transformer` and `nonce`.
84 * @returns The `children`, wrapped in the stream context provider.
85 */
86 function UseClientHydrationStreamProvider(props: {
87 children: React.ReactNode
88 /**
89 * Optional transformer to serialize/deserialize the data Example devalue,
90 * superjson et al
91 */
92 transformer?: DataTransformer
93 /** **Client method** Called in the browser when new entries are received */
94 onEntries: (entries: Array<TShape>) => void
95 /**
96 * **Server method** onFlush is called on the server when the cache is
97 * flushed
98 */
99 onFlush?: () => Array<TShape>
100 /**
101 * A nonce that'll allow the inline script to be executed when Content
102 * Security Policy is enforced
103 */
104 nonce?: string
105 }) {
106 // unique id for the cache provider
107 const id = `__RQ${React.useId()}`
108 const idJSON = htmlEscapeJsonString(JSON.stringify(id))
109β
110 const [transformer] = React.useState(
111 () =>
112 (props.transformer ?? {
113 // noop
114 serialize: (obj: any) => obj,
115 deserialize: (obj: any) => obj,
116 }) as unknown as TypedDataTransformer<TShape>,
117 )
118β
119 // <server stuff>
120 const [stream] = React.useState<Array<TShape>>(() => {
121 if (!environmentManager.isServer()) {
122 return {
123 push() {
124 // no-op on the client
125 },
126 } as unknown as Array<TShape>
127 }
128 return []
129 })
130 const countRef = React.useRef(0)
131 useServerInsertedHTML(() => {
132 // This only happens on the server
133 stream.push(...(props.onFlush?.() ?? []))
134β
135 if (!stream.length) {
136 return null
137 }
138 // console.log(`pushing ${stream.length} entries`)
139 const serializedCacheArgs = stream
140 .map((entry) => transformer.serialize(entry))
141 .map((entry) => JSON.stringify(entry))
142 .join(',')
143β
144 // Flush stream
145 stream.length = 0
146β
147 const html: Array<string> = [
148 `window[${idJSON}] = window[${idJSON}] || [];`,
149 `window[${idJSON}].push(${htmlEscapeJsonString(serializedCacheArgs)});`,
150 ]
151 return (
152 <script
153 key={countRef.current++}
154 nonce={props.nonce}
155 dangerouslySetInnerHTML={{
156 __html: html.join(''),
157 }}
158 />
159 )
160 })
161 // </server stuff>
162β
163 // <client stuff>
164 // Setup and run the onEntries handler on the client only, but do it during
165 // the initial render so children have access to the data immediately
166 // This is important to avoid the client suspending during the initial render
167 // if the data has not yet been hydrated.
168 if (!environmentManager.isServer()) {
169 const win = window as any
170 if (!win[id]?.initialized) {
171 // Client: consume cache:
172 const onEntries = (...serializedEntries: Array<Serialized<TShape>>) => {
173 const entries = serializedEntries.map((serialized) =>
174 transformer.deserialize(serialized),
175 )
176 props.onEntries(entries)
177 }
178β
179 const winStream: Array<Serialized<TShape>> = win[id] ?? []
180β
181 onEntries(...winStream)
182β
183 win[id] = {
184 initialized: true,
185 push: onEntries,
186 }
187 }
188 }
189 // </client stuff>
190β
191 return (
192 <StreamContext.Provider value={{ stream, id }}>
193 {props.children}
194 </StreamContext.Provider>
195 )
196 }
197β
198 return {
199 Provider: UseClientHydrationStreamProvider,
200 context: StreamContext,
201 }
202}