server.ts 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import {
  2. AngularNodeAppEngine,
  3. createNodeRequestHandler,
  4. isMainModule,
  5. writeResponseToNodeResponse,
  6. } from '@angular/ssr/node';
  7. import express from 'express';
  8. import { dirname, resolve } from 'node:path';
  9. import { fileURLToPath } from 'node:url';
  10. const serverDistFolder = dirname(fileURLToPath(import.meta.url));
  11. const browserDistFolder = resolve(serverDistFolder, '../browser');
  12. const app = express();
  13. const angularApp = new AngularNodeAppEngine();
  14. /**
  15. * Example Express Rest API endpoints can be defined here.
  16. * Uncomment and define endpoints as necessary.
  17. *
  18. * Example:
  19. * ```ts
  20. * app.get('/api/**', (req, res) => {
  21. * // Handle API request
  22. * });
  23. * ```
  24. */
  25. /**
  26. * Serve static files from /browser
  27. */
  28. app.use(
  29. express.static(browserDistFolder, {
  30. maxAge: '1y',
  31. index: false,
  32. redirect: false,
  33. }),
  34. );
  35. /**
  36. * Handle all other requests by rendering the Angular application.
  37. */
  38. app.use('/**', (req, res, next) => {
  39. angularApp
  40. .handle(req)
  41. .then((response) =>
  42. response ? writeResponseToNodeResponse(response, res) : next(),
  43. )
  44. .catch(next);
  45. });
  46. /**
  47. * Start the server if this module is the main entry point.
  48. * The server listens on the port defined by the `PORT` environment variable, or defaults to 4000.
  49. */
  50. if (isMainModule(import.meta.url)) {
  51. const port = process.env['PORT'] || 4000;
  52. app.listen(port, () => {
  53. console.log(`Node Express server listening on http://localhost:${port}`);
  54. });
  55. }
  56. /**
  57. * The request handler used by the Angular CLI (dev-server and during build).
  58. */
  59. export const reqHandler = createNodeRequestHandler(app);