Search code examples
angularexpressserver-side-rendering

How to use express with Angular serverside rendering?


I give a try to the Angular's Server Side Rendering and getting stuck to the simplest use case I imagined.

Tests

Test 1

  • Expected behavior : Using express to shortcut the angular app by only returning a "welcome object"
  • Actual behavior : Angular app is normally rendered

Test 2

  • Expected behavior : 'toto' endpoint say 'toto'
  • Actual behavior : Angular router cannot match this route.

Way to reproduce

  1. Run ng new --ssr (by runing this, I consider that express server will be well configured by default)
  2. In the server.ts file, replace the server.get('*', (req, res, next) => { /* content */ }); content (Angular app) by res.send({msg: "welcome"});
  3. Run ng serve
  4. Run curl http://localhost:4200 I'm getting default Angular homepage, but I expected to receive the {msg: "welcome"} object
  5. In the server.ts file, add the following basic endpoint and ng serve again
  server.get('/toto', async (req, res) => {
    res.send({msg: "toto"})
  });
  1. Run curl http://localhost:4200/toto The Angular Router answers me, not Express

Result

From these two tests, it seems that express impl from server.ts is completely skipped.

I probably missed something obvious but Angular doc, Express doc or just googling don't give me any clue...

In angular.json, the server.ts is correctly specified projects.latest-ng.architect.build.options.ssr.entry: "server.ts", there's no compilation issue.

Does anyone have any idea what's wrong?


Solution

  • ng serve doesn't use server.ts (it doesn't use express.) You have to build your app with production configuration and run your created server.mjs file with node. With this way your application will use server.te file.