الانتقال إلى المحتوى
FrontendAngular· 7 دقائق للقراءة

'window is not defined': Running Browser-Only Code Safely with SSR

With SSR, constructors, field initializers and ngOnInit run on the server too. Move browser-only work into render hooks and platform-specific services instead of guarding it line by line.

ReadIn

مقال كل يوم يفرق معاك

21 نوفمبر 2026
  • كاتب موثّق
  • Angular 22
محتويات المقال

A team adds SSR to an app that has run in browsers for years. The first server render fails with ReferenceError: localStorage is not defined in the theme service, so they wrap that line in isPlatformBrowser(). Then window is not defined comes from a reading-progress bar, then navigator from the analytics service, and each one gets its own check. A week later there are dozens of checks, one of them sits in a template and causes a hydration mismatch on every article page, and the next library upgrade breaks the server again, this time at import, where no check can reach.

The common misconception

The belief: component code is browser code. SSR is an extra step that happens somewhere else, so when a line fails on the server, you fence that one line off with isPlatformBrowser() and move on.

It's a reasonable starting point. For most of an Angular app's life, every line did run in a browser. The error names one global on one line, and wrapping that line makes the error disappear, which feels like a fix. Answers online often show exactly that pattern. What's missing is a picture of what the server actually executes, and without it you guard lines one crash at a time instead of designing for two platforms.

What actually happens

The server runs your whole app

To produce HTML, the server bootstraps the same application in a server runtime such as Node.js. Routes are matched, services created, components constructed, inputs set, ngOnInit called and templates evaluated, just as in the browser. The SSR guide lists what isn't there: browser-specific globals like window, document, navigator and location, and certain properties of HTMLElement. at build time runs the same code too, so a static page has the same constraints as a server-rendered one.

That's why one check per crash never converges. Any code reachable from bootstrap can run on the server: a field initializer, a service constructor, a guard, a pipe. And module-level code runs when the file is imported, before any component exists, so a library that touches window at import time fails before your check could ever run.

Render hooks are the browser-only lifecycle

Angular already has a place for browser-only work. The lifecycle guide says render callbacks "do not run during server-side rendering or during build-time pre-rendering", and the SSR guide recommends for code that relies on browser-specific symbols. afterNextRender() runs once after the next render, which suits a third-party widget or a scroll listener; afterEveryRender() runs after every render, for measurements that must stay current. Both must be called in an injection context, typically the constructor.

TypeScript reading-progress.ts
import { isPlatformBrowser } from '@angular/common';import { Component, inject, OnInit, PLATFORM_ID, signal } from '@angular/core';@Component({  selector: 'app-reading-progress',  template: `<div class="bar" [style.width.%]="percent()"></div>`,})export class ReadingProgress implements OnInit {  private readonly isBrowser = isPlatformBrowser(inject(PLATFORM_ID));  // Missed one: field initializers run on the server too,  // so this line throws "window is not defined" there  private readonly height = window.innerHeight;  readonly percent = signal(0);  ngOnInit() {    if (this.isBrowser) {      // Added after the first crash; never removed on destroy      window.addEventListener('scroll', () => this.percent.set(        (scrollY / (document.body.scrollHeight - this.height)) * 100,      ));    }  }}

The right version has no platform check at all. The server renders the bar at 0%, the browser renders the same markup, and only after that render does the callback attach the listener. The cleanup sits next to the setup, so the listener can't outlive the component.

Platform-specific services instead of checks

Not every difference is about timing. Reading a saved theme is a real question on both platforms with different answers. Here the SSR guide is explicit: prefer platform-specific providers over runtime checks with isPlatformBrowser or isPlatformServer. Components inject one abstraction, and each platform registers its own implementation.

TypeScript key-value-store.ts
import { Injectable } from '@angular/core';// Components inject the capability; each platform provides its ownexport abstract class KeyValueStore {  abstract get(key: string): string | null;}@Injectable()export class BrowserStore implements KeyValueStore {  get(key: string) { return localStorage.getItem(key); }}@Injectable()export class ServerStore implements KeyValueStore {  get(key: string) { return null; } // nothing saved to read during SSR}

Register { provide: KeyValueStore, useClass: BrowserStore } in app.config.ts and the server version in app.config.server.ts, which a CLI project merges on top of the browser config. The server implementation can do better than null, too: the REQUEST token gives it the incoming request, so a theme stored in a cookie can be rendered correctly from the first byte.

isPlatformBrowser() isn't banned. A single check inside one service, for a decision that doesn't change what's rendered, is fine. The problem is using it as the default tool: every check is a branch where the two platforms do different work, and the checks spread to wherever the last crash happened instead of living in one place.

CodeRuns on the server?Runs in the browser?
Module top level, including library importsYesYes
Constructor, field initializers, inject()YesYes
ngOnInit and template bindingsYesYes
afterNextRender() and afterEveryRender() callbacksNoYes
Event handlers such as (click)No, there are no users thereYes

How to apply it in your project

  1. Search for browser globalsLook for window, document, localStorage, sessionStorage, navigator and location in constructors, field initializers, ngOnInit, services, guards and pipes. Each one runs on the server.
  2. Move DOM work into render hooksPut scroll listeners, measurements and widget setup in afterNextRender() or afterEveryRender(), and register their cleanup with DestroyRef.
  3. Put real differences behind providersDefine an abstract service for storage, analytics or anything else that differs, with a browser implementation in app.config.ts and a server one in app.config.server.ts.
  4. Load browser-only libraries lazilyIf a library touches window when it's imported, load it with a dynamic import() inside afterNextRender() instead of a top-level import.

Key takeaways

  • With SSR and prerendering, constructors, field initializers, ngOnInit and services run on the server too.
  • Render hooks such as afterNextRender() are the lifecycle that skips the server.
  • Prefer platform-specific providers to scattered isPlatformBrowser() checks, as the SSR guide advises.
  • Render the same markup on both platforms and enhance it after render; never branch the template on the platform.

📚 المصادر

  1. Authoring server-compatible components — Angular
  2. afterNextRender — Angular
  3. Component lifecycle — Angular
  4. Hydration — Angular

التعليقات (0)