What browser specific APIs commonly cause problems when running Angular code on the server, and how do you handle them safely?
Short answer
APIs that only exist in a browser, like window, document, or localStorage, are not available in the Node.js environment used for server rendering, and accessing them directly will cause errors.
Advertisement
AModel answer
APIs that only exist in a browser, like window, document, or localStorage, are not available in the Node.js environment used for server rendering, and accessing them directly will cause errors. You check whether the code is running in a browser using Angular's platform detection tools before accessing these APIs.
import { isPlatformBrowser } from '@angular/common';
import { PLATFORM_ID, inject } from '@angular/core';
constructor() {
const platformId = inject(PLATFORM_ID);
if (isPlatformBrowser(platformId)) {
localStorage.setItem('key', 'value');
}
}Real-world example
A component that reads the user's saved theme preference from localStorage checks isPlatformBrowser first, avoiding a server crash during rendering since localStorage does not exist in the Node.js server environment at all.
Likely follow-ups
- What other common browser only APIs besides localStorage often cause this same problem?
- How would you provide a safe fallback value when running on the server instead of just skipping the code entirely?
Related topics