server.ts.template 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import { APP_BASE_HREF } from '@angular/common';
  2. import { CommonEngine, isMainModule } from '@angular/ssr/node';
  3. import express from 'express';
  4. import { dirname, join, resolve } from 'node:path';
  5. import { fileURLToPath } from 'node:url';
  6. import <% if (isStandalone) { %>bootstrap<% } else { %>AppServerModule<% } %> from './main.server';
  7. const serverDistFolder = dirname(fileURLToPath(import.meta.url));
  8. const browserDistFolder = resolve(serverDistFolder, '../<%= browserDistDirectory %>');
  9. const indexHtml = join(serverDistFolder, 'index.server.html');
  10. const app = express();
  11. const commonEngine = new CommonEngine();
  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/**', (req, res) => {
  19. * // Handle API request
  20. * });
  21. * ```
  22. */
  23. /**
  24. * Serve static files from /<%= browserDistDirectory %>
  25. */
  26. app.get(
  27. '**',
  28. express.static(browserDistFolder, {
  29. maxAge: '1y',
  30. index: 'index.html'
  31. }),
  32. );
  33. /**
  34. * Handle all other requests by rendering the Angular application.
  35. */
  36. app.get('**', (req, res, next) => {
  37. const { protocol, originalUrl, baseUrl, headers } = req;
  38. commonEngine
  39. .render({
  40. <% if (isStandalone) { %>bootstrap<% } else { %>bootstrap: AppServerModule<% } %>,
  41. documentFilePath: indexHtml,
  42. url: `${protocol}://${headers.host}${originalUrl}`,
  43. publicPath: browserDistFolder,
  44. providers: [{ provide: APP_BASE_HREF, useValue: baseUrl }],
  45. })
  46. .then((html) => res.send(html))
  47. .catch((err) => next(err));
  48. });
  49. /**
  50. * Start the server if this module is the main entry point.
  51. * The server listens on the port defined by the `PORT` environment variable, or defaults to 4000.
  52. */
  53. if (isMainModule(import.meta.url)) {
  54. const port = process.env['PORT'] || 4000;
  55. app.listen(port, () => {
  56. console.log(`Node Express server listening on http://localhost:${port}`);
  57. });
  58. }
  59. export default app;