server.ts.template 1.6 KB

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