Angular 17 SSR Express Server Providers

1k Views Asked by At

I tried to share my request and response object to the angular application by defining Providers in the "server.ts" file.
Anyway, by injecting them into the app.component they are always undefined no matter if i am in the server or client context.

Does anybody know how to fix this behaviour? Sadly there isn't much information about it.

I didn't run the app in dev mode since angular currently ignores server.ts in devmode! - i builded it and served the express erver.

My tokens look like this:

export const REQUEST = new InjectionToken<Request>('REQUEST');
export const RESPONSE = new InjectionToken<Response>('RESPONSE');

My server looks like this:

  // All regular routes use the Angular engine
  server.get('*', (req, res, next) => {
    console.log('HI HI HI hi');
    const { protocol, originalUrl, baseUrl, headers } = req;
    /*const transferState = inject(TransferState);
    transferState.set(makeStateKey<any>('t'), JSON.stringify('hi'));*/
    commonEngine
      .render({
        bootstrap,
        documentFilePath: indexHtml,
        url: `${protocol}://${headers.host}${originalUrl}`,
        publicPath: browserDistFolder,
        providers: [
          { provide: RESPONSE, useValue: res },
          { provide: REQUEST, useValue: req }
          ],
      })
      .then((html) => res.send(html))
      .catch((err) => next(err));
  });

My Client Injects the Injects the response object

  constructor(@Optional() @Inject(RESPONSE) private response: Response) {
    super();
  }
  ngOnClientInit() {
    console.log('RESPONSE', this.response);
    console.log('I am on client', this.communicationService.getValue('data'), this.token);
  }

No matter what i try, my Response is always null.

I googled and read the official documentation .

I am expecting the token to return a value!

2

There are 2 best solutions below

1
On

This is a known issue. ATM the devServer doesn't rely on the server.ts config.

0
On

Disable prerender and works perfectly