The user wants a guide on how to implement server-side data prefetching in an Angular Universal application.
Key Concepts to Cover:
Angular Universal: What it is (SSR).
Data Prefetching: Why it's needed (SEO, performance, initial load speed).
TransferState API: The core mechanism to prevent duplicate HTTP requests (client-side re-fetching what the server already fetched).
Resolve Guards: The standard Angular way to prefetch data before navigation.
Server-specific logic: Using isPlatformServer or APP_INITIALIZER (though APP_INITIALIZER is tricky with Universal sometimes, Resolvers are usually better for route-specific data).
Step-by-Step Plan:
Prerequisites: Mention Angular CLI and adding Universal (ng add @nguniversal/express-engine).
The Problem: Briefly explain the "double fetch" issue (Server fetches, Client fetches again on hydration).
The Solution (TransferState): This is the most critical part.
Import BrowserTransferStateModule (client) and ServerTransferStateModule (server).
Wait, actually, in modern Angular (v14+), TransferState is part of @angular/platform-browser and usually requires minimal setup, but I should explain how to use the TransferState service manually inside a service or interceptor.
Better approach for modern Angular: Use HttpClient with the TransferHttpCacheModule (automatically handles caching GET requests).
Manual approach: Using the TransferState service keys.
Decision: I will focus on the Resolver approach combined with TransferState (specifically TransferHttpCacheModule which is the easiest and most effective "auto-magic" way, but I will also show the manual TransferState service usage for granular control).
Step 1: Setup TransferHttpCacheModule. This is the "easy button". It intercepts requests on the server, caches them, and serves them on the client.
Step 2: Create a Data Service. Standard service using HttpClient.
Step 3: Create a Resolver. This ensures data is ready before the component renders on the server.
Step 4: Configure Routes. Add the resolver to a route.
Step 5: Component Implementation. How to read the data (using ActivatedRoute).
Alternative (Advanced): Manual TransferState usage inside a service for non-HTTP or complex scenarios.
Drafting the Content:
Intro: Why prefetch? SEO + fast paint.
Core Mechanism:TransferState. Explain that the server renders HTML with data, but the client app boots up and might fetch again. TransferState serializes the data into the HTML script tag for the client to pick up.
Implementation:
Install:ng add @nguniversal/express-engine.
App Module: Import TransferHttpCacheModule (or ServerTransferStateModule / BrowserTransferStateModule in older versions, but TransferHttpCacheModule is the modern standard for HTTP).
The Component: Inject ActivatedRoute, access route.snapshot.data.
Refining the TransferState part:
There are two ways to do this:
Automatic (Interceptor based):TransferHttpCacheModule. This is usually preferred.
Manual (Service based): Using TransferState.set and get.
I should provide the Resolver approach because that answers the "Prefetching" aspect (ensuring data is there before navigation completes).
Let's stick to the standard modern Angular approach:
Enable SSR.
Use TransferHttpCacheModule to prevent the double request.
Use a Resolver to trigger the fetch during the server render.
Self-Correction:TransferHttpCacheModule handles the state transfer automatically for HttpClient calls. The Resolver ensures the call happens before the HTML is generated.
Structure of the response:
High-level overview: How it works.
Step 1: Enable TransferHttpCache. (The magic glue).
Step 2: Create a Resolver. (The prefetch trigger).
Step 3: Configure Routing.
Step 4: Read data in Component.
Step 5: Server & Client Build.
Manual TransferState (Optional/Advanced): Just a snippet to show how it works under the hood.
This looks solid. It covers the "Prefetching" (Resolver) and the "Universal/SSR" part (TransferState/Cache).
Wait, what about Angular 17/18+?
Hydration is the new standard. provideClientHydration() is usually in app.config.ts. TransferHttpCacheModule is often integrated or behaves slightly differently if using standalone components. I should write the code to be generally compatible but mention the module-based approach as it's still very common, or provide the standalone provideClientHydration(withHttpTransferCacheOptions()) syntax.
Decision: I will provide the Standalone/Modern approach (Angular 17+) as the primary answer, but keep it understandable for module-based apps.
Actually, mixing Module-based (Universal default generation usually creates modules) and Standalone can be confusing.
Let's stick to the most standard approach currently generated by the CLI. ng add @nguniversal still generates app.server.module. I will focus on the logic regardless of the boilerplate.
Revised Plan:
Concept: Explain Server -> HTML + Data -> Client. Client reads Data.
Tool:TransferState API.
Strategy: Use a Resolver to block navigation until data loads + TransferHttpCacheModule to pass data to client.
Code Example:
Configure TransferHttpCache.
Create the Service (standard HttpClient).
Create the Resolver.
Setup Routes.
Consume in Component.
This is the complete answer.
One crucial detail: APP_INITIALIZER vs Resolvers.
Resolvers are better for route-specific data. APP_INITIALIZER is better for global app config (like loading user profile/translations before the app boots). I'll stick to Resolvers as it fits "prefetching" for specific pages better.
Let's refine the "Transfer State" explanation. It's important to explain why we need it (avoiding the client making the same HTTP call again after hydration).
Final Polish:
Ensure code snippets are copy-pasteable and clean. Use TypeScript.
Let's write out the response following this logic.
Prerequisites:ng add @nguniversal/express-engine.
The Mechanism:TransferState.
Implementation Steps.
Step 1: Import TransferHttpCacheModule.
Step 2: Create Resolver.
Step 3: Add Resolver to Route.
Step 4: Read Data.
Manual Approach: Briefly show TransferState service usage for non-HTTP data.
That seems complete. I will write the solution now.
Server-side data prefetching in Angular Universal is primarily handled using Resolvers combined with the TransferState API.
Here is the complete implementation strategy.
The Architecture
Resolver: Intercepts the navigation request. It runs on both the server and the client.
TransferState: Acts as a key-value store. The server fetches data and saves it here. The client reads the data from the rendered HTML page instead of making a new HTTP request.
First, ensure your application is configured to transfer state from the server to the client.
In modern Angular (v17+), this is handled in app.config.ts. In older versions, it is handled in app.server.module.ts.
Modern Angular (Standalone/App Config):
typescript
// app.config.ts
import { provideHttpClient } from '@angular/common/http';
import { provideClientHydration } from '@angular/platform-browser';
export const appConfig: ApplicationConfig = {
providers: [
provideHttpClient(),
// Enables state transfer from server to client automatically
provideClientHydration()
]
};
Step 2: Create a Resolver
A Resolver ensures that data is loaded before the route finishes activating. This allows the server to wait for the data before rendering the HTML.
Create a file product.resolver.ts:
typescript
import { inject } from '@angular/core';
import { ResolveFn } from '@angular/router';
import { ProductService } from './product.service';
import { Product } from './product.model';
export const productResolver: ResolveFn<Product[]> = (route, state) => {
const productService = inject(ProductService);
// Return the Observable. Angular Universal will wait for this
// to complete on the server before rendering.
return productService.getProducts();
};
Step 3: Configure Routing
Add the resolver to your route definition in app.routes.ts (or your routing module).
typescript
import { Routes } from '@angular/router';
import { ProductComponent } from './product/product.component';
import { productResolver } from './product.resolver';
export const routes: Routes = [
{
path: 'products',
component: ProductComponent,
// The resolver will prefetch data before the component loads
resolve: {
products: productResolver
}
}
];
Step 4: The Service (Handling TransferState)
This is the most critical step. Without TransferState, the server fetches the data, sends the HTML to the browser, and then the browser fetches the data again (the "Double Fetch" problem).
We modify the service to check if data already exists in the TransferState cache.
product.service.ts:
typescript
import { Injectable, inject, PLATFORM_ID } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { makeStateKey, TransferState } from '@angular/platform-browser';
import { Observable, of } from 'rxjs';
import { tap } from 'rxjs/operators';
import { isPlatformServer } from '@angular/common';
@Injectable({
providedIn: 'root'
})
export class ProductService {
private http = inject(HttpClient);
private transferState = inject(TransferState);
private platformId = inject(PLATFORM_ID);
private PRODUCTS_KEY = makeStateKey<any>('products-data');
getProducts(): Observable<any> {
// 1. Check if data already exists in the transferred state
if (this.transferState.hasKey(this.PRODUCTS_KEY)) {
const data = this.transferState.get(this.PRODUCTS_KEY, null);
console.log('Reading from TransferState (Client Cache)');
return of(data);
}
// 2. If not, fetch from API
return this.http.get('https://api.example.com/products').pipe(
tap((data) => {
// 3. If running on the Server, save to TransferState
if (isPlatformServer(this.platformId)) {
console.log('Writing to TransferState (Server)');
this.transferState.set(this.PRODUCTS_KEY, data);
}
})
);
}
}
Step 5: Read Data in the Component
Finally, read the resolved data in your component using the ActivatedRoute.
product.component.ts:
typescript
import { Component, inject } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { AsyncPipe, JsonPipe } from '@angular/common';
import { Observable } from 'rxjs';
@Component({
selector: 'app-product',
standalone: true,
imports: [AsyncPipe, JsonPipe],
template: `
<h1>Products</h1>
<!-- The data is guaranteed to be here instantly -->
<pre>{{ products$ | async | json }}</pre>
`
})
export class ProductComponent {
private route = inject(ActivatedRoute);
// Access the data resolved by the resolver
products$ = this.route.data.pipe(
map(data => data['products'])
);
}
(Note: You need to import map from rxjs/operators).
How the Flow Works
Server Request:
The user requests /products.
Angular Server activates the route.
The productResolver triggers getProducts().
The TransferState is empty, so the server executes the HTTP request.
The server receives the data and saves it into TransferState using set.
The server renders the HTML (with the data visible) and embeds the TransferState data into a <script> tag in the HTML.
Client Hydration:
The browser loads the HTML.
Angular boots up on the client.
The productResolver triggers getProducts() again (standard Angular behavior).
The Service checks TransferState.hasKey. It returns true.
The Service returns of(data) immediately. No HTTP request is made.