Explaining server-side data prefetching
The user wants guidance on implementing server-side data prefetching in an Angular Universal application, including explanation and code. They’re looking for a thorough but concise approach to concepts like SSR, TransferState, route resolvers, and interceptors.
I’ll break it down with structured steps: first, install Angular Universal if it’s not already done. Next, use route resolvers for server data fetching. After that, I’ll show how to use TransferState to pass data to the client to prevent duplicate HTTP calls, and I might suggest using an HTTP interceptor or service for caching.Clarifying Angular Universal behavior
When using Angular Universal with resolvers and initialNavigation: 'enabledBlocking', it's important to clarify how it works.
To set it up, I would typically advise running ng add @nguniversal/express-engine. In the data service, I'd use absolute URLs along with environment variables. Best practices involve creating TransferHttpCacheModule and ServerTransferStateModule, but in Angular 15+, we now have options like provideClientHydration and withHttpTransferCache.
For an Angular v15+ setup, I’d show how to use bootstrapApplication in the main.server.ts file with relevant providers for server rendering and caching.Describing data fetching in Angular
It's common for tutorials to still reference BrowserTransferStateModule and ServerTransferStateModule, which is relevant for users on Angular 12-17. I need to lay out a couple of approaches without being too verbose.
First, fetching data in resolvers allows Angular to wait for the Observable to complete before activating the route. This means that on the server side, it renders once the data is ready, and on the client side, we can use TransferState to keep the data.
For example, I’d create a resolver and use it in the route to ensure efficient data handling without making duplicate HTTP calls.Simplifying Angular prefetching
Angular's TransferHttpCacheModule is a great tool because it automatically caches HTTP calls during server-side rendering (SSR) and allows the client to utilize them. To implement this for Angular versions under 15, I’d suggest importing the necessary modules in app.server.module.ts and app.module.ts.
For example, in the server module, I’d include ServerTransferStateModule, and in the app module, I’d make sure to add TransferHttpCacheModule. However, since the user asked for an implementation, I’ll provide a step-by-step approach focused on setting it up effectively, considering the Angular version they may be using.Implementing server-side data prefetching in Angular
For implementing server-side data prefetching, I would break it down into straightforward steps, focusing on HTTP transfer caching to ensure efficient data reuse on the client side.
First, I’d add Angular Universal to the project. Then, I’d configure TransferHttpCacheModule in both the app.module.ts and app.server.module.ts. Next, I'd create a service and a resolver to fetch data before rendering. It’s important to use Angular’s router to wait for async tasks, ensuring that data is ready before HTML is sent to the client.
In the example, an HTTP GET request will be made to /api/products, with caching handled automatically by the TransferHttpCache. This way, the resolver ensures that the data is fetched efficiently without repetition.Implementing server-side data prefetching
To ensure the initial route is rendered on the server with data and reused on the client, I’ll break this down step-by-step.
First, set up Angular Universal and the transfer cache. Then, use a resolver to prefetch route data and leverage it in your component. It’s also possible to preload non-route data using APP_INITIALIZER, but I’ll focus on route resolvers since that aligns with the user's request.
For Angular 15+, it’s important to include initialNavigation: 'enabledBlocking' in the RouterModule setup, which ensures that server-side rendering works optimally. This way, HTTP calls are not repeated, and data is readily available when needed. Server-side data prefetching in Angular Universal is mainly about:
- Fetching data before the route is rendered on the server.
- Reusing that data on the client so the browser doesn’t refetch everything after hydration.
Below is a straightforward implementation using:
- Route resolvers to block navigation until data is loaded.
- Angular Universal’s HTTP transfer cache so HTTP calls made on the server are reused on the client.
1. Prerequisites: Angular Universal + Transfer Cache
If you don’t have Universal yet:
ng add @nguniversal/express-engine
This sets up:
server.ts
app.server.module.ts
- Server build/serve targets in
angular.json.
Enable HTTP transfer cache
For module-based applications (Angular 13–16 style):
app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule, BrowserTransferStateModule } from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';
import { TransferHttpCacheModule } from '@nguniversal/common';
import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';
@NgModule({
declarations: [AppComponent],
imports: [
BrowserModule.withServerTransition({ appId: 'serverApp' }),
HttpClientModule,
BrowserTransferStateModule, // enables TransferState on browser
TransferHttpCacheModule, // reuses SSR HTTP calls on client
AppRoutingModule,
],
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, // enables TransferState on server
],
bootstrap: [AppComponent],
})
export class AppServerModule {}
For standalone/Angular 16+, the same idea is done via providers:
// main.ts (browser)
bootstrapApplication(AppComponent, {
providers: [
provideClientHydration(withHttpTransferCache()),
provideHttpClient(withFetch(), withInterceptorsFromDi()),
// ...other providers
]
});
// main.server.ts
bootstrapApplication(AppComponent, {
providers: [
provideServerRendering(),
provideHttpClient(withFetch(), withHttpTransferCache()),
// ...other providers
]
});
(Details vary by version, but the key is withHttpTransferCache() or TransferHttpCacheModule.)
2. Make Router Wait for Data (initialNavigation)
Ensure the router blocks the first navigation until async work (like resolvers) is done. In Universal apps, this is typically:
app-routing.module.ts
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { ProductsComponent } from './products/products.component';
import { ProductResolver } from './products/product-resolver.service';
const routes: Routes = [
{
path: 'products',
component: ProductsComponent,
resolve: { products: ProductResolver },
},
{ path: '', redirectTo: 'products', pathMatch: 'full' },
];
@NgModule({
imports: [
RouterModule.forRoot(routes, {
initialNavigation: 'enabledBlocking', // important for SSR prefetch
}),
],
exports: [RouterModule],
})
export class AppRoutingModule {}
3. Create a Data Service (used on both server and client)
products/product.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
export interface Product {
id: number;
name: string;
}
@Injectable({ providedIn: 'root' })
export class ProductService {
constructor(private http: HttpClient) {}
getProducts(): Observable<Product[]> {
// URL should be reachable both from Node (SSR) and browser
// Often you proxy `/api` to your backend from the Universal server.
return this.http.get<Product[]>('/api/products');
}
}
4. Create a Route Resolver to Prefetch Data on Server
products/product-resolver.service.ts
import { Injectable } from '@angular/core';
import { Resolve, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs';
import { Product, ProductService } from './product.service';
@Injectable({ providedIn: 'root' })
export class ProductResolver implements Resolve<Product[]> {
constructor(private productService: ProductService) {}
resolve(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<Product[]> {
// Called on both server and browser.
// On server: performs real HTTP call.
// On browser: TransferHttpCache will replay the response instead of refetching.
return this.productService.getProducts();
}
}
During SSR, Angular runs the router, hits this resolver, waits for getProducts() to complete, and only then renders the ProductsComponent with the data.
5. Consume Prefetched Data in the Component
products/products.component.ts
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { map, Observable } from 'rxjs';
import { Product } from './product.service';
@Component({
selector: 'app-products',
templateUrl: './products.component.html',
})
export class ProductsComponent implements OnInit {
products$!: Observable<Product[]>;
constructor(private route: ActivatedRoute) {}
ngOnInit(): void {
this.products$ = this.route.data.pipe(
map(data => data['products'] as Product[])
);
}
}
products/products.component.html
<h1>Products</h1>
<ul>
<li *ngFor="let product of products$ | async">
{{ product.name }}
</li>
</ul>
What happens:
-
On the server:
- Router activates
/products.
ProductResolver calls getProducts(); HTTP request is made in Node.
- TransferHttpCache intercepts and stores the response in
TransferState.
ProductsComponent receives data, template renders full HTML list.
- HTML + serialized state are sent to the browser.
-
On the client (browser):
- Angular bootstraps, hydration kicks in.
- Same
ProductResolver executes, but HTTP call is intercepted by the transfer cache.
- Instead of calling the backend again, it uses the response from SSR.
- No flicker/loading and no duplicate request.
6. Backend/Proxy (very brief)
Your Universal server (server.ts) typically either:
- Serves the Angular app and proxies
/api/* to your real backend, or
- Directly implements endpoints.
Example (Express) snippet if you want a quick mock:
server.get('/api/products', (req, res) => {
res.json([
{ id: 1, name: 'Book' },
{ id: 2, name: 'Laptop' },
]);
});
7. Summary
To implement server-side data prefetching in Angular Universal:
- Enable SSR with
@nguniversal/express-engine.
- Add HTTP transfer cache:
TransferHttpCacheModule + BrowserTransferStateModule + ServerTransferStateModule,
- or
withHttpTransferCache() in standalone apps.
- Use
initialNavigation: 'enabledBlocking' in the router.
- Use route resolvers (or guards) that return HTTP Observables.
- Read resolver data from
ActivatedRoute.data in your components.
With this setup, the first page load is fully rendered with data on the server, and the browser reuses that data instead of re-fetching it.