tezvyn:

Angular TransferState: Avoid Double Data Fetching in SSR

AI-drafted, machine-checkedSource: angular.devadvanced
Angular TransferState: Avoid Double Data Fetching in SSR

TransferState is a key-value cache that bridges your Angular SSR server and the browser, preventing the client from re-fetching data the server already got. Use it to pass resolved API data from the server render to the client, avoiding wasted network calls.

WHY IT EXISTS: In Angular Universal (SSR), the server renders the page, often fetching data via HTTP. When the browser receives the HTML and the Angular app starts (a process called hydration), it would normally re-fetch that same data, causing wasted network calls and a potential content flicker.

THE MENTAL MODEL: Think of TransferState as a sealed bag of data passed from the server to the client. The server performs an expensive task (like an API call), puts the result in the bag, and attaches it to the HTML response. The client app, upon starting, checks the bag first before deciding whether it needs to perform that same task itself.

HOW IT WORKS: On the server, you inject TransferState and use makeStateKey to create a unique, typed key. After an API call resolves, you store the data using transferState.set(YOUR_KEY, data). Angular automatically serializes this state and embeds it within a <script> tag in the initial HTML. On the client, you inject TransferState again. Before making an API call, you first attempt to retrieve the data with transferState.get(YOUR_KEY, null). If it returns data, you use it; if it's null, you proceed with the API call.

WHEN TO USE IT: Use it for any data fetched during the server-side render that is critical for the initial client-side view. This is perfect for content from a CMS, product details on an e-commerce site, or a user's profile information.

WHEN NOT TO USE IT: Avoid using it for data that is not fetched on the server or for extremely large payloads, as it increases the size of the initial HTML document. It's also not suitable for highly volatile data that might be stale by the time the client hydrates.

ONE CANONICAL EXAMPLE: A common pattern is to create an HTTP interceptor. This interceptor checks if a request is running on the server. If so, upon a successful GET response, it stores the response body in TransferState. On the client, the interceptor first checks TransferState for a cached response matching the request URL. If found, it returns the cached data in an Observable and cancels the actual HTTP request, effectively preventing the duplicate call.

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.