Implement server-side data prefetching in Angular using TransferState. The server fetches data and embeds it in HTML JSON, and the client reads this on startup to avoid the double-fetch problem.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
This explains how to implement server-side data prefetching in Angular Universal using TransferState by importing ServerTransferStateModule on the server, BrowserTransferStateModule with BrowserModule.withServerTransition on the client, and using a service that stores fetched data on the server in TransferState and reads it on the client to avoid duplicate HTTP calls.
Below is a minimal, practical example of how to fetch data on the server and pass it to the browser via Angular’s TransferState, so the client does not need to re-fetch the same data (“double-fetch problem”).
1. Add SSR and Transfer Modules
Make sure you have Angular Universal set up (e.g., via ng add @nguniversal/express-engine). Then:
In app.module.ts (browser module), import BrowserTransferStateModule.
In app.server.module.ts (server module), import ServerTransferStateModule.
// app.server.module.ts (server)
import { NgModule } from '@angular/core';
import { ServerModule, ServerTransferStateModule } from '@angular/platform-server';
import { AppModule } from './app.module';
import { AppComponent } from './app.component';
@NgModule({
imports: [
AppModule,
ServerModule,
ServerTransferStateModule
],
bootstrap: [AppComponent],
})
export class AppServerModule {}
These modules ensure Angular writes the serialized state into the rendered HTML on the server, and the browser picks it up at bootstrap.
2. Create a Service Using TransferState
This service will:
On the server: fetch data via HttpClient, then set it in the TransferState.
On the browser: check if TransferState already has the data; if yes, return it and remove it from the state to avoid repeated use. If not present, fetch it normally.
ts
// data.service.ts
import { Injectable, Inject, PLATFORM_ID } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { TransferState, makeStateKey } from '@angular/platform-browser';
import { isPlatformServer } from '@angular/common';
import { Observable, of } from 'rxjs';
import { tap } from 'rxjs/operators';
const DATA_KEY = makeStateKey<any>('myData');
@Injectable({ providedIn: 'root' })
export class DataService {
constructor(
private http: HttpClient,
private transferState: TransferState,
@Inject(PLATFORM_ID) private platformId: Object
) {}
getData(): Observable<any> {
// If the client already has the state (from SSR), use it
if (this.transferState.hasKey(DATA_KEY)) {
const data = this.transferState.get(DATA_KEY, null);
this.transferState.remove(DATA_KEY); // optional: clean up
return of(data);
}
// Otherwise, fetch from the API
return this.http.get('/api/data').pipe(
tap(data => {
// Only set the state on the server; it will be serialized into HTML
if (isPlatformServer(this.platformId)) {
this.transferState.set(DATA_KEY, data);
}
})
);
}
}
3. Use the Service in a Component
When the component initializes, it will call getData(). On the server, that fetch will run and set the state. When the app renders on the client, the state is already there, so the browser reads it and skips the network call.
Server render: Angular Universal calls getData(), fetches from /api/data, and stores it in TransferState. The HTML includes a JSON blob containing this data.
Client bootstrap: Angular reads the JSON blob from the HTML, populates TransferState, and when the component calls getData() again, it finds the data in TransferState and uses it, avoiding a second network request.
If you prefer automatic caching of all server-side HttpClient calls, you can also use TransferHttpCacheModule (Angular <16) or the modern HTTP transfer cache feature in Angular 16+. But the above example shows how to do it manually with TransferState.