server.ts 1.7 KB

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