
'window is not defined': Running Browser-Only Code Safely with SSR
- كاتب موثّق
- Angular 22
محتويات المقال
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
isPlatformBrowser() and move on.
What actually happens
The server runs your whole app
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.
window at import time fails before your check could ever run.
Render hooks are the browser-only lifecycle
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.
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, )); } }}import { afterNextRender, Component, DestroyRef, inject, signal,} from '@angular/core';@Component({ selector: 'app-reading-progress', template: `<div class="bar" [style.width.%]="percent()"></div>`,})export class ReadingProgress { // Rendered as 0 on the server and on the first browser render readonly percent = signal(0); constructor() { const destroyRef = inject(DestroyRef); // Browser only, after rendering: window and layout are safe here afterNextRender(() => { const onScroll = () => { const max = document.body.scrollHeight - window.innerHeight; this.percent.set(max > 0 ? (window.scrollY / max) * 100 : 0); }; window.addEventListener('scroll', onScroll); destroyRef.onDestroy(() => window.removeEventListener('scroll', onScroll)); }); }}Platform-specific services instead of checks
isPlatformBrowser or isPlatformServer. Components inject one abstraction, and each platform registers its own implementation.
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}{ 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.
inject() | ||
ngOnInit and template bindings | ||
afterNextRender() and afterEveryRender() callbacks | ||
(click) |
How to apply it in your project
Search for browser globals Look for window,document,localStorage,sessionStorage,navigatorandlocationin constructors, field initializers,ngOnInit, services, guards and pipes. Each one runs on the server.Move DOM work into render hooks Put scroll listeners, measurements and widget setup in afterNextRender()orafterEveryRender(), and register their cleanup withDestroyRef.Put real differences behind providers Define an abstract service for storage, analytics or anything else that differs, with a browser implementation in app.config.tsand a server one inapp.config.server.ts.Load browser-only libraries lazily If a library touches windowwhen it's imported, load it with a dynamicimport()insideafterNextRender()instead of a top-level import.
Key takeaways
With SSR and prerendering, constructors, field initializers, ngOnInitand 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.
التعليقات (0)