|
| 1 | +import { APP_BASE_HREF } from '@angular/common'; |
| 2 | +import { CommonEngine } from '@angular/ssr/node'; |
| 3 | +import express from 'express'; |
| 4 | +import { fileURLToPath } from 'node:url'; |
| 5 | +import { dirname, join, resolve } from 'node:path'; |
| 6 | +import bootstrap from './src/main.server'; |
| 7 | + |
| 8 | +// The Express app is exported so that it can be used by serverless Functions. |
| 9 | +export function app(): express.Express { |
| 10 | + const server = express(); |
| 11 | + const serverDistFolder = dirname(fileURLToPath(import.meta.url)); |
| 12 | + const browserDistFolder = resolve(serverDistFolder, '../browser'); |
| 13 | + const indexHtml = join(serverDistFolder, 'index.server.html'); |
| 14 | + |
| 15 | + const commonEngine = new CommonEngine(); |
| 16 | + |
| 17 | + server.set('view engine', 'html'); |
| 18 | + server.set('views', browserDistFolder); |
| 19 | + |
| 20 | + // Example Express Rest API endpoints |
| 21 | + // server.get('/api/**', (req, res) => { }); |
| 22 | + // Serve static files from /browser |
| 23 | + server.get('**', express.static(browserDistFolder, { |
| 24 | + maxAge: '1y', |
| 25 | + index: 'index.html', |
| 26 | + })); |
| 27 | + |
| 28 | + // All regular routes use the Angular engine |
| 29 | + server.get('**', (req, res, next) => { |
| 30 | + const { protocol, originalUrl, baseUrl, headers } = req; |
| 31 | + |
| 32 | + commonEngine |
| 33 | + .render({ |
| 34 | + bootstrap, |
| 35 | + documentFilePath: indexHtml, |
| 36 | + url: `${protocol}://${headers.host}${originalUrl}`, |
| 37 | + publicPath: browserDistFolder, |
| 38 | + providers: [{ provide: APP_BASE_HREF, useValue: baseUrl }], |
| 39 | + }) |
| 40 | + .then((html) => res.send(html)) |
| 41 | + .catch((err) => next(err)); |
| 42 | + }); |
| 43 | + |
| 44 | + return server; |
| 45 | +} |
| 46 | + |
| 47 | +function run(): void { |
| 48 | + const port = process.env['PORT'] || 4000; |
| 49 | + |
| 50 | + // Start up the Node server |
| 51 | + const server = app(); |
| 52 | + server.listen(port, () => { |
| 53 | + console.log(`Node Express server listening on http://localhost:${port}`); |
| 54 | + }); |
| 55 | +} |
| 56 | + |
| 57 | +run(); |
0 commit comments