Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .changeset/curly-dodos-import.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'@tanstack/router-core': patch
'@tanstack/react-router': patch
---

Pass router SSR import maps through to React's streaming server renderers.
8 changes: 8 additions & 0 deletions packages/react-router/src/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,14 @@ import type {
} from './route'

declare module '@tanstack/router-core' {
export interface RouterSsrOptionsExtensions {
importMap?: {
imports?: Record<string, string>
integrity?: Record<string, string>
scopes?: Record<string, Record<string, string>>
}
}

export interface RouterOptionsExtensions {
/**
* The default `component` a route should use if no component is provided.
Expand Down
8 changes: 8 additions & 0 deletions packages/react-router/src/ssr/renderRouterToStream.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,12 @@ const isAbortError = (request: Request, error: unknown) =>
(request.signal.aborted && error === request.signal.reason) ||
(error instanceof Error && error.name === 'AbortError')

/**
* Renders a React router application to a streaming SSR response.
*
* @param options - The request, router, response headers, and React content to render.
* @returns The router-managed streaming response.
*/
export const renderRouterToStream = async ({
request,
router,
Expand All @@ -55,6 +61,7 @@ export const renderRouterToStream = async ({
if (typeof ReactDOMServer.renderToReadableStream === 'function') {
const stream = await ReactDOMServer.renderToReadableStream(children, {
signal: request.signal,
importMap: router.options.ssr?.importMap,
nonce: router.options.ssr?.nonce,
progressiveChunkSize: Number.POSITIVE_INFINITY,
onError: (error, info) => {
Expand Down Expand Up @@ -154,6 +161,7 @@ export const renderRouterToStream = async ({

try {
pipeable = ReactDOMServer.renderToPipeableStream(children, {
importMap: router.options.ssr?.importMap,
nonce: router.options.ssr?.nonce,
progressiveChunkSize: Number.POSITIVE_INFINITY,
...(isbot(request.headers.get('User-Agent'))
Expand Down
62 changes: 62 additions & 0 deletions packages/react-router/tests/renderRouterToStream.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,68 @@ function unwrapResponse(
}

describe('renderRouterToStream - pipeable sync errors', () => {
test('passes the import map to readable stream rendering', async () => {
const importMap = {
imports: { package: '/package.js' },
integrity: { '/package.js': 'sha384-readable' },
scopes: { '/scope/': { dependency: '/dependency.js' } },
}
const stream = Object.assign(
new ReadableStream<Uint8Array>({
start(controller) {
controller.close()
},
}),
{ allReady: Promise.resolve() },
)
reactDomServerMocks.renderToReadableStream = vi.fn(
(_children?: unknown, options?: { importMap?: typeof importMap }) => {
expect(options?.importMap).toBe(importMap)
return stream
},
)

const router = await buildRouter()
router.options.ssr = { importMap }
try {
await renderRouterToStream({
request: new Request('http://localhost/'),
router,
responseHeaders: new Headers(),
children: null,
})
} finally {
router.serverSsr?.cleanup()
}
})

test('passes the import map to pipeable stream rendering', async () => {
const importMap = {
imports: { package: '/package.js' },
integrity: { '/package.js': 'sha384-pipeable' },
scopes: { '/scope/': { dependency: '/dependency.js' } },
}
reactDomServerMocks.renderToPipeableStream.mockImplementationOnce(
(_children, options) => {
expect(options.importMap).toBe(importMap)
return { abort: vi.fn(), pipe: vi.fn() }
},
)

const router = await buildRouter()
router.options.ssr = { importMap }
try {
await renderRouterToStream({
request: new Request('http://localhost/'),
router,
responseHeaders: new Headers(),
children: null,
})
} finally {
router.serverSsr?.cleanup()
}
})

test('request abort cancels readable rendering without consuming the response body', async () => {
const cancel = vi.fn()
const stream = Object.assign(new ReadableStream<Uint8Array>({ cancel }), {
Expand Down
2 changes: 2 additions & 0 deletions packages/router-core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -261,6 +261,8 @@ export type {
RouterEvents,
MatchRoutesOpts,
RouterOptionsExtensions,
RouterSsrOptions,
RouterSsrOptionsExtensions,
DefaultRemountDepsFn,
PreloadRouteFn,
MatchRouteFn,
Expand Down
12 changes: 8 additions & 4 deletions packages/router-core/src/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,13 @@ import type {
} from './Matches'
import type { RootRouteId } from './root'
import type { ParseRoute, RouteById, RouteIds, RoutePaths } from './routeInfo'
import type { AnyRouter, Register, RegisteredRouter, SSROption } from './router'
import type {
AnyRouter,
Register,
RegisteredRouter,
RouterSsrOptions,
SSROption,
} from './router'
import type { BuildLocationFn, NavigateFn } from './RouterProvider'
import type {
Assign,
Expand Down Expand Up @@ -1203,9 +1209,7 @@ type AssetFnContextOptions<
in out TBeforeLoadFn,
in out TLoaderDeps,
> = {
ssr?: {
nonce?: string
}
ssr?: RouterSsrOptions
matches: Array<
RouteMatch<
TRouteId,
Expand Down
10 changes: 7 additions & 3 deletions packages/router-core/src/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,12 @@ export interface DefaultRouterOptionsExtensions {}

export interface RouterOptionsExtensions extends DefaultRouterOptionsExtensions {}

export interface RouterSsrOptionsExtensions {}

export interface RouterSsrOptions extends RouterSsrOptionsExtensions {
nonce?: string
}

export type SSROption = boolean | 'data-only'

export interface RouterOptions<
Expand Down Expand Up @@ -514,9 +520,7 @@ export interface RouterOptions<
*/
rewrite?: LocationRewrite
origin?: string
ssr?: {
nonce?: string
}
ssr?: RouterSsrOptions
}

export type LocationRewrite = {
Expand Down