Angular20 min read
SSR Safe Coding: window/document, localStorage, and TransferState
Write Angular code that works both on server and browser, including data transfer without double-fetch.
Madison Clark
September 13, 2025
5.8k259
SSR changes where your code runs. Some code runs on the server first, then in the browser.
## Problem: window/document not available on server
❌ Bad:
```ts
localStorage.getItem('token');
```
## Solution: check platform
```ts
import { inject, PLATFORM_ID } from '@angular/core';
import { isPlatformBrowser } from '@angular/common';
export class TokenService {
private platformId = inject(PLATFORM_ID);
getToken() {
if (!isPlatformBrowser(this.platformId)) return null;
return localStorage.getItem('token');
}
}
```
## TransferState (avoid double fetching)
When server fetches data, you can reuse it in the browser without fetching again.
Concept:
- server calls API
- saves response to TransferState
- browser reads it and skips duplicate request
This makes SSR fast and efficient.
> Next: Angular deployment strategies, builds, caching, and versioning.
#Angular#SSR#Advanced