# Angular SSR: ReferenceError: window is not defined / document is not defined / localStorage is not defined

**Code:** `window is not defined` · **Category:** Angular · **Seen on:** Angular, Node.js, TypeScript

Code that only works in a browser ran during server-side rendering, where `window`, `document` and `localStorage` do not exist.

## Meaning

Angular SSR renders on Node. Browser globals are unavailable there. Wrap browser-only code with `isPlatformBrowser`, run it in `afterNextRender`, inject `DOCUMENT` instead of using `document` directly, and use abstractions for storage. Libraries that touch `window` at import time need lazy import or an SSR-safe alternative.

## Common causes

- Direct use of `window`, `document`, `localStorage` or `navigator` in components/services
- Third-party library accessing `window` on import
- Code in constructors or `ngOnInit` running on the server
- Using `ElementRef.nativeElement` APIs that need a real DOM
- Missing platform check around analytics/maps/charts

## Quick fix

1. Guard with `isPlatformBrowser(inject(PLATFORM_ID))`
2. Move DOM work to `afterNextRender()`
3. Inject `DOCUMENT` instead of the global `document`

## Detailed fix by platform

### Angular

1. `private platformId = inject(PLATFORM_ID); if (isPlatformBrowser(this.platformId)) { localStorage.setItem('k', 'v'); }`
2. `afterNextRender(() => { this.chart = new Chart(...); });`

## Code examples

### Browser-only code

```typescript
import { PLATFORM_ID, afterNextRender, inject } from '@angular/core';
import { isPlatformBrowser } from '@angular/common';

export class ThemeService {
  private platformId = inject(PLATFORM_ID);
  load() {
    if (isPlatformBrowser(this.platformId)) {
      return localStorage.getItem('theme');   // only runs in the browser
    }
    return null;
  }
}
```

## How to diagnose

1. **Global** — Which global is undefined?
2. **Source** — Own code or a library import?
3. **Timing** — Runs at construction or after render?

---
Source: [WhatIsMyError](https://whatismyerror.com/errors/angular/ssr-window-is-not-defined)
