Open History to see the last commit
1import { pathToFileURL } from 'node:url'
2import { basename, extname, join } from 'pathe'
3import { NodeRequest, sendNodeResponse } from 'srvx/node'
4import { joinURL } from 'ufo'
5import { VITE_ENVIRONMENT_NAMES } from '../../constants'
6import { getServerOutputDirectory } from '../output-directory'
7import { getBundlerOptions } from '../../utils'
8import type { Plugin } from 'vite'
9β
10export function previewServerPlugin(): Plugin {
11 return {
12 name: 'tanstack-start-core:preview-server',
13 configurePreviewServer: {
14 // Run last so platform plugins (Cloudflare, Vercel, etc.) can register their handlers first
15 order: 'post',
16 handler(server) {
17 // Return a function so Vite's internal middlewares (static files, etc.) handle requests first.
18 // Our SSR handler only processes requests that nothing else handled.
19 return () => {
20 // Cache the server build to avoid re-importing on every request
21 let serverBuild: any = null
22β
23 server.middlewares.use(async (req, res, next) => {
24 try {
25 // Lazy load server build on first request
26 if (!serverBuild) {
27 // Derive output filename from input
28 const serverEnv =
29 server.config.environments[VITE_ENVIRONMENT_NAMES.server]
30 const serverInput =
31 getBundlerOptions(serverEnv?.build)?.input ?? 'server'
32β
33 if (typeof serverInput !== 'string') {
34 throw new Error('Invalid server input. Expected a string.')
35 }
36β
37 // Get basename without extension and add .js
38 const outputFilename = `${basename(serverInput, extname(serverInput))}.js`
39 const serverOutputDir = getServerOutputDirectory(server.config)
40 const serverEntryPath = join(serverOutputDir, outputFilename)
41 const imported = await import(
42 pathToFileURL(serverEntryPath).toString()
43 )
44β
45 serverBuild = imported.default
46 }
47β
48 // Prepend base path to request URL to match routing setup
49 req.url = joinURL(server.config.base, req.url ?? '/')
50β
51 const webReq = new NodeRequest({ req, res })
52 const webRes: Response = await serverBuild.fetch(webReq)
53β
54 if (webRes.headers.get('content-type')?.startsWith('text/html')) {
55 res.setHeader('content-encoding', 'identity')
56 }
57β
58 // Temporary workaround
59 // Vite preview's compression middleware doesn't support flattened array headers that srvx sets
60 // Call writeHead() before srvx to avoid corruption
61 res.setHeaders(webRes.headers)
62 res.writeHead(webRes.status, webRes.statusText)
63β
64 return sendNodeResponse(res, webRes)
65 } catch (error) {
66 next(error)
67 }
68 })
69 }
70 },
71 },
72 }
73}