Open History to see the last commit
1/**
2 * TanStack Start Production Server with Bun
3 *
4 * A high-performance production server for TanStack Start applications that
5 * implements intelligent static asset loading with configurable memory management.
6 *
7 * Features:
8 * - Hybrid loading strategy (preload small files, serve large files on-demand)
9 * - Configurable file filtering with include/exclude patterns
10 * - Memory-efficient response generation
11 * - Production-ready caching headers
12 *
13 * Environment Variables:
14 *
15 * PORT (number)
16 * - Server port number
17 * - Default: 3000
18 *
19 * ASSET_PRELOAD_MAX_SIZE (number)
20 * - Maximum file size in bytes to preload into memory
21 * - Files larger than this will be served on-demand from disk
22 * - Default: 5242880 (5MB)
23 * - Example: ASSET_PRELOAD_MAX_SIZE=5242880 (5MB)
24 *
25 * ASSET_PRELOAD_INCLUDE_PATTERNS (string)
26 * - Comma-separated list of glob patterns for files to include
27 * - If specified, only matching files are eligible for preloading
28 * - Patterns are matched against filenames only, not full paths
29 * - Example: ASSET_PRELOAD_INCLUDE_PATTERNS="*.js,*.css,*.woff2"
30 *
31 * ASSET_PRELOAD_EXCLUDE_PATTERNS (string)
32 * - Comma-separated list of glob patterns for files to exclude
33 * - Applied after include patterns
34 * - Patterns are matched against filenames only, not full paths
35 * - Example: ASSET_PRELOAD_EXCLUDE_PATTERNS="*.map,*.txt"
36 *
37 * ASSET_PRELOAD_VERBOSE_LOGGING (boolean)
38 * - Enable detailed logging of loaded and skipped files
39 * - Default: false
40 * - Set to "true" to enable verbose output
41 *
42 * ASSET_PRELOAD_ENABLE_ETAG (boolean)
43 * - Enable ETag generation for preloaded assets
44 * - Default: true
45 * - Set to "false" to disable ETag support
46 *
47 * ASSET_PRELOAD_ENABLE_GZIP (boolean)
48 * - Enable Gzip compression for eligible assets
49 * - Default: true
50 * - Set to "false" to disable Gzip compression
51 *
52 * ASSET_PRELOAD_GZIP_MIN_SIZE (number)
53 * - Minimum file size in bytes required for Gzip compression
54 * - Files smaller than this will not be compressed
55 * - Default: 1024 (1KB)
56 *
57 * ASSET_PRELOAD_GZIP_MIME_TYPES (string)
58 * - Comma-separated list of MIME types eligible for Gzip compression
59 * - Supports partial matching for types ending with "/"
60 * - Default: text/,application/javascript,application/json,application/xml,image/svg+xml
61 *
62 * Usage:
63 * bun run server.ts
64 */
65β
66// Configuration
67const SERVER_PORT = Number(process.env.PORT ?? 3000)
68const CLIENT_DIRECTORY = './dist/client'
69const SERVER_ENTRY_POINT = './dist/server/server.js'
70β
71// Logging utilities for professional output
72const log = {
73 info: (message: string) => {
74 console.log(`[INFO] ${message}`)
75 },
76 success: (message: string) => {
77 console.log(`[SUCCESS] ${message}`)
78 },
79 warning: (message: string) => {
80 console.log(`[WARNING] ${message}`)
81 },
82 error: (message: string) => {
83 console.log(`[ERROR] ${message}`)
84 },
85 header: (message: string) => {
86 console.log(`\n${message}\n`)
87 },
88}
89β
90// Preloading configuration from environment variables
91const MAX_PRELOAD_BYTES = Number(
92 process.env.ASSET_PRELOAD_MAX_SIZE ?? 5 * 1024 * 1024, // 5MB default
93)
94β
95// Parse comma-separated include patterns (no defaults)
96const INCLUDE_PATTERNS = (process.env.ASSET_PRELOAD_INCLUDE_PATTERNS ?? '')
97 .split(',')
98 .map((s) => s.trim())
99 .filter(Boolean)
100 .map((pattern: string) => convertGlobToRegExp(pattern))
101β
102// Parse comma-separated exclude patterns (no defaults)
103const EXCLUDE_PATTERNS = (process.env.ASSET_PRELOAD_EXCLUDE_PATTERNS ?? '')
104 .split(',')
105 .map((s) => s.trim())
106 .filter(Boolean)
107 .map((pattern: string) => convertGlobToRegExp(pattern))
108β
109// Verbose logging flag
110const VERBOSE = process.env.ASSET_PRELOAD_VERBOSE_LOGGING === 'true'
111β
112// Optional ETag feature
113const ENABLE_ETAG = (process.env.ASSET_PRELOAD_ENABLE_ETAG ?? 'true') === 'true'
114β
115// Optional Gzip feature
116const ENABLE_GZIP = (process.env.ASSET_PRELOAD_ENABLE_GZIP ?? 'true') === 'true'
117const GZIP_MIN_BYTES = Number(process.env.ASSET_PRELOAD_GZIP_MIN_SIZE ?? 1024) // 1KB
118const GZIP_TYPES = (
119 process.env.ASSET_PRELOAD_GZIP_MIME_TYPES ??
120 'text/,application/javascript,application/json,application/xml,image/svg+xml'
121)
122 .split(',')
123 .map((v) => v.trim())
124 .filter(Boolean)
125β
126/**
127 * Convert a simple glob pattern to a regular expression
128 * Supports * wildcard for matching any characters
129 */
130function convertGlobToRegExp(globPattern: string): RegExp {
131 // Escape regex special chars except *, then replace * with .*
132 const escapedPattern = globPattern
133 .replace(/[-/\\^$+?.()|[\]{}]/g, '\\$&')
134 .replace(/\*/g, '.*')
135 return new RegExp(`^${escapedPattern}$`, 'i')
136}
137β
138/**
139 * Compute ETag for a given data buffer
140 */
141function computeEtag(data: Uint8Array): string {
142 const hash = Bun.hash(data)
143 return `W/"${hash.toString(16)}-${data.byteLength.toString()}"`
144}
145β
146/**
147 * Metadata for preloaded static assets
148 */
149interface AssetMetadata {
150 route: string
151 size: number
152 type: string
153}
154β
155/**
156 * In-memory asset with ETag and Gzip support
157 */
158interface InMemoryAsset {
159 raw: Uint8Array
160 gz?: Uint8Array
161 etag?: string
162 type: string
163 immutable: boolean
164 size: number
165}
166β
167/**
168 * Result of static asset preloading process
169 */
170interface PreloadResult {
171 routes: Record<string, (req: Request) => Response | Promise<Response>>
172 loaded: AssetMetadata[]
173 skipped: AssetMetadata[]
174}
175β
176/**
177 * Check if a file is eligible for preloading based on configured patterns
178 */
179function isFileEligibleForPreloading(relativePath: string): boolean {
180 const fileName = relativePath.split(/[/\\]/).pop() ?? relativePath
181β
182 // If include patterns are specified, file must match at least one
183 if (INCLUDE_PATTERNS.length > 0) {
184 if (!INCLUDE_PATTERNS.some((pattern) => pattern.test(fileName))) {
185 return false
186 }
187 }
188β
189 // If exclude patterns are specified, file must not match any
190 if (EXCLUDE_PATTERNS.some((pattern) => pattern.test(fileName))) {
191 return false
192 }
193β
194 return true
195}
196β
197/**
198 * Check if a MIME type is compressible
199 */
200function isMimeTypeCompressible(mimeType: string): boolean {
201 return GZIP_TYPES.some((type) =>
202 type.endsWith('/') ? mimeType.startsWith(type) : mimeType === type,
203 )
204}
205β
206/**
207 * Conditionally compress data based on size and MIME type
208 */
209function compressDataIfAppropriate(
210 data: Uint8Array,
211 mimeType: string,
212): Uint8Array | undefined {
213 if (!ENABLE_GZIP) return undefined
214 if (data.byteLength < GZIP_MIN_BYTES) return undefined
215 if (!isMimeTypeCompressible(mimeType)) return undefined
216 try {
217 return Bun.gzipSync(data.buffer as ArrayBuffer)
218 } catch {
219 return undefined
220 }
221}
222β
223/**
224 * Create response handler function with ETag and Gzip support
225 */
226function createResponseHandler(
227 asset: InMemoryAsset,
228): (req: Request) => Response {
229 return (req: Request) => {
230 const headers: Record<string, string> = {
231 'Content-Type': asset.type,
232 'Cache-Control': asset.immutable
233 ? 'public, max-age=31536000, immutable'
234 : 'public, max-age=3600',
235 }
236β
237 if (ENABLE_ETAG && asset.etag) {
238 const ifNone = req.headers.get('if-none-match')
239 if (ifNone && ifNone === asset.etag) {
240 return new Response(null, {
241 status: 304,
242 headers: { ETag: asset.etag },
243 })
244 }
245 headers.ETag = asset.etag
246 }
247β
248 if (
249 ENABLE_GZIP &&
250 asset.gz &&
251 req.headers.get('accept-encoding')?.includes('gzip')
252 ) {
253 headers['Content-Encoding'] = 'gzip'
254 headers['Content-Length'] = String(asset.gz.byteLength)
255 const gzCopy = new Uint8Array(asset.gz)
256 return new Response(gzCopy, { status: 200, headers })
257 }
258β
259 headers['Content-Length'] = String(asset.raw.byteLength)
260 const rawCopy = new Uint8Array(asset.raw)
261 return new Response(rawCopy, { status: 200, headers })
262 }
263}
264β
265/**
266 * Create composite glob pattern from include patterns
267 */
268function createCompositeGlobPattern(): Bun.Glob {
269 const raw = (process.env.ASSET_PRELOAD_INCLUDE_PATTERNS ?? '')
270 .split(',')
271 .map((s) => s.trim())
272 .filter(Boolean)
273 if (raw.length === 0) return new Bun.Glob('**/*')
274 if (raw.length === 1) return new Bun.Glob(raw[0])
275 return new Bun.Glob(`{${raw.join(',')}}`)
276}
277β
278/**
279 * Initialize static routes with intelligent preloading strategy
280 * Small files are loaded into memory, large files are served on-demand
281 */
282async function initializeStaticRoutes(
283 clientDirectory: string,
284): Promise<PreloadResult> {
285 const routes: Record<string, (req: Request) => Response | Promise<Response>> =
286 {}
287 const loaded: AssetMetadata[] = []
288 const skipped: AssetMetadata[] = []
289β
290 log.info(`Loading static assets from ${clientDirectory}...`)
291 if (VERBOSE) {
292 console.log(
293 `Max preload size: ${(MAX_PRELOAD_BYTES / 1024 / 1024).toFixed(2)} MB`,
294 )
295 if (INCLUDE_PATTERNS.length > 0) {
296 console.log(
297 `Include patterns: ${process.env.ASSET_PRELOAD_INCLUDE_PATTERNS ?? ''}`,
298 )
299 }
300 if (EXCLUDE_PATTERNS.length > 0) {
301 console.log(
302 `Exclude patterns: ${process.env.ASSET_PRELOAD_EXCLUDE_PATTERNS ?? ''}`,
303 )
304 }
305 }
306β
307 let totalPreloadedBytes = 0
308β
309 try {
310 const glob = createCompositeGlobPattern()
311 for await (const relativePath of glob.scan({ cwd: clientDirectory })) {
312 const filepath = `${clientDirectory}/${relativePath}`
313 const route = `/${relativePath}`
314β
315 try {
316 // Get file metadata
317 const file = Bun.file(filepath)
318β
319 // Skip if file doesn't exist or is empty
320 if (!(await file.exists()) || file.size === 0) {
321 continue
322 }
323β
324 const metadata: AssetMetadata = {
325 route,
326 size: file.size,
327 type: file.type || 'application/octet-stream',
328 }
329β
330 // Determine if file should be preloaded
331 const matchesPattern = isFileEligibleForPreloading(relativePath)
332 const withinSizeLimit = file.size <= MAX_PRELOAD_BYTES
333β
334 if (matchesPattern && withinSizeLimit) {
335 // Preload small files into memory with ETag and Gzip support
336 const bytes = new Uint8Array(await file.arrayBuffer())
337 const gz = compressDataIfAppropriate(bytes, metadata.type)
338 const etag = ENABLE_ETAG ? computeEtag(bytes) : undefined
339 const asset: InMemoryAsset = {
340 raw: bytes,
341 gz,
342 etag,
343 type: metadata.type,
344 immutable: true,
345 size: bytes.byteLength,
346 }
347 routes[route] = createResponseHandler(asset)
348β
349 loaded.push({ ...metadata, size: bytes.byteLength })
350 totalPreloadedBytes += bytes.byteLength
351 } else {
352 // Serve large or filtered files on-demand
353 routes[route] = () => {
354 const fileOnDemand = Bun.file(filepath)
355 return new Response(fileOnDemand, {
356 headers: {
357 'Content-Type': metadata.type,
358 'Cache-Control': 'public, max-age=3600',
359 },
360 })
361 }
362β
363 skipped.push(metadata)
364 }
365 } catch (error: unknown) {
366 if (error instanceof Error && error.name !== 'EISDIR') {
367 log.error(`Failed to load ${filepath}: ${error.message}`)
368 }
369 }
370 }
371β
372 // Show detailed file overview only when verbose mode is enabled
373 if (VERBOSE && (loaded.length > 0 || skipped.length > 0)) {
374 const allFiles = [...loaded, ...skipped].sort((a, b) =>
375 a.route.localeCompare(b.route),
376 )
377β
378 // Calculate max path length for alignment
379 const maxPathLength = Math.min(
380 Math.max(...allFiles.map((f) => f.route.length)),
381 60,
382 )
383β
384 // Format file size with KB and actual gzip size
385 const formatFileSize = (bytes: number, gzBytes?: number) => {
386 const kb = bytes / 1024
387 const sizeStr = kb < 100 ? kb.toFixed(2) : kb.toFixed(1)
388β
389 if (gzBytes !== undefined) {
390 const gzKb = gzBytes / 1024
391 const gzStr = gzKb < 100 ? gzKb.toFixed(2) : gzKb.toFixed(1)
392 return {
393 size: sizeStr,
394 gzip: gzStr,
395 }
396 }
397β
398 // Rough gzip estimation (typically 30-70% compression) if no actual gzip data
399 const gzipKb = kb * 0.35
400 return {
401 size: sizeStr,
402 gzip: gzipKb < 100 ? gzipKb.toFixed(2) : gzipKb.toFixed(1),
403 }
404 }
405β
406 if (loaded.length > 0) {
407 console.log('\nπ Preloaded into memory:')
408 console.log(
409 'Path β Size β Gzip Size',
410 )
411 loaded
412 .sort((a, b) => a.route.localeCompare(b.route))
413 .forEach((file) => {
414 const { size, gzip } = formatFileSize(file.size)
415 const paddedPath = file.route.padEnd(maxPathLength)
416 const sizeStr = `${size.padStart(7)} kB`
417 const gzipStr = `${gzip.padStart(7)} kB`
418 console.log(`${paddedPath} β ${sizeStr} β ${gzipStr}`)
419 })
420 }
421β
422 if (skipped.length > 0) {
423 console.log('\nπΎ Served on-demand:')
424 console.log(
425 'Path β Size β Gzip Size',
426 )
427 skipped
428 .sort((a, b) => a.route.localeCompare(b.route))
429 .forEach((file) => {
430 const { size, gzip } = formatFileSize(file.size)
431 const paddedPath = file.route.padEnd(maxPathLength)
432 const sizeStr = `${size.padStart(7)} kB`
433 const gzipStr = `${gzip.padStart(7)} kB`
434 console.log(`${paddedPath} β ${sizeStr} β ${gzipStr}`)
435 })
436 }
437 }
438β
439 // Show detailed verbose info if enabled
440 if (VERBOSE) {
441 if (loaded.length > 0 || skipped.length > 0) {
442 const allFiles = [...loaded, ...skipped].sort((a, b) =>
443 a.route.localeCompare(b.route),
444 )
445 console.log('\nπ Detailed file information:')
446 console.log(
447 'Status β Path β MIME Type β Reason',
448 )
449 allFiles.forEach((file) => {
450 const isPreloaded = loaded.includes(file)
451 const status = isPreloaded ? 'MEMORY' : 'ON-DEMAND'
452 const reason =
453 !isPreloaded && file.size > MAX_PRELOAD_BYTES
454 ? 'too large'
455 : !isPreloaded
456 ? 'filtered'
457 : 'preloaded'
458 const route =
459 file.route.length > 30
460 ? file.route.substring(0, 27) + '...'
461 : file.route
462 console.log(
463 `${status.padEnd(12)} β ${route.padEnd(30)} β ${file.type.padEnd(28)} β ${reason.padEnd(10)}`,
464 )
465 })
466 } else {
467 console.log('\nπ No files found to display')
468 }
469 }
470β
471 // Log summary after the file list
472 console.log() // Empty line for separation
473 if (loaded.length > 0) {
474 log.success(
475 `Preloaded ${String(loaded.length)} files (${(totalPreloadedBytes / 1024 / 1024).toFixed(2)} MB) into memory`,
476 )
477 } else {
478 log.info('No files preloaded into memory')
479 }
480β
481 if (skipped.length > 0) {
482 const tooLarge = skipped.filter((f) => f.size > MAX_PRELOAD_BYTES).length
483 const filtered = skipped.length - tooLarge
484 log.info(
485 `${String(skipped.length)} files will be served on-demand (${String(tooLarge)} too large, ${String(filtered)} filtered)`,
486 )
487 }
488 } catch (error) {
489 log.error(
490 `Failed to load static files from ${clientDirectory}: ${String(error)}`,
491 )
492 }
493β
494 return { routes, loaded, skipped }
495}
496β
497/**
498 * Initialize the server
499 */
500async function initializeServer() {
501 log.header('Starting Production Server')
502β
503 // Load TanStack Start server handler
504 let handler: { fetch: (request: Request) => Response | Promise<Response> }
505 try {
506 const serverModule = (await import(SERVER_ENTRY_POINT)) as {
507 default: { fetch: (request: Request) => Response | Promise<Response> }
508 }
509 handler = serverModule.default
510 log.success('TanStack Start application handler initialized')
511 } catch (error) {
512 log.error(`Failed to load server handler: ${String(error)}`)
513 process.exit(1)
514 }
515β
516 // Build static routes with intelligent preloading
517 const { routes } = await initializeStaticRoutes(CLIENT_DIRECTORY)
518β
519 // Create Bun server
520 const server = Bun.serve({
521 port: SERVER_PORT,
522β
523 routes: {
524 // Serve static assets (preloaded or on-demand)
525 ...routes,
526β
527 // Fallback to TanStack Start handler for all other routes
528 '/*': (req: Request) => {
529 try {
530 return handler.fetch(req)
531 } catch (error) {
532 log.error(`Server handler error: ${String(error)}`)
533 return new Response('Internal Server Error', { status: 500 })
534 }
535 },
536 },
537β
538 // Global error handler
539 error(error) {
540 log.error(
541 `Uncaught server error: ${error instanceof Error ? error.message : String(error)}`,
542 )
543 return new Response('Internal Server Error', { status: 500 })
544 },
545 })
546β
547 log.success(`Server listening on http://localhost:${String(server.port)}`)
548}
549β
550// Initialize the server
551initializeServer().catch((error: unknown) => {
552 log.error(`Failed to start server: ${String(error)}`)
553 process.exit(1)
554})