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