// Plain Node server (no Express) for a built single-page app, e.g. a Vite `dist/` folder. // Crawlers get the page rendered by Prebaked through the official prerender-node middleware, // with a 10 s time limit (prerender-timeout.cjs); everyone else gets the files in `dist/`. // // npm install prerender-node // PREBAKED_TOKEN= node server.mjs // // Needs prerender-timeout.cjs next to this file. Optional env: PORT (3000), DIST_DIR (dist). import { createReadStream, statSync } from 'node:fs'; import { createServer } from 'node:http'; import { extname, join, normalize, resolve, sep } from 'node:path'; import prerender from 'prerender-node'; import { withTimeout } from './prerender-timeout.cjs'; const DIST = resolve(process.env.DIST_DIR ?? 'dist'); const PORT = Number(process.env.PORT ?? 3000); const TYPES = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8', '.json': 'application/json', '.svg': 'image/svg+xml', '.png': 'image/png', '.jpg': 'image/jpeg', '.webp': 'image/webp', '.ico': 'image/x-icon', '.woff2': 'font/woff2', '.txt': 'text/plain; charset=utf-8', '.xml': 'application/xml', }; prerender .set('prerenderServiceUrl', process.env.PREBAKED_SERVICE_URL ?? 'https://service.prebaked.io/') .set('prerenderToken', process.env.PREBAKED_TOKEN) // Prebaked errors serve your own page; only the rendered page's own status reaches crawlers. .set('afterRender', (err, req, prerenderRes) => { const status = prerenderRes?.statusCode ?? 0; const pageStatus = (status >= 200 && status < 400) || status === 404 || status === 410; if (err || !pageStatus) return { cancelRender: true }; }) .addUserAgents(['OAI-SearchBot', 'ClaudeBot', 'Claude-User', 'Claude-SearchBot', 'meta-externalagent']); const prebaked = withTimeout(prerender, { timeoutMs: 10_000 }); /** A file inside DIST, or null. */ function fileFor(urlPath) { let path; try { path = normalize(join(DIST, decodeURIComponent(urlPath))); } catch { return null; } if (path !== DIST && !path.startsWith(DIST + sep)) return null; try { return statSync(path).isFile() ? path : null; } catch { return null; } } /** Static files from DIST; every other path gets index.html (SPA routes). */ function serveDist(req, res) { const urlPath = new URL(req.url, 'http://localhost').pathname; const file = fileFor(urlPath) ?? join(DIST, 'index.html'); res.writeHead(200, { 'Content-Type': TYPES[extname(file)] ?? 'application/octet-stream' }); if (req.method === 'HEAD') return res.end(); createReadStream(file).pipe(res); } createServer((req, res) => { prebaked(req, res, (err) => { if (err) console.error(err); serveDist(req, res); }); }).listen(PORT, () => console.log(`http://localhost:${PORT}`));