Sub topic 6
Avoiding duplicate requests with the HTTP transfer cache
This chapter assumes you have SSR and hydration running, as set up in the earlier chapters. It also assumes you know HttpClient basics and how interceptors and dependency injection work. Here you will see why SSR can fetch the same data twice, how Angular prevents that, and how to tune or bypass the mechanism.
The duplicate request problem
When a page renders on the server, components call HttpClient and wait for the responses. The server then serializes the finished HTML and sends it to the browser.
The browser downloads the JavaScript and bootstraps the application again. The same components run again and call the same endpoints. Without help, the browser repeats every request the server already made. This causes three problems:
- It wastes bandwidth and load on your API.
- It delays hydration, because the component waits for data it already showed on screen.
- It can cause a visual flicker or a mismatch if the second response differs from the first.
The fix is to send the server's responses to the browser inside the HTML, and have the browser read them instead of calling the network.
What provideClientHydration gives you
You do not have to enable the transfer cache separately. provideClientHydration() registers an HttpClient interceptor that implements it.
import { ApplicationConfig } from '@angular/core';
import { provideRouter } from '@angular/router';
import { provideHttpClient, withFetch } from '@angular/common/http';
import { provideClientHydration, withEventReplay } from '@angular/platform-browser';
import { routes } from './app.routes';
export const appConfig: ApplicationConfig = {
providers: [
provideRouter(routes),
provideHttpClient(withFetch()),
provideClientHydration(withEventReplay()),
],
};This configuration already has the transfer cache. The mechanism works like this:
- On the server, the interceptor lets each eligible request go through. It stores the response body, status, and URL in
TransferState. - Angular writes
TransferStateinto the HTML as a JSON<script>element with the idng-state. - In the browser,
TransferStateis read from that element before the application starts. - When a component calls
HttpClient, the interceptor builds a cache key. If an entry exists, it returns the stored response without touching the network.
The cache key is made from the HTTP method, the full URL including query parameters, and the response type. The same URL requested as JSON and as text are two separate entries.
The cache lives only until the app is stable
The browser uses cached entries only during the initial load. Once the application reports that it is stable, which means it has no pending tasks such as in-flight requests, the interceptor stops serving from the cache. After that, every request goes to the network.
This design prevents stale data. If the user stays on the page for ten minutes and clicks a link, a request for the same URL fetches fresh data. It also means the cache covers only requests made during bootstrap and the first route activation. A request you fire later from a button click is never cached this way.
What is cached by default
The default rules are conservative:
| Request type | Cached by default | Reason |
|---|---|---|
| `GET` and `HEAD` | Yes | They are safe and repeatable. |
| `POST` and other methods | No | They usually change server state. |
| Requests with an `Authorization` or `Proxy-Authorization` header | No | The response may be user-specific, and it would be embedded in HTML that could be cached by a CDN. |
| Response headers | Not transferred | Only the body, status, and URL are stored. |
The header rule matters for correctness. If the server sent an authenticated response in the HTML and a shared cache stored that HTML, one user's data could reach another user. Treat anything in ng-state as public content, because anyone who can read the page source can read it.
Customizing the cache
Pass withHttpTransferCacheOptions to provideClientHydration to change the global rules.
import { ApplicationConfig } from '@angular/core';
import { provideHttpClient, withFetch } from '@angular/common/http';
import {
provideClientHydration,
withEventReplay,
withHttpTransferCacheOptions,
} from '@angular/platform-browser';
export const appConfig: ApplicationConfig = {
providers: [
provideHttpClient(withFetch()),
provideClientHydration(
withEventReplay(),
withHttpTransferCacheOptions({
includePostRequests: true,
includeHeaders: ['X-Total-Count'],
filter: (req) => !req.url.includes('/api/live'),
}),
),
],
};The available options are:
| Option | Type | Effect |
|---|---|---|
| `includePostRequests` | `boolean` | Also caches `POST` requests. Use it for read-only endpoints that happen to use `POST`, such as a search API. |
| `includeRequestsWithAuthHeaders` | `boolean` | Caches requests that carry authorization headers. Enable it only if you are sure the rendered output is not shared between users. |
| `includeHeaders` | `string[]` | Lists response headers to store in the cache. By default none are stored. |
| `filter` | `(req) => boolean` | Return `false` to exclude a request. It runs for each request that is otherwise eligible. |
If you want to turn the feature off entirely, use withNoHttpTransferCache():
provideClientHydration(withNoHttpTransferCache())Do this only when you have a specific reason, for example when all data comes from a source other than HttpClient.
Controlling a single request
Global options are blunt. For one request, set the transferCache option on the call itself. It overrides the global setting.
import { HttpClient } from '@angular/common/http';
import { Injectable, inject } from '@angular/core';
export interface Product {
id: string;
name: string;
price: number;
}
export interface Stock {
id: string;
available: number;
}
@Injectable({ providedIn: 'root' })
export class ProductService {
private http = inject(HttpClient);
// Cached by default: a plain GET.
getProduct(id: string) {
return this.http.get<Product>(`/api/products/${id}`);
}
// Never cached: stock changes quickly, so the browser must fetch fresh data.
getStock(id: string) {
return this.http.get<Stock>(`/api/stock/${id}`, { transferCache: false });
}
// Cached, and one response header is carried across with the body.
getCatalog() {
return this.http.get<Product[]>('/api/products', {
observe: 'response',
transferCache: { includeHeaders: ['X-Total-Count'] },
});
}
}Setting transferCache: false has a visible effect. The server renders the page with its stock value. The browser then calls the API again during hydration, and the value may change. If the template shows that value, you can get a brief change on screen. Use false for data that must be fresh, and design the template so a change is acceptable.
Without includeHeaders, response.headers.get('X-Total-Count') returns null in the browser when the response came from the cache. This is a common source of bugs that appear only after SSR is enabled, because everything works on the server and in plain client-side rendering.
Sharing other data with TransferState
The HTTP cache only covers HttpClient. Data from other sources has no automatic transfer. Examples are the global fetch, a database client used in server-only code, a WebSocket snapshot, and a value computed during render.
For those, use TransferState directly. It is a key-value store that Angular serializes into the page on the server and restores in the browser.
import { Injectable, TransferState, inject, makeStateKey } from '@angular/core';
const RENDERED_AT = makeStateKey<string>('renderedAt');
@Injectable({ providedIn: 'root' })
export class RenderInfo {
private state = inject(TransferState);
readonly renderedAt: string;
constructor() {
const saved = this.state.get(RENDERED_AT, '');
if (saved) {
// Browser after SSR: reuse the value the server produced.
this.renderedAt = saved;
} else {
// Server, or a client-only render: compute and store it.
this.renderedAt = new Date().toISOString();
this.state.set(RENDERED_AT, this.renderedAt);
}
}
}The service computes the timestamp once on the server and stores it. The browser finds the saved value and uses it, so the text it renders matches the server's HTML. Without this, the browser would compute a different timestamp, and the text would differ from the server markup.
The main methods are:
makeStateKey<T>(name)creates a typed key. The name must be unique across the application.get(key, default)returns the stored value, or the default.set(key, value)stores a value.hasKey(key)checks for a key.remove(key)deletes an entry.
The value must be JSON-serializable. Plain objects, arrays, strings, numbers, and booleans work. Date objects become strings, and class instances lose their methods. Convert before storing and rebuild after reading.
Keep the payload small
Every entry increases the size of the HTML document. A response with 2 MB of JSON adds about 2 MB to every page view, and it cannot be streamed or deferred. Two habits help:
- Have the API return only the fields the page uses, or map the response to a smaller object before returning it from a service. The cache stores the raw HTTP body, so mapping after the call does not shrink the payload. Use an API that returns less, or a custom
TransferStateentry holding the mapped result. - Exclude large, below-the-fold responses with
transferCache: false, or load them in a deferred block.
Common problems
The browser still makes the request. Check these causes in order:
- The request is a
POST, or has anAuthorizationheader, and you have not enabled those options. - The URL differs between server and browser. A relative URL on the server and an absolute URL in the browser produce different keys. Build URLs the same way on both sides.
- The request happens after the app is stable, for example in a click handler or a long timer.
- The request does not use
HttpClient. A directfetch()call bypasses the interceptor. - The query parameters are in a different order or contain a value that changes, such as a timestamp. The key then differs.
Data appears on the server but is empty in the browser. The response was probably excluded by a filter, or the code reads a response header that was not listed in includeHeaders.
Personal data appears in the page source. An authenticated request was included by includeRequestsWithAuthHeaders or a custom TransferState entry. Remove it from the cache, or render that part of the page only in the browser using afterNextRender or a client render mode for the route.
Summary of the decision
- Use the default cache for
GETdata that is the same for every visitor. - Add
includeHeaderswhen your code reads response headers. - Use
transferCache: falsewhen freshness matters more than avoiding a second request. - Use
TransferStatefor data that does not come throughHttpClient. - Keep per-user and sensitive data out of the transferred state.
Exercise
A component calls this.http.post<Result[]>('/api/search', { term }) during initialization. The server renders the results, but the browser sends the same POST again during hydration. Name two ways to stop the duplicate request, and say when each one is appropriate.
Show answer
Option 1: pass withHttpTransferCacheOptions({ includePostRequests: true }) to provideClientHydration. This is appropriate when the POST is a read-only query, such as search, and you want all such requests cached. Option 2: if you do not want a global change, store the result yourself with TransferState, using makeStateKey and set on the server and get in the browser. A filter can narrow the global option so only /api/search is included. Do not enable this for POST requests that change data.
Exercise
Your catalog service calls this.http.get('/api/products', { observe: 'response' }) and shows response.headers.get('X-Total-Count') as the item count. After enabling SSR, the count shows correctly in the server HTML but is empty after hydration. What is the cause and the fix?
Show answer
Response headers are not stored in the transfer cache by default, so the cached response in the browser has no X-Total-Count header and headers.get returns null. Fix it by listing the header, either globally with withHttpTransferCacheOptions({ includeHeaders: ['X-Total-Count'] }) or on that request with transferCache: { includeHeaders: ['X-Total-Count'] }.
Exercise
Why does the transfer cache stop serving entries once the application is stable, and what would go wrong if it kept serving them?
Show answer
The cache exists only to avoid repeating the requests made during the first render. After the app is stable, later requests represent new user actions or navigation. If the cache kept answering them, users would see stale data for as long as the page stayed open, because the entries embedded in the HTML would never refresh.