Open History to see the last commit
1import { resolve } from 'node:path'
2import { pathToFileURL } from 'node:url'
3import { NodeRequest, sendNodeResponse } from 'srvx/node'
4import { joinURL } from 'ufo'
5import { RSBUILD_ENVIRONMENT_NAMES } from './planning'
6import type { IncomingMessage, ServerResponse } from 'node:http'
7import type { RsbuildConfig } from '@rsbuild/core'
8β
9type ServerSetupFn = Extract<
10 NonNullable<NonNullable<RsbuildConfig['server']>['setup']>,
11 (...args: Array<any>) => any
12>
13type ServerSetupContext = Parameters<ServerSetupFn>[0]
14type SSRMiddleware = (
15 req: IncomingMessage & { originalUrl?: string },
16 res: ServerResponse,
17 next: (error?: unknown) => void,
18) => Promise<void>
19type FetchHandler = (req: Request) => Promise<Response> | Response
20β
21type ServerEntry =
22 | FetchHandler
23 | {
24 fetch?: FetchHandler
25 }
26β
27function resolveFetchHandler(serverEntry: ServerEntry): FetchHandler {
28 if (typeof serverEntry === 'function') {
29 return serverEntry
30 }
31β
32 if (typeof serverEntry.fetch === 'function') {
33 return serverEntry.fetch.bind(serverEntry)
34 }
35β
36 throw new Error(
37 'Unable to resolve a request handler from Rsbuild server bundle',
38 )
39}
40β
41function getPublicBasePathname(publicBase: string): string {
42 try {
43 return new URL(publicBase, 'http://localhost').pathname
44 } catch {
45 return publicBase
46 }
47}
48β
49function restorePreviewUrl(opts: {
50 req: IncomingMessage & { originalUrl?: string }
51 publicBase: string
52}) {
53 if (opts.req.originalUrl) {
54 opts.req.url = opts.req.originalUrl
55 }
56β
57 const publicBasePathname = getPublicBasePathname(opts.publicBase)
58 if (publicBasePathname === '/') {
59 return
60 }
61β
62 const url = opts.req.url ?? '/'
63 if (url.startsWith(publicBasePathname)) {
64 return
65 }
66β
67 opts.req.url = joinURL(publicBasePathname, url)
68}
69β
70async function loadDevFetchHandler(
71 context: ServerSetupContext,
72): Promise<FetchHandler> {
73 if (context.action !== 'dev') {
74 throw new Error('Cannot load Rsbuild dev SSR bundle outside dev mode')
75 }
76β
77 const ssrEnv = context.server.environments[RSBUILD_ENVIRONMENT_NAMES.server]
78β
79 if (!ssrEnv) {
80 throw new Error(
81 `SSR environment "${RSBUILD_ENVIRONMENT_NAMES.server}" not found`,
82 )
83 }
84β
85 const serverEntry = await ssrEnv.loadBundle<{ default: ServerEntry }>('index')
86 return resolveFetchHandler(serverEntry.default)
87}
88β
89/**
90 * Returns a `server.setup` function for rsbuild v2.
91 *
92 * Two middleware positions are used:
93 *
94 * 1. **Setup body** (BEFORE built-ins): Intercepts `/_serverFn/` URLs so
95 * they never reach rsbuild's htmlFallback/htmlCompletion middleware,
96 * which can swallow long base64 function IDs.
97 *
98 * 2. **Returned callback** (AFTER built-ins, BEFORE fallback): Handles
99 * all remaining SSR requests (page navigations). This position lets
100 * rsbuild's asset middleware serve compiled JS/CSS first.
101 *
102 * The middleware choreography is shared by dev and preview. The server entry
103 * loader differs: dev reads from Rsbuild's in-memory environment so rebuilds
104 * are reflected immediately, while preview lazy-imports the production server
105 * bundle from disk.
106 *
107 * See rsbuild source: devMiddlewares.ts `applyDefaultMiddlewares()` and
108 * previewServer.ts `startPreviewServer()`.
109 */
110export function createServerSetup(opts: {
111 serverFnBasePath: string
112 serverOutputDirectory: string
113 publicBase: string
114}): ServerSetupFn {
115 let previewFetchHandlerPromise: Promise<FetchHandler> | undefined
116β
117 const getPreviewFetchHandler = () => {
118 if (!previewFetchHandlerPromise) {
119 previewFetchHandlerPromise = loadPreviewFetchHandler(
120 opts.serverOutputDirectory,
121 )
122 }
123β
124 return previewFetchHandlerPromise
125 }
126β
127 return (context) => {
128 const serverFnBase = opts.serverFnBasePath
129β
130 const handleSSR: SSRMiddleware = async (req, res, next) => {
131 try {
132 const fetchHandler =
133 context.action === 'dev'
134 ? await loadDevFetchHandler(context)
135 : await getPreviewFetchHandler()
136β
137 if (context.action === 'preview') {
138 // Rsbuild preview's base middleware strips server.base before the
139 // returned setup callback runs. Put it back before creating the Web
140 // Request so Start's router sees the same URL shape as build/custom
141 // servers. The early server-fn middleware runs before that base
142 // middleware, so avoid prepending when the URL already has the base.
143 restorePreviewUrl({ req, publicBase: opts.publicBase })
144 } else if (req.originalUrl) {
145 // Restore the original URL (rsbuild may rewrite to /index.html)
146 req.url = req.originalUrl
147 }
148β
149 const webReq = new NodeRequest({ req, res })
150 const webRes = await fetchHandler(webReq)
151 return sendNodeResponse(res, webRes)
152 } catch (e) {
153 console.error('[tanstack-start] SSR error:', e)
154β
155 const webReq = new NodeRequest({ req, res })
156 if (webReq.headers.get('content-type')?.includes('application/json')) {
157 return sendNodeResponse(
158 res,
159 new Response(
160 JSON.stringify(
161 {
162 status: 500,
163 error: 'Internal Server Error',
164 message:
165 'An unexpected error occurred. Please try again later.',
166 timestamp: new Date().toISOString(),
167 },
168 null,
169 2,
170 ),
171 {
172 status: 500,
173 headers: { 'Content-Type': 'application/json' },
174 },
175 ),
176 )
177 }
178β
179 return next(e)
180 }
181 }
182β
183 // Position 1: BEFORE built-ins β intercept server function calls
184 // early so they are not swallowed by htmlFallback or assetsMiddleware.
185 context.server.middlewares.use(async (req, res, next) => {
186 const url = req.url || '/'
187 if (url.startsWith(serverFnBase)) {
188 return handleSSR(req, res, next)
189 }
190 return next()
191 })
192β
193 // Position 2: AFTER built-ins, before fallback β SSR catch-all for
194 // page navigations. Assets are already handled by rsbuild middleware.
195 return () => {
196 context.server.middlewares.use(handleSSR)
197 }
198 }
199}
200β
201async function loadPreviewFetchHandler(
202 serverOutputDirectory: string,
203): Promise<FetchHandler> {
204 const serverEntryPath = resolve(serverOutputDirectory, 'index.js')
205 const imported = (await import(
206 pathToFileURL(serverEntryPath).toString()
207 )) as { default: ServerEntry }
208β
209 try {
210 return resolveFetchHandler(imported.default)
211 } catch (error) {
212 throw new Error(
213 `Unable to resolve a request handler from Rsbuild server bundle at ${serverEntryPath}`,
214 { cause: error },
215 )
216 }
217}