Angular: Run Code Only on Browser or Server

Angular Universal runs your app twice: on a server and in a browser. Use `isPlatformBrowser` to run code only where it's safe, like accessing `window` or `document`, to prevent your server-side render from crashing.
WHY IT EXISTS Angular Universal improves performance and SEO by rendering pages on a server before sending them to the client. However, a server environment like Node.js has no concept of a browser's window or document objects. Code that tries to access these globals will crash during server-side rendering (SSR). A mechanism was needed to differentiate between the two environments.
THE MENTAL MODEL An Angular Universal component is like a script for a play that's performed twice. The first performance is a 'dress rehearsal' on the server stage, which has no real windows or interactive props. The second is the 'live show' in the browser with a full set. isPlatformBrowser is a stage direction in your script telling an actor, "Only perform this action during the live show."
HOW IT WORKS You inject a special token, PLATFORM_ID, into your component or service. You then pass this token to the isPlatformBrowser() function from @angular/common. It returns a boolean: true if the code is running in a browser, false otherwise. You use this boolean in an if statement to guard your platform-specific code, typically inside lifecycle hooks like ngOnInit or ngAfterViewInit.
WHEN TO USE IT Use this check anytime you need to access browser-global objects like window, document, localStorage, or navigator. It's also critical when initializing third-party libraries that directly manipulate the DOM (like charting or animation libraries) and are not 'SSR-aware'.
WHEN NOT TO USE IT You don't need it for most standard Angular logic. Component templates, data binding, dependency injection, and HTTP requests via HttpClient are platform-agnostic by design. Only use it for direct, un-abstracted access to the host environment's APIs.
ONE CANONICAL EXAMPLE A common use case is accessing localStorage. First, inject the platform identifier in your component's constructor: constructor(@Inject(PLATFORM_ID) private platformId: object). Then, in a method like ngOnInit, you create a conditional block: if (isPlatformBrowser(this.platformId)) { ... }. Inside this if block, you can safely write code like localStorage.setItem('user-theme', 'dark'); knowing it will only execute in a browser environment and not crash the server.
Read the original → angular.dev
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.