// Step-by-Step Implementation of Server-Side Data Prefetching in Angular Universal
Angular Universal enables server-side rendering (SSR) with data prefetching to deliver fully hydrated HTML, improving SEO, TTFB, and client hydration speed. We'll use:
TransferHttpCacheModule: Automatically caches HTTP requests made on the server and replays them on the client (avoids duplicate fetches).
TransferState: Transfers custom state (non-HTTP data) from server to client.
Route Resolvers: Fetch data before route activation (runs on both server & client).
Platform Detection: Use isPlatformServer/isPlatformBrowser to conditionalize logic.
This example prefetches user profile data for a route /user/:id via HTTP. Assumes:
For Module-based (similar in app-routing.module.ts):
typescript
// Resolve: { user: UserResolver } // Use class-based if preferred
5. Component Consumes Resolved Data
typescript
// src/app/components/user.component.ts
import { Component, inject } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { CommonModule } from '@angular/common';
import { User } from '../services/user.service';
@Component({
selector: 'app-user',
standalone: true,
imports: [CommonModule],
template: `
<div *ngIf="user">
<h1>{{ user.name }}</h1>
<p>{{ user.email }}</p>
</div>
<div *ngIf="!user">Loading...</div>
`,
})
export class UserComponent {
private route = inject(ActivatedRoute);
user = this.route.snapshot.data['user'] as User; // Resolved data available immediately
}
6. Handle TransferState in Main Entry Points
main.server.ts (already handles by default with @angular/ssr):
typescript
// src/main.server.ts
import { bootstrapApplication } from '@angular/platform-browser';
import { renderApplication } from '@angular/platform-server';
import { appConfig } from './app/app.config.server';
import { AppComponent } from './app/app.component';
export default async function render(url: string, document: string) {
const value = await renderApplication(() => bootstrapApplication(AppComponent, appConfig), {
document,
url,
});
return value;
}
main.ts (browser): No changes needed; TransferState auto-injects.
7. Build & Serve
bash
# Build for production
npm run build:ssr
# Serve (Express by default)
npm run serve:ssr
Visit http://localhost:4000/user/1:
Server: Fetches data, embeds in HTML, caches HTTP.
Client: Hydrates instantly (data from TransferState/HTTP cache), no refetch.
Advanced Tips
Non-HTTP Data: Use TransferState directly (e.g., computed values).
Multiple Requests: TransferHttpCacheModule dedupes all HttpClient calls automatically.
GraphQL/Other: Manually set TransferState in resolvers/services.
Debug: Log isPlatformServer to verify.
Performance: Purge cache with TransferCacheModule.purge() if needed.
Errors: Use APP_INITIALIZER for app-wide prefetching.
This setup ensures zero client fetches on hydration for resolved data. Test with Chrome DevTools > Network (disable cache) – server HTML includes data! 🚀
If you need custom service examples or GraphQL integration, provide more details.