Angular › Server-Side Rendering with Angular Universal

How do you fetch data on the server before rendering a page with Angular Universal?

Intermediate

Answer

You use Angular's TransferState feature together with your normal data fetching services, letting data fetched during server rendering be passed along to the browser, so the client does not need to make the exact same request again once the app finishes hydrating.
import { TransferState, makeStateKey } from '@angular/core';

const USER_KEY = makeStateKey<User>('user');

constructor(private state: TransferState, private http: HttpClient) {
  const cached = this.state.get(USER_KEY, null);
  if (cached) {
    this.user = cached;
  } else {
    this.http.get<User>('/api/user').subscribe((user) => {
      this.user = user;
      this.state.set(USER_KEY, user);
    });
  }
}
Real-world example A profile page avoids fetching the same user data twice, once on the server during rendering and again on the client during hydration, by using TransferState to pass the already fetched data along to the browser.

Common follow-ups: What happens to data stored in TransferState after hydration completes?;Why does avoiding a duplicate fetch matter for both performance and cost?