How to configure in Spartacus a different OCC baseUrl in CSR app vs SSR app

Viewed 12

Normally in Spartacus, both SSR and CSR app use the same OCC baseUrl configuration:

   provideConfig(
      backend: {
        occ: {
          baseUrl: 'https://some.baseUrl.com'
        },
      },
    }),

But how to configure a different OCC base url in CSR app vs SSR app?

1 Answers

Instead of providing a static config, you can provide a config factory, which takes the PLATFORM_ID and checks whether it is a browser or not. Then, conditionally, you can return a config chunk with a different OCC base url. See the following example:

import { PLATFORM_ID } from '@angular/core';
import { isPlatformBrowser } from '@angular/common';
import { OccConfig, provideConfigFactory } from '@spartacus/core';

function myOccConfigFactory(): OccConfig {
  const platformId = inject(PLATFORM_ID);
  const isBrowser = isPlatformBrowser(platformId);
  const baseUrl = isBrowser
    ? 'https://baseUrl.for.browser'
    : 'https://baseUrl.for.ssr';

  return { backend: { occ: { baseUrl } } };
}

/* ... */
@NgModule({
  providers: [
    /* ... */,
    provideConfigFactory(myOccConfigFactory),
  ]
})

Note: The technique of using provideConfigFactory with injecting PLATFORM_ID allows for providing any type of Spartacus confiugration (not only the OCC base url) differently in CSR vs SSR.

Related