Pierre Taquet
Pierre Taquet

Reputation: 121

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

Test 2

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?

Upvotes: 2

Views: 1084

Answers (3)

Daih1985
Daih1985

Reputation: 46

The Angular team announced that they plan to fix this issue with Angular 18 coming May 2024

https://github.com/angular/angular-cli/issues/26323#issuecomment-1971390348

Upvotes: 0

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.

Upvotes: 2

Matthieu Riegler
Matthieu Riegler

Reputation: 55544

If you're on Angular v17, the devServer will not use the express config in server.ts. It will only be used in prod

You can track this issue on the CLI repo for updates on that topic.

Upvotes: 2

Related Questions