Skip to content
Merged
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
37 changes: 5 additions & 32 deletions packages/stats-generator/src/serve/react-router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,45 +15,18 @@ const staticDir = join(appDir, 'build', 'client')
const buildPath = join(appDir, 'build', 'server', 'index.js')
const buildUrl = pathToFileURL(buildPath).href

// Resolve react-router from the app's own node_modules, not the stats-generator's.
const appRequire = createRequire(join(appDir, 'package.json'))
const rrPath = appRequire.resolve('react-router')
const { createRequestHandler } = await import(pathToFileURL(rrPath).href)
const rrNodePath = appRequire.resolve('@react-router/node')
const { createRequestListener } = await import(pathToFileURL(rrNodePath).href)
const build = await import(buildUrl)
const handler = createRequestHandler(build, 'production')
const handler = createRequestListener({ build, mode: 'production' })

const server = createServer(async (req, res) => {
const server = createServer((req, res) => {
const { pathname } = new URL(req.url ?? '/', `http://localhost:${PORT}`)

if (tryServeFile(staticDir, pathname, req, res)) return

const headers = new Headers(
Object.fromEntries(
Object.entries(req.headers).map(([k, v]) => [
k,
Array.isArray(v) ? v.join(', ') : (v ?? ''),
]),
),
)
const hasBody = req.method !== 'GET' && req.method !== 'HEAD'
const webReq = new Request(`http://localhost:${PORT}${req.url ?? '/'}`, {
method: req.method,
headers,
body: hasBody ? req : null,
duplex: 'half',
})

const webRes: Response = await handler(webReq)

res.writeHead(webRes.status, Object.fromEntries(webRes.headers.entries()))

if (webRes.body) {
for await (const chunk of webRes.body) {
res.write(chunk)
}
}

res.end()
handler(req, res)
}).listen(PORT, () => {
console.log(`Ready at http://localhost:${PORT}`)
})
Expand Down
Loading