I'm focused on the fundamental goal: building an Angular Universal application with pre-rendering. This means server-side rendering is the core need, especially for SEO. My next step will involve breaking down the critical steps. This will make it simpler for the user to understand.
Clarifying Core Steps
I'm now prioritizing the logical breakdown of the process. I'm focusing on distilling the essential steps, particularly how Angular Universal version 17+ simplifies setup via @angular/ssr. I'm also refining the steps for API integration and efficient data transfer using the TransferState to minimize client-side re-fetching.
Mapping Out Implementation
I'm now deep-diving into the technical details. I'm focusing on the practical code required, specifically how to structure the API service using HttpClient, TransferState, and makeStateKey for seamless data transfer. I'm also refining the steps for SEO metadata injection and discussing prerendering configurations within angular.json, to create a complete understanding for the user.
Constructing a Technical Blueprint
I'm now in the process of mapping out the code structure. I'm focusing on creating an ApiService using HttpClient and TransferState, and I'm detailing the implementation for both server and client execution. I'll make sure to provide comprehensive explanations of crucial aspects like Non-Destructive Hydration and preventing double HTTP requests, focusing on Angular 17+ best practices.
Developing a Stepwise Plan
I'm now consolidating the steps into a coherent guide. I'm focusing on the "ideal" structure of the output. I'll include the new SSR setup, API service creation (with TransferState), and component implementation. I am planning to highlight the practical aspects of preventing double HTTP requests, focusing on the latest Angular versions and including provideClientHydration with HttpClient. Finally, I will address the differences between SSR and prerendering (SSG) in clear terms, and how to configure them.
Formulating a Comprehensive Plan
I'm now formulating a step-by-step tutorial. I'm focusing on the practical application of key concepts. This includes setting up SSR with Angular 17+ and API calls using HttpClient. I am also planning to highlight how to prevent double requests with TransferState, providing concrete code samples for clarity, and including the provideClientHydration in the process. The importance of SEO metadata and prerendering configuration will be addressed to complete the guidance.
This guide will walk you through building an Angular application (version 17+) that uses Server-Side Rendering (SSR) and Static Site Generation (SSG) to pre-render API data for SEO.
We will use:
Angular SSR: To render HTML on the server.
TransferState: To fetch data on the server and pass it to the client (preventing the browser from re-fetching the API).
Meta/Title Services: To dynamically update SEO tags.
As of Angular 17+, SSR makes setup extremely easy.
bash
# Create new project
ng new angular-seo-demo
# Select 'Yes' for Server-Side Rendering (SSR) and Static Site Generation (SSG/Prerendering)
# Select 'Yes' and pick your stylesheet format (CSS/SCSS)
If you have an existing project, run:
bash
ng add @angular/ssr
Step 2: Create a Data Service with TransferState
This is the most critical step. We need a service that fetches data but handles two scenarios:
Server: Fetch API -> Save result to State -> Render HTML.
Client: Check State -> If data exists, use it; otherwise, fetch API.
Generate a service:
bash
ng generate service services/posts
src/app/services/posts.service.ts
typescript
import { Injectable, makeStateKey, TransferState, inject, PLATFORM_ID } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, of, tap } from 'rxjs';
import { isPlatformServer } from '@angular/common';
// Define a unique key for the state
const POSTS_KEY = makeStateKey<any[]>('posts-list');
@Injectable({
providedIn: 'root'
})
export class PostsService {
private http = inject(HttpClient);
private transferState = inject(TransferState);
private platformId = inject(PLATFORM_ID);
private apiUrl = 'https://jsonplaceholder.typicode.com/posts?_limit=5';
getPosts(): Observable<any[]> {
// 1. Check if data exists in TransferState (Client side logic)
if (this.transferState.hasKey(POSTS_KEY)) {
const storedPosts = this.transferState.get(POSTS_KEY, []);
// Remove key so subsequent navigations re-fetch if needed (optional)
this.transferState.remove(POSTS_KEY);
return of(storedPosts);
}
// 2. If no state, fetch from API
return this.http.get<any[]>(this.apiUrl).pipe(
tap(data => {
// 3. If running on Server, save data to TransferState
if (isPlatformServer(this.platformId)) {
this.transferState.set(POSTS_KEY, data);
}
})
);
}
}
Step 3: Configure HttpClient
In Angular 17+ (Standalone), ensure HttpClient is provided with fetch enabled (required for efficient SSR).
src/app/app.config.ts
typescript
import { ApplicationConfig } from '@angular/core';
import { provideRouter } from '@angular/router';
import { routes } from './app.routes';
import { provideClientHydration } from '@angular/platform-browser';
import { provideHttpClient, withFetch } from '@angular/common/http';
export const appConfig: ApplicationConfig = {
providers: [
provideRouter(routes),
provideClientHydration(),
provideHttpClient(withFetch()) // <--- Add this
]
};
Step 4: Build the Component (SEO Logic)
We will display the data and update the HTML <title> and <meta> tags so crawlers can understand the page content.
src/app/app.component.ts
typescript
import { Component, OnInit, inject } from '@angular/core';
import { CommonModule } from '@angular/common'; // For NgFor
import { RouterOutlet } from '@angular/router';
import { Meta, Title } from '@angular/platform-browser';
import { PostsService } from './services/posts.service';
@Component({
selector: 'app-root',
standalone: true,
imports: [CommonModule, RouterOutlet],
template: `
<div style="padding: 20px; font-family: sans-serif;">
<h1>Angular SEO & Prerendering Demo</h1>
<ul *ngIf="posts.length > 0; else loading">
<li *ngFor="let post of posts" style="margin-bottom: 20px; border-bottom: 1px solid #ccc;">
<h3>{{ post.title }}</h3>
<p>{{ post.body }}</p>
</li>
</ul>
<ng-template #loading>Loading content...</ng-template>
</div>
`
})
export class AppComponent implements OnInit {
posts: any[] = [];
// Inject services
private postsService = inject(PostsService);
private titleService = inject(Title);
private metaService = inject(Meta);
ngOnInit() {
this.loadData();
}
loadData() {
this.postsService.getPosts().subscribe(data => {
this.posts = data;
this.setSEOTags();
});
}
setSEOTags() {
// Set the browser tab title
this.titleService.setTitle('Top 5 Posts - Angular SEO');
// Update Meta tags for social media and SEO
this.metaService.updateTag({ name: 'description', content: 'This is a list of pre-rendered posts fetched from an API.' });
this.metaService.updateTag({ property: 'og:title', content: 'Top 5 Posts - Angular SEO' });
this.metaService.updateTag({ property: 'og:description', content: 'Check out these posts rendered on the server.' });
}
}
Step 5: Testing SSR (Development Mode)
Run the development server with SSR logic:
bash
npm run watch
# or
ng serve
Open http://localhost:4200.
Right-click -> View Page Source.
Search for the post content (e.g., "sunt aut facere").
Result: You should see the actual text inside the HTML source code. You should also see a <script id="posts-list"> tag containing the JSON data. This confirms Pre-rendering + State Transfer is working.
Step 6: Static Site Generation / Prerendering (Production)
If you want to generate static HTML files for specific routes at build time (instead of rendering per request on the server), you configure Prerendering.
Open angular.json.
Locate the prerender block under architect. By default, it prerenders the root (/).
If you have dynamic routes (e.g., /posts/1, /posts/2), creates a routes.txt file in your root folder:
To simulate a real production environment (Node.js server serving pre-rendered HTML):
bash
npm run build
npm run serve:ssr:angular-seo-demo
Navigate to http://localhost:4000. The page load will be instant because the API was fetched on the server, and the browser simply "hydrates" the existing HTML using the state transfer script.