# Prerequisites
# - Node.js 18+ (LTS recommended)
# - Angular CLI 17+ (ng --version to check)
# Step 1: Create a new Angular application
ng new my-universal-seo-app --routing --style=scss --ssr=false
cd my-universal-seo-app
Step 2: Add Angular Universal (SSR) Support
Angular Universal enables server-side rendering out-of-the-box with Express.
ng add @nguniversal/express-engine
This does the heavy lifting:
- Adds
server.ts (Express server).
- Updates
angular.json with SSR builder.
- Adds
main.server.ts and app.server.module.ts.
- Installs
@nguniversal/express-engine, @angular/platform-server, etc.
Step 3: Simulate API Data Fetching
We'll use JSONPlaceholder API for demo posts. On SSR, we'll fetch data server-side, embed it in HTML, and transfer to client via TransferState (prevents duplicate API calls).
3.1 Install HttpClient (already included, but ensure)
HttpClient is in app.module.ts by default.
3.2 Create Data Service
ng generate service data
src/app/data.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { TransferState, makeStateKey } from '@angular/platform-browser';
import { tap } from 'rxjs/operators';
const POSTS_KEY = makeStateKey<any[]>('posts');
export interface Post {
id: number;
title: string;
body: string;
}
@Injectable({
providedIn: 'root'
})
export class DataService {
constructor(
private http: HttpClient,
private transferState: TransferState
) {}
getPosts(): Observable<Post[]> {
if (this.transferState.hasKey(POSTS_KEY)) {
const posts = this.transferState.get(POSTS_KEY, [] as Post[]);
this.transferState.remove(POSTS_KEY);
return of(posts);
}
return this.http.get<Post[]>('https://jsonplaceholder.typicode.com/posts?_limit=10').pipe(
tap(posts => {
this.transferState.set(POSTS_KEY, posts);
})
);
}
}
Why TransferState?
- Server fetches API → stores in state → embeds in HTML.
- Client checks state first → uses pre-fetched data → no re-fetch.
- SEO win: Initial HTML has full data (viewable in
curl or "View Page Source").
3.3 Update App Module (Browser)
src/app/app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
@NgModule({
declarations: [AppComponent],
imports: [
BrowserModule.withServerTransition({ appId: 'my-universal-seo-app' }),
AppRoutingModule,
HttpClientModule // Ensures HttpClient works on server too
],
bootstrap: [AppComponent]
})
export class AppModule {}
3.4 Update App Server Module
src/app/app.server.module.ts (auto-generated, but verify HttpClientModule):
import { NgModule } from '@angular/core';
import { ServerModule } from '@angular/platform-server';
import { AppModule } from './app.module';
import { AppComponent } from './app.component';
import { ModuleMapLoaderModule } from '@nguniversal/module-map-ngfactory-loader';
import { HttpClientModule, HttpTransferCacheModule } from '@angular/common/http';
import { TransferHttpCacheModule } from '@nguniversal/common';
@NgModule({
imports: [
AppModule,
ServerModule,
ModuleMapLoaderModule,
HttpClientModule, // HttpClient on server
TransferHttpCacheModule, // Global HTTP cache for SSR
HttpTransferCacheModule
],
bootstrap: [AppComponent]
})
export class AppServerModule {}
3.5 Create Posts Component
ng generate component posts
src/app/posts/posts.component.ts
import { Component, OnInit } from '@angular/core';
import { DataService, Post } from '../data.service';
import { Observable } from 'rxjs';
@Component({
selector: 'app-posts',
templateUrl: './posts.component.html',
styleUrls: ['./posts.component.scss']
})
export class PostsComponent implements OnInit {
posts$!: Observable<Post[]>;
constructor(private dataService: DataService) {}
ngOnInit() {
this.posts$ = this.dataService.getPosts();
}
}
src/app/posts/posts.component.html (SEO-friendly with meta)
<div class="posts-container">
<h1>Latest Posts (SSR Pre-rendered for SEO)</h1>
<article *ngFor="let post of posts$ | async; trackBy: trackById" class="post">
<h2>{{ post.title }}</h2>
<p>{{ post.body }}</p>
</article>
</div>
src/app/posts/posts.component.ts (add trackBy for perf):
trackById(index: number, post: Post): number {
return post.id;
}
src/app/posts/posts.component.scss
.posts-container {
max-width: 800px;
margin: 0 auto;
padding: 20px;
.post {
border-bottom: 1px solid #eee;
padding: 20px 0;
h2 {
color: #333;
margin-bottom: 10px;
}
}
}
3.6 Route to Posts
src/app/app-routing.module.ts
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/common/router';
import { PostsComponent } from './posts/posts.component';
const routes: Routes = [
{ path: '', redirectTo: '/posts', pathMatch: 'full' },
{ path: 'posts', component: PostsComponent }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule {}
3.7 Update App Component (SEO Title/Meta)
src/app/app.component.html
<router-outlet></router-outlet>
src/app/app.component.ts (dynamic title)
import { Component } from '@angular/core';
import { Title, Meta } from '@angular/platform-browser';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
title = 'My Universal SEO App';
constructor(private titleService: Title, private meta: Meta) {
this.titleService.setTitle(this.title);
this.meta.updateTag({ name: 'description', content: 'Angular Universal app with API pre-rendering for optimal SEO.' });
}
}
Step 4: Enhance Server.ts (Optional: Custom Middleware)
server.ts (auto-generated; add for production):
import 'zone.js/dist/zone-node';
import * as express from 'express';
import { join } from 'path';
import { ngExpressEngine } from '@nguniversal/express-engine';
import { existsSync } from 'fs';
const DIST_FOLDER = join(process.cwd(), 'dist/my-universal-seo-app/browser');
const INDEX_HTML = join(DIST_FOLDER, 'index.original.html');
const app = express();
app.engine('html', ngExpressEngine({
bootstrap: () => import('./main.server').then(m => m.app),
}));
app.set('view engine', 'html');
app.set('views', DIST_FOLDER);
// Serve static files
app.get('*.*', express.static(DIST_FOLDER, {
maxAge: '1y'
}));
// All regular routes use SSR
app.get('*', (req, res) => {
res.render(INDEX_HTML, {
req,
providers: [{ provide: 'REQUEST', useValue: req }]
});
});
const port = process.env['PORT'] || 4000;
app.listen(port, () => {
console.log(`SSR server running on http://localhost:${port}`);
});
Step 5: Build & Run
# Development (HMR + SSR)
npm run dev:ssr
# Production Build
npm run build:ssr
# Production Serve
npm run serve:ssr # http://localhost:4000
Step 6: Verify SEO & Pre-rendering
- Browser DevTools > Network: Client won't re-fetch
/posts (uses TransferState).
- View Page Source: Full posts data in HTML (search for post titles).
- Curl Test:
curl http://localhost:4000/posts | grep -A5 -B5 "title"
→ Sees rendered <h2> titles from API.
- Lighthouse SEO Audit: Run in Chrome → Near-perfect score (SSR magic).
- Google Search Console: Crawlers see full content instantly.
Key SEO Wins
- Fast Initial Render: Data in HTML (no JS needed).
- TransferState: No flash/dupe calls.
- Dynamic Meta: Titles/descriptions crawlable.
- Scalable: Works with any API (swap JSONPlaceholder).
Production Tips
- Prerender.io or @nguniversal/builders prerender: Static pre-render routes.
- Cloud: Vercel/Netlify auto-deploys Angular Universal.
- i18n: Universal supports it natively.
- Error Handling: Add
catchError in service.
Full repo template: GitHub Mirror (fork & tweak).
Questions? Ask Sherlock! 🕵️♂️