Skip to content

fix react-basic-ssr-streaming-file-based example #4429

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 16 commits into
base: main
Choose a base branch
from
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

This file was deleted.

34 changes: 34 additions & 0 deletions examples/react/basic-ssr-streaming-file-based/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
{
"name": "tanstack-router-react-example-basic-ssr-streaming-file-based",
"private": true,
"type": "module",
"scripts": {
"dev": "node server",
"build": "npm run build:client && npm run build:server",
"build:client": "vite build",
"build:server": "vite build --ssr",
"serve": "NODE_ENV=production node server",
"debug": "node --inspect-brk server"
},
"dependencies": {
"@tanstack/react-router": "^1.121.16",
"@tanstack/react-start": "^1.121.16",
"get-port": "^7.1.0",
"react": "^19.0.0",
"react-dom": "^19.0.0"
},
"devDependencies": {
"@tanstack/react-router-devtools": "^1.121.16",
"@tanstack/router-plugin": "^1.121.16",
"@types/express": "^4.17.23",
"@vitejs/plugin-react": "^4.5.2",
"typescript": "^5.7.2",
"compression": "^1.8.0",
"express": "^4.21.2",
"isbot": "^5.1.22",
"node-fetch": "^3.3.2",
"vite": "^6.3.5",
"@types/react": "^19.0.8",
"@types/react-dom": "^19.0.1"
}
}
Binary file not shown.
19 changes: 15 additions & 4 deletions examples/react/basic-ssr-streaming-file-based/server.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import path from 'node:path'
import express from 'express'
import getPort, { portNumbers } from 'get-port'
import * as zlib from 'node:zlib'

const isTest = process.env.NODE_ENV === 'test' || !!process.env.VITE_TEST_BUILD

Expand Down Expand Up @@ -37,21 +39,30 @@ export async function createServer(
// use vite's connect instance as middleware
app.use(vite.middlewares)
} else {
app.use((await import('compression')).default())
app.use(
(await import('compression')).default({
brotli: {
flush: zlib.constants.BROTLI_OPERATION_FLUSH,
},
flush: zlib.constants.Z_SYNC_FLUSH,
}),
)
}

if (isProd) app.use(express.static('./dist/client'))

app.use('*', async (req, res) => {
try {
const url = req.originalUrl

if (url.includes('.')) {
if (path.extname(url) !== '') {
console.warn(`${url} is not valid router path`)
res.status(404)
res.end(`${url} is not valid router path`)
return
}

// Extract the head from vite's index transformation hook
// Best effort extraction of the head from vite's index transformation hook
let viteHead = !isProd
? await vite.transformIndexHtml(
url,
Expand All @@ -73,7 +84,7 @@ export async function createServer(
})()

console.info('Rendering: ', url, '...')
entry.render({ req, res, url, head: viteHead })
entry.render({ req, res, head: viteHead })
} catch (e) {
!isProd && vite.ssrFixStacktrace(e)
console.info(e.stack)
Expand Down
59 changes: 50 additions & 9 deletions examples/react/basic-ssr-streaming-file-based/src/entry-server.tsx
Original file line number Diff line number Diff line change
@@ -1,22 +1,63 @@
import { pipeline } from 'node:stream/promises'
import {
createRequestHandler,
defaultStreamHandler,
} from '@tanstack/react-start/server'
import { createRouter } from './router'
import type express from 'express'

// index.js
import './fetch-polyfill'

export async function render(opts: {
url: string
export async function render({
req,
res,
head,
}: {
head: string
req: express.Request
res: express.Response
}) {
return createRequestHandler({
createRouter,
req: opts.req,
res: opts.res,
})(defaultStreamHandler)
// Convert the express request to a fetch request
const url = new URL(req.originalUrl || req.url, 'https://localhost:3000').href

const request = new Request(url, {
method: req.method,
headers: (() => {
const headers = new Headers()
for (const [key, value] of Object.entries(req.headers)) {
headers.set(key, value as any)
}
return headers
})(),
})

// Create a request handler
const handler = createRequestHandler({
request,
createRouter: () => {
const router = createRouter()

// Update each router instance with the head info from vite
router.update({
context: {
...router.options.context,
head: head,
},
})
return router
},
})

// Let's use the default stream handler to create the response
const response = await handler(defaultStreamHandler)

// Convert the fetch response back to an express response
res.statusMessage = response.statusText
res.status(response.status)

response.headers.forEach((value, name) => {
res.setHeader(name, value)
})

// Stream the response body
return pipeline(response.body as any, res)
}
Loading