Tim
Tim

Reputation: 386

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

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?

Upvotes: 1

Views: 1612

Answers (2)

Kent Leow
Kent Leow

Reputation: 1

Yes, you're right, there's a globally declared function used window for something.

For me, I solved it by adding this chunk of code in app.component.ts

// add this
if (globalThis.window === undefined) {
  globalThis.window =
    ({
      addEventListener: () => {},
      // add more methods as you wish
    } as never);
}

// app.component.ts
@Component({
  selector: 'app-root',
  standalone: true,
  templateUrl: './app.component.html',
  styleUrl: './app.component.css',
  imports: [...],
})

This is not a perfect way or correct solution, but serve as a temporary workaround to get through the blocker. By this, when there's no defined window, we will assign a new window object for it. If there's any window's methods required, we can add it into the object we defined.

Upvotes: 0

codeandcloud
codeandcloud

Reputation: 55200

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
}

Upvotes: 1

Related Questions