This is a great question about implementing server-side data prefetching in Angular using TransferState to solve the double-fetch problem. Let me provide a comprehensive guide with practical examples.
The TransferState API in Angular is designed to transfer state from the server to the client during Server-Side Rendering (SSR). This avoids the double-fetch problem where:
- Server fetches data and renders the page
- Client-side Angular app starts and fetches the same data again
Here's what I need to cover:
- Basic TransferState setup
- Server-side data fetching and storage in TransferState
- Client-side retrieval from TransferState
- HTTP Interceptor to handle automatic state management
- Complete working examples
- Best practices
Let me create a comprehensive implementation:
Server-Side Data Prefetching in Angular with TransferState
I'll guide you through implementing TransferState to eliminate the double-fetch problem in Server-Side Rendering (SSR).
1. Core Setup & Configuration
Install Dependencies
npm install @angular/platform-server @nguniversal/express-engine
Module Configuration
app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule, BrowserTransferStateModule } from '@angular/platform-browser';
import { TransferHttpCacheModule } from '@nguniversal/common';
import { AppComponent } from './app.component';
import { HttpClientModule } from '@angular/common/http';
@NgModule({
declarations: [AppComponent],
imports: [
BrowserModule.withServerTransition({ appId: 'myApp' }),
BrowserTransferStateModule,
TransferHttpCacheModule, // Automatic HTTP caching
HttpClientModule,
],
providers: [],
bootstrap: [AppComponent],
})
export class AppModule {}
app.server.module.ts
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 {}
2. Service Layer with TransferState
data.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { TransferState, makeStateKey } from '@angular/platform-browser';
import { Observable, of } from 'rxjs';
import { tap } from 'rxjs/operators';
export interface User {
id: number;
name: string;
email: string;
}
export interface Product {
id: number;
title: string;
price: number;
description: string;
}
// Create unique keys for each data type
const USERS_STATE_KEY = makeStateKey<User[]>('users');
const PRODUCTS_STATE_KEY = makeStateKey<Product[]>('products');
@Injectable({
providedIn: 'root',
})
export class DataService {
constructor(
private http: HttpClient,
private transferState: TransferState
) {}
// Fetch users with caching
getUsers(): Observable<User[]> {
// Check if data already exists in TransferState
const cachedUsers = this.transferState.get<User[]>(USERS_STATE_KEY, null);
if (cachedUsers) {
console.log('✓ Users loaded from TransferState');
return of(cachedUsers);
}
console.log('✓ Fetching users from server');
return this.http.get<User[]>('/api/users').pipe(
tap(users => {
// Store the data in TransferState
this.transferState.set(USERS_STATE_KEY, users);
})
);
}
// Fetch products with caching
getProducts(): Observable<Product[]> {
const cachedProducts = this.transferState.get<Product[]>(
PRODUCTS_STATE_KEY,
null
);
if (cachedProducts) {
console.log('✓ Products loaded from TransferState');
return of(cachedProducts);
}
console.log('✓ Fetching products from server');
return this.http.get<Product[]>('/api/products').pipe(
tap(products => {
this.transferState.set(PRODUCTS_STATE_KEY, products);
})
);
}
// Clear specific cache
clearCache(key: any): void {
this.transferState.remove(key);
}
}
// Export keys for use in other services
export { USERS_STATE_KEY, PRODUCTS_STATE_KEY };
3. Custom HTTP Interceptor
transfer-state.interceptor.ts
import { Injectable } from '@angular/core';
import {
HttpInterceptor,
HttpRequest,
HttpHandler,
HttpEvent,
} from '@angular/common/http';
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';
import { TransferState, makeStateKey } from '@angular/platform-browser';
@Injectable()
export class TransferStateInterceptor implements HttpInterceptor {
constructor(private transferState: TransferState) {}
intercept(
req: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
// Only cache GET requests
if (req.method !== 'GET') {
return next.handle(req);
}
// Create a unique key based on the URL
const key = makeStateKey(req.url);
const cached = this.transferState.get(key, null);
if (cached) {
return of(new HttpResponse({ body: cached, status: 200 }));
}
return next.handle(req).pipe(
tap(event => {
if (event instanceof HttpResponse) {
// Store the response in TransferState
this.transferState.set(key, event.body);
}
})
);
}
}
// Add to app.module.ts providers:
// import { HTTP_INTERCEPTORS } from '@angular/common/http';
// {
// provide: HTTP_INTERCEPTORS,
// useClass: TransferStateInterceptor,
// multi: true,
// }
4. Component Usage
app.component.ts
import { Component, OnInit } from '@angular/core';
import { DataService, User, Product } from './data.service';
@Component({
selector: 'app-root',
template: `
<div class="container">
<h1>TransferState Data Prefetching</h1>
<!-- Users Section -->
<section>
<h2>Users</h2>
<div *ngIf="loading$ | async; else usersList">
<p>Loading users...</p>
</div>
<ng-template #usersList>
<div *ngIf="users$ | async as users; else noUsers">
<ul>
<li *ngFor="let user of users">
<strong>{{ user.name }}</strong> - {{ user.email }}
</li>
</ul>
</div>
<ng-template #noUsers>
<p>No users found.</p>
</ng-template>
</ng-template>
</section>
<!-- Products Section -->
<section>
<h2>Products</h2>
<div *ngIf="productsLoading$ | async; else productsList">
<p>Loading products...</p>
</div>
<ng-template #productsList>
<div *ngIf="products$ | async as products; else noProducts">
<div class="product-grid">
<div *ngFor="let product of products" class="product-card">
<h3>{{ product.title }}</h3>
<p>{{ product.description }}</p>
<p class="price">${{ product.price }}</p>
</div>
</div>
</div>
<ng-template #noProducts>
<p>No products found.</p>
</ng-template>
</ng-template>
</section>
</div>
`,
styles: [`
.container {
max-width: 1200px;
margin: 0 auto;
padding: 20px;
}
section {
margin-bottom: 40px;
padding: 20px;
border: 1px solid #ddd;
border-radius: 8px;
}
ul {
list-style: none;
padding: 0;
}
li {
padding: 10px;
border-bottom: 1px solid #eee;
}
.product-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
gap: 20px;
}
.product-card {
border: 1px solid #ddd;
padding: 15px;
border-radius: 8px;
}
.price {
font-size: 18px;
font-weight: bold;
color: green;
}
`],
})
export class AppComponent implements OnInit {
users$ = this.dataService.getUsers();
products$ = this.dataService.getProducts();
loading$ = this.users$.pipe(map(() => false));
productsLoading$ = this.products$.pipe(map(() => false));
constructor(private dataService: DataService) {}
ngOnInit(): void {
// Data is fetched in component initialization
console.log('Component initialized');
}
}
5. Server-Side Rendering Setup
server.ts
import { ngExpressEngine } from '@nguniversal/express-engine';
import * as express from 'express';
import { join } from 'path';
import { APP_BASE_HREF } from '@angular/common';
import { existsSync } from 'fs';
import { AppServerModule } from './src/main.server';
const port = process.env['PORT'] || 4000;
const distFolder = join(process.cwd(), 'dist/myApp');
const indexHtml = existsSync(join(distFolder, 'index.original.html'))
? 'index.original.html'
: 'index';
const app = express();
// Set the engine
app.engine(
'html',
ngExpressEngine({
bootstrap: AppServerModule,
})
);
app.set('view engine', 'html');
app.set('views', distFolder);
// Serve static files
app.get(
'*.*',
express.static(distFolder, {
maxAge: '1y',
})
);
// All regular routes use the Universal engine
app.get('*', (req, res) => {
res.render(indexHtml, {
req,
providers: [{ provide: APP_BASE_HREF, useValue: req.baseUrl }],
});
});
// Simulated API endpoints
app.get('/api/users', (req, res) => {
res.json([
{ id: 1, name: 'John Doe', email: 'john@example.com' },
{ id: 2, name: 'Jane Smith', email: 'jane@example.com' },
{ id: 3, name: 'Bob Johnson', email: 'bob@example.com' },
]);
});
app.get('/api/products', (req, res) => {
res.json([
{
id: 1,
title: 'Laptop',
price: 999,
description: 'High-performance laptop',
},
{
id: 2,
title: 'Mouse',
price: 29,
description: 'Wireless mouse',
},
{
id: 3,
title: 'Keyboard',
price: 79,
description: 'Mechanical keyboard',
},
]);
});
app.listen(port, () => {
console.log(`Node Express server listening on http://localhost:${port}`);
});
6. Advanced: Route Resolvers with Prefetch
data.resolver.ts
import { Injectable } from '@angular/core';
import {
Resolve,
ActivatedRouteSnapshot,
RouterStateSnapshot,
} from '@angular/router';
import { Observable } from 'rxjs';
import { DataService, User } from './data.service';
@Injectable({
providedIn: 'root',
})
export class UserResolver implements Resolve<User[]> {
constructor(private dataService: DataService) {}
resolve(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<User[]> {
return this.dataService.getUsers();
}
}
@Injectable({
providedIn: 'root',
})
export class ProductResolver implements Resolve<any> {
constructor(private dataService: DataService) {}
resolve(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<any> {
return this.dataService.getProducts();
}
}
app-routing.module.ts
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { UserResolver, ProductResolver } from './data.resolver';
import { AppComponent } from './app.component';
const routes: Routes = [
{
path: '',
component: AppComponent,
resolve: {
users: UserResolver,
products: ProductResolver,
},
},
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule],
})
export class AppRoutingModule {}
7. Testing & Verification
transfer-state.service.spec.ts
import { TestBed } from '@angular/core/testing';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { TransferState, makeStateKey } from '@angular/platform-browser';
import { DataService, USERS_STATE_KEY } from './data.service';
describe('DataService with TransferState', () => {
let service: DataService;
let httpMock: HttpTestingController;
let transferState: TransferState;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
providers: [DataService, TransferState],
});
service = TestBed.inject(DataService);
httpMock = TestBed.inject(HttpTestingController);
transferState = TestBed.inject(TransferState);
});
afterEach(() => {
httpMock.verify();
});
it('should fetch users from HTTP when not in TransferState', (done) => {
service.getUsers().subscribe((users) => {
expect(users.length).toBeGreaterThan(0);
expect(transferState.get(USERS_STATE_KEY, null)).toBeTruthy();
done();
});
const req = httpMock.expectOne('/api/users');
expect(req.request.method).toBe('GET');
req.flush([
{ id: 1, name: 'Test User', email: 'test@example.com' },
]);
});
it('should return cached users from TransferState', (done) => {
const mockUsers = [
{ id: 1, name: 'Cached User', email: 'cached@example.com' },
];
transferState.set(USERS_STATE_KEY, mockUsers);
service.getUsers().subscribe((users) => {
expect(users).toEqual(mockUsers);
done();
});
// No HTTP request should be made
httpMock.expectNone('/api/users');
});
it('should store fetched data in TransferState', (done) => {
service.getUsers().subscribe(() => {
const cachedData = transferState.get(USERS_STATE_KEY, null);
expect(cachedData).toBeTruthy();
done();
});
const req = httpMock.expectOne('/api/users');
req.flush([{ id: 1, name: 'Test', email: 'test@example.com' }]);
});
});
8. Performance Monitoring
transfer-state.monitor.service.ts
import { Injectable } from '@angular/core';
import { TransferState, makeStateKey } from '@angular/platform-browser';
import { PLATFORM_ID, Inject } from '@angular/core';
import { isPlatform } from '@angular/common';
export interface CacheMetrics {
hits: number;
misses: number;
totalRequests: number;
hitRate: number;
dataSize: number;
}
@Injectable({
providedIn: 'root',
})
export class TransferStateMonitor {
private metrics: Map<string, CacheMetrics> = new Map();
private isServer = !isPlatform('browser', this.platformId);
constructor(
private transferState: TransferState,
@Inject(PLATFORM_ID) private platformId: Object
) {}
recordHit(key: string): void {
const current = this.metrics.get(key) || this.initializeMetrics();
current.hits++;
current.totalRequests++;
current.hitRate = current.hits / current.totalRequests;
this.metrics.set(key, current);
}
recordMiss(key: string): void {
const current = this.metrics.get(key) || this.initializeMetrics();
current.misses++;
current.totalRequests++;
current.hitRate = current.hits / current.totalRequests;
this.metrics.set(key, current);
}
private initializeMetrics(): CacheMetrics {
return {
hits: 0,
misses: 0,
totalRequests: 0,
hitRate: 0,
dataSize: 0,
};
}
getMetrics(key: string): CacheMetrics {
return this.metrics.get(key) || this.initializeMetrics();
}
getAllMetrics(): Map<string, CacheMetrics> {
return this.metrics;
}
logMetrics(): void {
console.log('TransferState Cache Metrics:');
this.metrics.forEach((metrics, key) => {
console.log(`Key: ${key}`, {
...metrics,
hitPercentage: (metrics.hitRate * 100).toFixed(2) + '%',
});
});
}
getStateSize(): number {
const state = (this.transferState as any).getState();
return new Blob([JSON.stringify(state)]).size;
}
}
9. Best Practices Checklist
// ✓ DO:
// 1. Use TransferState for frequently accessed data
const cachedData = this.transferState.get(KEY, null);
// 2. Always provide a null/fallback value
this.transferState.get(KEY, []);
// 3. Clear state after use on the client side (optional)
this.transferState.remove(KEY);
// 4. Use HTTP Interceptor for automatic caching
{
provide: HTTP_INTERCEPTORS,
useClass: TransferStateInterceptor,
multi: true,
}
// ❌ DON'T:
// 1. Store sensitive data in TransferState (visible in HTML)
// this.transferState.set(SENSITIVE_KEY, userData); // ❌
// 2. Store large objects without pagination
// this.transferState.set(BIG_DATA, hugeArray); // ❌
// 3. Forget to handle the fallback case
// this.transferState.get(KEY); // ❌ No fallback
// 4. Use TransferState for frequently changing data
// this.transferState.set(STOCK_PRICE, price); // ❌
10. Debug Utilities
debug.service.ts
import { Injectable } from '@angular/core';
import { TransferState } from '@angular/platform-browser';
@Injectable({
providedIn: 'root',
})
export class TransferStateDebugService {
constructor(private transferState: TransferState) {}
inspectState(): void {
const state = (this.transferState as any).getState();
console.table(state);
}
getState<T>(key: any): T | null {
return this.transferState.get(key, null);
}
setState<T>(key: any, value: T): void {
this.transferState.set(key, value);
}
removeKey(key: any): void {
this.transferState.remove(key);
}
getAllKeys(): string[] {
const state = (this.transferState as any).getState();
return Object.keys(state || {});
}
printStateJSON(): string {
const state = (this.transferState as any).getState();
return JSON.stringify(state, null, 2);
}
exportState(): void {
const dataStr = this.printStateJSON();
const element = document.createElement('a');
element.setAttribute(
'href',
'data:text/plain;charset=utf-8,' + encodeURIComponent(dataStr)
);
element.setAttribute('download', 'transfer-state.json');
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
}
}
This comprehensive guide covers everything needed to implement TransferState effectively. The key benefits are:
✅ Eliminates double-fetch - Server data transfers to client
✅ Faster initial load - No waiting for HTTP requests
✅ Better SEO - Content available immediately
✅ Improved UX - Seamless server-to-client transition
Would you like me to elaborate on any specific part?