Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

The "window is not defined" error occurs in Angular Server-Side Rendering (SSR) when a module or component tries to access the global "window" object, which is not available in the Node.js environment. Here are some ways to resolve this error:

  1. Use the typeof operator to check whether "window" is defined or not before using it. For example:

if (typeof window !== 'undefined') { // Use window object methods or properties here }

  1. Use the platform-browser module from '@angular/platform-browser' to import the Window object in the component or service. For example:

import { Component, Inject } from '@angular/core'; import { WINDOW } from '@angular/common'; @Component({ selector: 'app-root', template: 'My app', }) export class AppComponent { constructor(@Inject(WINDOW) private window: Window) {} }

  1. Use a browser-specific library or module like 'jsdom' or 'domino' to simulate the browser environment in Node.js. For example:

const { JSDOM } = require('jsdom'); const { window } = new JSDOM(); global.window = window; global.document = window.document;

The global object makes the Window object available globally for SSR.