lostium / ssr-i18n-angular17

This project is a basic example of how to use Server Side Rendering with multi-language (i18n) websites using Angular 17.
17 stars 4 forks source link

Why is $localize.locale Different Between Server and Browser in Angular 17 SSR? #5

Open attalbialami opened 1 month ago

attalbialami commented 1 month ago

Hello @agarciar

I used your project to test Angular 17 with SSR. I added the following code to the AppComponent, then ranpnpm build and pnpm serve:ssr:ssr-i18n-angular17:

  constructor(
    @Inject(LOCALE_ID) public localeId: string,
    @Inject(PLATFORM_ID) private platformId: Object
  ) {
    if (isPlatformBrowser(this.platformId)) {
      console.log('prints only in browser not in server');
      console.log(this.localeId);
      console.log($localize.locale);
    }

    if (isPlatformServer(this.platformId)) {
      console.log('prints only in server not in browser');
      console.log(this.localeId);
      console.log($localize.locale);
    }
  }

When running the project in SSRand visiting the URL http://localhost:4000/en

In the browser console, I see: image

And in the Express server log, I see: image

My question is: Why is $localize.locale on the server set to "de" and different from the one in the browser, which is "en"? Normally, they both should be "en".

Could you please provide some explanation for this discrepancy? Your help is much appreciated.

Thank you.

agarciar commented 1 month ago

Hi @attalbialami,

I don't know the reason, it seems to possibly show the last compiled locale. However, you should always use LOCALE_ID as it is explicitly set in server.ts.

Sorry, I can't give you more information.