Error in Angular Server-Side Rendering (SSR) with ngx-leaflet: "ReferenceError: window is not defined"

615 Views Asked by At

I am encountering an issue with Angular v17 Server-Side Rendering (SSR) and the ngx-leaflet library in my Angular application. When trying to run the application in an SSR environment, I am getting the following error after build and before prerendering :

"ReferenceError: window is not defined"

I know it's because window isn't accessible on the server side, but I don't use the window object, I think it's due to the use of a function in the library that uses window.

Any idea how to find where to fix it?

1

There are 1 best solutions below

3
On

Try this.

@if(showLeaflet) {
<div style="height: 300px;"
     leaflet 
     [leafletOptions]="options">
</div>
}

Code-behind

platformId = inject(PLATFORM_ID);
showLeaflet = false;
//...
ngOnInit() {
  if (isPlatformBrowser(this.platformId)) {
    showLeaflet  = true;
  }
}

Generally,

If you are inside a component, use afterNextRender

afterNextRender(() => {
  //access window, localStorage, sessionStorage
}, {phase: AfterRenderPhase.Read});

If not(when in services, guards, etc...) use isPlatformBrowser

platformId = inject(PLATFORM_ID);
// ...
if (isPlatformBrowser(this.platformId)) {
  //access window, localStorage, sessionStorage
}