import { AngularNodeAppEngine, createNodeRequestHandler, isMainModule, writeResponseToNodeResponse, } from '@angular/ssr/node'; import * as http from 'node:http'; /** * Lazily instantiate AngularNodeAppEngine so the engine boots only when * the first request arrives. All routes use RenderMode.Server — every * request triggers on-demand SSR that fetches fresh API data before rendering. */ let appEngine: AngularNodeAppEngine | null = null; function getEngine(): AngularNodeAppEngine { if (!appEngine) { appEngine = new AngularNodeAppEngine(); } return appEngine; } /** * Handle incoming requests using the Angular SSR engine. * Every request is rendered on the server with fresh data from the API. */ const requestHandler = createNodeRequestHandler(async (req, res, next) => { try { const response = await getEngine().handle(req); if (response) { await writeResponseToNodeResponse(response, res); } else { next(); } } catch (error) { next(error); } }); export default requestHandler; if (isMainModule(import.meta.url)) { const httpServer = http.createServer(); httpServer.on('request', async (req: http.IncomingMessage, res: http.ServerResponse) => { requestHandler(req, res, () => { res.statusCode = 404; res.end('Not Found'); }); }); httpServer.listen(4200, () => { console.log(`Node SSR server listening on http://localhost:4200`); }); }