diff --git a/docs/framework/react/api/router/RouterType.md b/docs/framework/react/api/router/RouterType.md index 1b2b9b83ed..6cea3e5092 100644 --- a/docs/framework/react/api/router/RouterType.md +++ b/docs/framework/react/api/router/RouterType.md @@ -171,48 +171,6 @@ Matches a pathname and search params against the router's route tree and returns - A route match object if a match was found. - `false` if no match was found. -### `.injectHtml` method - -Injects the HTML for the router into the DOM. - -- Type: `(html: string | (() => Promise | string)) => void` -- Properties - - `html` - - Type: `string | (() => Promise | string)` - - Required - - The HTML to inject into the DOM. - - If a function is provided, it will be called and the resolved value will be injected into the DOM. - -### `.dehydrateData` method - -Dehydrates data into the router on the server that can be streamed to the client and rehydrated later. - -- Type: `(key: any, getData: T | (() => Promise | T)) => () => void` -- Properties - - `key` - - Type: `any` - - Required - - The key that will be used to identify the dehydrated data. - - `getData` - - Type: `T | (() => Promise | T)` - - Required - - The data that will be dehydrated. - - If a function is provided, it will be called and the resolved value will be dehydrated. - -### `.hydrateData` method - -Hydrates data into the router on the client that was dehydrated on the server. - -- Type: `(key: any) => T | undefined` -- Properties - - `key` - - Type: `any` - - Required - - The key that was used to identify the dehydrated data. -- Returns - - The dehydrated data if it exists. - - `undefined` if the dehydrated data does not exist. - ### `.dehydrate` method Dehydrates the router's critical state into a serializable object that can be sent to the client in an initial request. diff --git a/docs/framework/react/guide/deferred-data-loading.md b/docs/framework/react/guide/deferred-data-loading.md index 052cc0d9b2..3022991b9d 100644 --- a/docs/framework/react/guide/deferred-data-loading.md +++ b/docs/framework/react/guide/deferred-data-loading.md @@ -93,7 +93,7 @@ The following is a high-level overview of how deferred data streaming works with - The client receives the initial html from the server - `` components suspend with placeholder promises while they wait for their data to resolve on the server - Server - - As deferred promises resolve, their results (or errors) are serialized and streamed to the client (via Router's `router.dehydrateData()` and `router.hydrateData()` methods) + - As deferred promises resolve, their results (or errors) are serialized and streamed to the client via an inline script tag - The resolved `` components and their suspense boundaries are resolved and their resulting HTML is streamed to the client along with their dehydrated data - Client - The suspended placeholder promises within `` are resolved with the streamed data/error responses and either render the result or throw the error to the nearest error boundary diff --git a/docs/framework/react/guide/external-data-loading.md b/docs/framework/react/guide/external-data-loading.md index 3e079c7c30..bb61eb4598 100644 --- a/docs/framework/react/guide/external-data-loading.md +++ b/docs/framework/react/guide/external-data-loading.md @@ -189,121 +189,3 @@ export function createRouter() { }) } ``` - -### 3rd Party Streaming with `transformStreamWithRouter` - -- The `router.injectHtml` function - - e.g. `router.injectHtml(() => '')` - - This function can be called multiple times during rendering to inject arbitrary HTML markup into the stream. - - Use it to inject things like `') - return null -} -``` - -### Dehydrating and Hydrating Deferred Data - -Injecting HTML is pretty low-level, so let's use the `router.dehydrateData` and `router.hydrateData` functions to inject and retrieve some JSON data instead. - -```tsx -function Custom() { - return ( - Loading...}> - - - ) -} - -let testCache: string - -function Test() { - const router = useRouter() - - // Attempt to rehydrate our data on the client - // On the server, this is a no=op and - // will return undefined - const data = router.hydrateData('testCache') - - // Suspend and load our fake data - if (!testCache) { - throw new Promise((resolve) => { - setTimeout(() => { - testCache = Date.now() - resolve() - }, 1000) - }) - } - - // Dehydrate our data on the server so it can - // be rehydrated on the client - router.dehydrateData('testCache', testCache) - - return data -} -``` - -### Providing Dehydration/Hydration utilities to external tools - -The `router.dehydrateData` and `router.hydrateData` functions are designed to be used by external tools to dehydrate and hydrate data. For example, imagine an external data fetching library called `cool-cache` (not real) that allows for custom hydration and dehydration functions to be provided. We could use the `router.dehydrateData` and `router.hydrateData` functions to provide hydration and dehydration capabilities to `cool-cache`: - -```tsx -// src/router.tsx - -export function createRouter() { - const coolCache = createCoolCache() - - const router = createRouter({ - ... - }) - - coolCache.setHydrationFn((coolCacheEntry) => - router.hydrateData(coolCacheEntry.hashedKey)) - - coolCache.setDehydrationFn((coolCacheEntry) => - router.dehydrateData(coolCacheEntry.hashedKey, () => coolCacheEntry)) - - return router -} -``` - -This would allow `cool-cache` to be used with TanStack Router and have its data automatically hydrated and dehydrated with no extra work. - -```tsx -// src/components/MyComponent.tsx - -import * as React from 'react' - -const coolCacheFetcher = createCoolCacheFetcher({ - key: 'todos', - fetchFn: () => fetchTodos(), -}) - -export function Test() { - // On the client, hydration would happen before `useCoolCacheFetcher` returns the data - const data = useCoolCacheFetcher(coolCacheFetcher) - // On the server, dehydration would happen after `useCoolCacheFetcher` is able to resolve the data - - return <>... -} -``` diff --git a/docs/framework/react/guide/ssr.md b/docs/framework/react/guide/ssr.md index 6714758c3f..d7bd35fc1d 100644 --- a/docs/framework/react/guide/ssr.md +++ b/docs/framework/react/guide/ssr.md @@ -221,56 +221,11 @@ Streaming SSR is the most modern flavor of SSR and is the process of continuousl This pattern can be useful for pages that have slow or high-latency data fetching requirements. For example, if you have a page that needs to fetch data from a third-party API, you can stream the critical initial markup and data to the client and then stream the less-critical third-party data to the client as it is resolved. -To enable this streaming pattern with TanStack Router, you will need to use React's `renderToPipeableStream` function to render your application to a readable stream. This function returns a stream that can be piped to the response. Here's the utility information: +**This streaming pattern is all automatic as long as you are using `renderToPipeableStream`**. -- `transformStreamWithRouter` from `@tanstack/start` - - e.g. `transformStreamWithRouter(router)` - - This function returns a stream Transform instance that can be used to transform a stream of HTML markup from React DOM's `renderToPipeableStream` function as it is piped to the response. - - This transform automatically and incrementally embeds fine-grained HTML injections and dehydrated data chunks into the stream. +## Streaming Dehydration/Hydration -### Transforming the Stream - -Let's implement the `transformStreamWithRouter` function from `@tanstack/start` to transform the stream of HTML markup from React DOM's `renderToPipeableStream` function as it is piped to the response. - -```tsx -// Render the app to a readable stream -let stream!: PipeableStream - -await new Promise((resolve) => { - stream = ReactDOMServer.renderToPipeableStream( - , - { - [callbackName]: () => { - res.statusCode = didError ? 500 : 200 - res.setHeader('Content-Type', 'text/html') - resolve() - }, - onError: (err) => { - didError = true - console.log(err) - }, - }, - ) -}) - -if (router.hasNotFoundMatch() && res.statusCode !== 500) { - res.statusCode = 404 -} - -// Add our Router transform to the stream -const transforms = [transformStreamWithRouter(router)] - -// Pipe the stream through our transforms -const transformedStream = transforms.reduce( - (stream, transform) => stream.pipe(transform as any), - stream, -) - -// Pipe the transformed stream to the response -transformedStream.pipe(res) -``` - -With `renderToPipeableStream` and `transformStreamWithRouter`, TanStack Router is now configured to stream data to the client as it is rendered on the server! +Streaming dehydration/hydration is an advanced pattern that goes beyond markup and allows you to dehydrate and stream any supporting data from the server to the client and rehydrate it on arrival. This is useful for applications that may need to further use/manage the underlying data that was used to render the initial markup on the server. ## Data Transformers diff --git a/examples/react/basic-ssr-streaming-file-based/src/entry-server.tsx b/examples/react/basic-ssr-streaming-file-based/src/entry-server.tsx index 6893cc75e0..95c6d85774 100644 --- a/examples/react/basic-ssr-streaming-file-based/src/entry-server.tsx +++ b/examples/react/basic-ssr-streaming-file-based/src/entry-server.tsx @@ -1,14 +1,14 @@ -import * as React from 'react' -import ReactDOMServer, { PipeableStream } from 'react-dom/server' -import { createMemoryHistory } from '@tanstack/react-router' -import { StartServer, transformStreamWithRouter } from '@tanstack/start/server' +import { PassThrough } from 'stream' +import { StartServer } from '@tanstack/start/server' import { isbot } from 'isbot' -import { ServerResponse } from 'http' -import express from 'express' +import { renderToPipeableStream } from 'react-dom/server' +import { createMemoryHistory } from '@tanstack/react-router' +import { createRouter } from './router' +import type express from 'express' +import type { ServerResponse } from 'http' // index.js import './fetch-polyfill' -import { createRouter } from './router' type ReactReadableStream = ReadableStream & { allReady?: Promise | undefined @@ -38,44 +38,30 @@ export async function render(opts: { // (streamed data will continue to load in the background) await router.load() - // Track errors - let statusCode = 200 + const passthrough = new PassThrough() - // Clever way to get the right callback. Thanks Remix! - const callbackName = isbot(opts.req.headers['user-agent']) - ? 'onAllReady' - : 'onShellReady' - - // Render the app to a readable stream - let stream!: PipeableStream - - await new Promise((resolve) => { - stream = ReactDOMServer.renderToPipeableStream( - , - { - [callbackName]: () => { - resolve() - }, - onError: (err) => { - statusCode = 500 - console.log(err) - }, - }, - ) + const pipeable = renderToPipeableStream(, { + ...(isbot(opts.req.headers['user-agent']) + ? { + onAllReady() { + pipeable.pipe(passthrough) + }, + } + : { + onShellReady() { + pipeable.pipe(passthrough) + }, + }), + onShellError(err) { + throw err + }, }) - if (router.hasNotFoundMatch() && statusCode !== 500) statusCode = 404 - - opts.res.statusCode = statusCode opts.res.setHeader('Content-Type', 'text/html') + opts.res.statusCode = router.state.statusCode + opts.res.statusMessage = `${router.state.statusCode}`.startsWith('5') + ? 'Internal Server Error' + : 'OK' - // Add our Router transform to the stream - const transforms = [transformStreamWithRouter(router)] - - const transformedStream = transforms.reduce( - (stream, transform) => stream.pipe(transform as any), - stream, - ) - - transformedStream.pipe(opts.res) + pipeable.pipe(opts.res) } diff --git a/examples/react/wip-with-bling/src/entry-server.tsx b/examples/react/wip-with-bling/src/entry-server.tsx index 323add50ea..2e0f32b1ec 100644 --- a/examples/react/wip-with-bling/src/entry-server.tsx +++ b/examples/react/wip-with-bling/src/entry-server.tsx @@ -1,14 +1,13 @@ +import { PassThrough } from 'stream' import * as React from 'react' -import ReactDOMServer, { PipeableStream } from 'react-dom/server' +import { renderToPipeableStream } from 'react-dom/server' import { createMemoryHistory } from '@tanstack/react-router' -import { StartServer, transformStreamWithRouter } from '@tanstack/start/server' +import { StartServer } from '@tanstack/start/server' import { isbot } from 'isbot' -import { ServerResponse } from 'http' -import express from 'express' - -// index.js -import './fetch-polyfill' import { createRouter } from './router' +import type { ServerResponse } from 'http' +import type express from 'express' +import './fetch-polyfill' type ReactReadableStream = ReadableStream & { allReady?: Promise | undefined @@ -38,41 +37,30 @@ export async function render(opts: { // (streamed data will continue to load in the background) await router.load() - // Track errors - let didError = false + const passthrough = new PassThrough() - // Clever way to get the right callback. Thanks Remix! - const callbackName = isbot(opts.req.headers['user-agent']) - ? 'onAllReady' - : 'onShellReady' - - // Render the app to a readable stream - let stream!: PipeableStream - - await new Promise((resolve) => { - stream = ReactDOMServer.renderToPipeableStream( - , - { - [callbackName]: () => { - opts.res.statusCode = didError ? 500 : 200 - opts.res.setHeader('Content-Type', 'text/html') - resolve() - }, - onError: (err) => { - didError = true - console.log(err) - }, - }, - ) + const pipeable = renderToPipeableStream(, { + ...(isbot(opts.req.headers['user-agent']) + ? { + onAllReady() { + pipeable.pipe(passthrough) + }, + } + : { + onShellReady() { + pipeable.pipe(passthrough) + }, + }), + onShellError(err) { + throw err + }, }) - // Add our Router transform to the stream - const transforms = [transformStreamWithRouter(router)] + opts.res.setHeader('Content-Type', 'text/html') + opts.res.statusCode = router.state.statusCode + opts.res.statusMessage = `${router.state.statusCode}`.startsWith('5') + ? 'Internal Server Error' + : 'OK' - const transformedStream = transforms.reduce( - (stream, transform) => stream.pipe(transform as any), - stream, - ) - - transformedStream.pipe(opts.res) + pipeable.pipe(opts.res) } diff --git a/packages/react-router/src/awaited.tsx b/packages/react-router/src/awaited.tsx index dbd1458a00..de94c6fd16 100644 --- a/packages/react-router/src/awaited.tsx +++ b/packages/react-router/src/awaited.tsx @@ -116,8 +116,7 @@ function AwaitInner( if (window.__TSR__ROUTER__) { let deferred = window.__TSR__ROUTER__.getDeferred('${state.uid}'); if (deferred) deferred.resolve(window.__TSR__DEFERRED__${state.uid}); - } - document.querySelectorAll('.tsr-script-once').forEach((el) => el.parentElement.removeChild(el));`} + }`} /> ) : null} {props.children(data)} @@ -125,7 +124,7 @@ function AwaitInner( ) } -function ScriptOnce({ +export function ScriptOnce({ className, children, ...rest @@ -135,7 +134,10 @@ function ScriptOnce({ {...rest} className={`tsr-script-once ${className || ''}`} dangerouslySetInnerHTML={{ - __html: children, + __html: [ + children, + `document.querySelectorAll('.tsr-script-once').forEach((el) => el.parentElement.removeChild(el));`, + ].join('\n'), }} /> ) diff --git a/packages/react-router/src/index.tsx b/packages/react-router/src/index.tsx index 3a72831ccf..6e5e5c24d0 100644 --- a/packages/react-router/src/index.tsx +++ b/packages/react-router/src/index.tsx @@ -12,7 +12,7 @@ export { } from '@tanstack/history' export { default as invariant } from 'tiny-invariant' export { default as warning } from 'tiny-warning' -export { useAwaited, Await, type AwaitOptions } from './awaited' +export { useAwaited, Await, type AwaitOptions, ScriptOnce } from './awaited' export { defer, isDehydratedDeferred, diff --git a/packages/react-router/src/router.ts b/packages/react-router/src/router.ts index 15986c97f7..33ee3f5dcb 100644 --- a/packages/react-router/src/router.ts +++ b/packages/react-router/src/router.ts @@ -2231,11 +2231,6 @@ export class Router< return match } - /** - * @deprecated Injecting HTML directly is no longer supported. Use the new component instead. - */ - injectHtml = async (html: string | (() => Promise | string)) => {} - // We use a token -> weak map to keep track of deferred promises // that are registered on the server and need to be resolved registeredDeferredsIds = new Map() diff --git a/packages/start/src/server/index.tsx b/packages/start/src/server/index.tsx index bb3d34cb24..211b0ccf4d 100644 --- a/packages/start/src/server/index.tsx +++ b/packages/start/src/server/index.tsx @@ -1,10 +1,6 @@ /// export { StartServer } from './StartServer' -export { - transformStreamWithRouter, - transformReadableStreamWithRouter, -} from './transformStreamWithRouter' export { getRequestHeaders } from './getRequestHeaders' export { createRequestHandler } from './createRequestHandler' export { defaultStreamHandler } from './defaultStreamHandler' diff --git a/packages/start/src/server/transformStreamWithRouter.tsx b/packages/start/src/server/transformStreamWithRouter.tsx deleted file mode 100644 index 8380bd0fda..0000000000 --- a/packages/start/src/server/transformStreamWithRouter.tsx +++ /dev/null @@ -1,140 +0,0 @@ -import { Transform } from 'stream' -import type { AnyRouter } from '@tanstack/react-router' - -/** - * @deprecated This is no longer necessary as long as you - * are using the component or `useAwaited` hook - */ -export function transformStreamWithRouter(router: AnyRouter) { - const callbacks = transformHtmlCallbacks(injectorFromRouter(router)) - return new Transform({ - transform(chunk, _encoding, callback) { - callbacks - .transform(chunk, this.push.bind(this)) - .then(() => callback()) - .catch((err) => callback(err)) - }, - flush(callback) { - callbacks - .flush(this.push.bind(this)) - .then(() => callback()) - .catch((err) => callback(err)) - }, - }) -} - -/** - * @deprecated This is no longer necessary as long as you - * are using the component or `useAwaited` hook - */ -export function transformReadableStreamWithRouter(router: AnyRouter) { - const callbacks = transformHtmlCallbacks(injectorFromRouter(router)) - return new TransformStream({ - transform(chunk, controller) { - return callbacks.transform(chunk, (chunkToPush) => { - controller.enqueue(chunkToPush) - return true - }) - }, - flush(controller) { - return callbacks.flush((chunkToPush) => { - controller.enqueue(chunkToPush) - return true - }) - }, - }) -} - -function injectorFromRouter(router: AnyRouter) { - return async () => '' -} - -// regex pattern for matching closing body and html tags -const patternBodyStart = /()/ -const patternHtmlEnd = /(<\/html>)/ - -// regex pattern for matching closing tags -const pattern = /(<\/[a-zA-Z][\w:.-]*?>)/g - -const textDecoder = new TextDecoder() - -function transformHtmlCallbacks(injector: () => Promise) { - let bodyStarted = false - let leftover = '' - // If a closing tag is split across chunks, store the HTML to add after it - // This expects that all the HTML that's added is closed properly - let leftoverHtml = '' - - return { - async transform(chunk: any, push: (chunkToPush: string) => boolean) { - const chunkString = leftover + textDecoder.decode(chunk) - - const bodyStartMatch = chunkString.match(patternBodyStart) - const bodyEndMatch = chunkString.match(patternBodyEnd) - const htmlEndMatch = chunkString.match(patternHtmlEnd) - - try { - const html = await injector() - - if (bodyStartMatch) { - bodyStarted = true - } - - if (!bodyStarted) { - push(chunkString) - leftover = '' - return - } - - // If a sequence was found - if ( - bodyEndMatch && - htmlEndMatch && - bodyEndMatch.index! < htmlEndMatch.index! - ) { - const bodyIndex = bodyEndMatch.index! + bodyEndMatch[0].length - const htmlIndex = htmlEndMatch.index! + htmlEndMatch[0].length - - // Add the arbitrary HTML before the closing body tag - const processed = - chunkString.slice(0, bodyIndex) + - html + - chunkString.slice(bodyIndex, htmlIndex) + - chunkString.slice(htmlIndex) - - push(processed) - leftover = '' - } else { - // For all other closing tags, add the arbitrary HTML after them - let result - let lastIndex = 0 - - while ((result = pattern.exec(chunkString)) !== null) { - lastIndex = result.index + result[0].length - } - - // If a closing tag was found, add the arbitrary HTML and send it through - if (lastIndex > 0) { - const processed = - chunkString.slice(0, lastIndex) + html + leftoverHtml - push(processed) - leftover = chunkString.slice(lastIndex) - } else { - // If no closing tag was found, store the chunk to process with the next one - leftover = chunkString - leftoverHtml += html - } - } - } catch (err) { - console.error(err) - throw err - } - }, - async flush(push: (chunkToPush: string) => boolean) { - if (leftover) { - push(leftover) - } - }, - } -}