Skip to content
tezvyn:
Menu

Angular: Run Code Only on Browser or Server

Source: angular.devMediumHow cards are made

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.

Interview question

In an Angular Universal application, which task most critically requires using isPlatformBrowser to prevent server-side rendering issues?

  • a.Injecting a custom service into a component's constructor.
  • b.Displaying dynamic data in a component template using interpolation.
  • c.Storing user preferences in localStorage or directly manipulating the document object.Correct
  • d.Making an HTTP GET request to fetch data from a backend API.
Why?

The correct answer C involves browser-specific APIs (localStorage, document) which are unavailable in a server environment and would cause a crash during SSR without the isPlatformBrowser guard. Options A, B, and D describe standard Angular features (HTTP requests, template rendering, dependency injection) that are designed to be platform-agnostic and do not require this check.

Just read this? Test yourself on what you have been reading.

Read the original → angular.dev

Put your scrolling time to good use

Learn one idea, try a quiz and save useful cards for revision. Tezvyn makes it easy to learn and stay current in your tech field, a few minutes at a time.

The iPhone app is on the way

We are building it. Until it lands, nothing here is held back from you: every interview card, your saved cards, streaks and the job board all work in Safari, plus hundreds of free practice quizzes of thirty questions each. Sign in and it all carries over to the app the day it arrives.

Want it as an icon? Tap Share at the bottom of Safari, then Add to Home Screen. It opens full screen and the cards you have read stay available offline.

Get it on Google PlayiPhone app coming soon

We are hiring for this. Open roles that interview on angular — each one lists the topics its interview covers.

See open roles