import path from 'path'; import { FastifyPluginAsync } from 'fastify'; export const fastifyRenderRouter: FastifyPluginAsync<{ isProduction?: boolean; }> = async (app, { isProduction = false }) => { const vite = await import('vite'); const { createPageRenderer } = await import('vite-plugin-ssr'); await app.register(import('@fastify/express')); app.register(import('@fastify/compress'), { global: false }); const ROOT = path.join(__dirname, '..'); const viteDevServer = await vite.createServer({ root: ROOT, server: { middlewareMode: 'ssr' }, }); app.use(viteDevServer.middlewares); const renderPage = createPageRenderer({ viteDevServer, isProduction, root: ROOT, }); app.get('*', async (req, res) => { const url = req.raw.url || req.url; const pageContextInit = { url, }; const pageContext = await renderPage(pageContextInit); const { httpResponse } = pageContext; if (!httpResponse) return; const { body, statusCode, contentType } = httpResponse; res.status(statusCode).type(contentType).compress(body); }); }; async function main() { const { default: fastify } = await import('fastify'); const app = fastify(); app.register(fastifyRenderRouter); app.listen(3000); } if (require.main === module) { main(); }