Sub topic 1
Client rendering, server rendering, and prerendering compared
Prerequisites
You should know Angular components, standalone application configuration, dependency injection, routing, and basic HttpClient usage. You also need basic Node.js and npm knowledge.
Rendering models
In client-side rendering (CSR), the server sends a small HTML shell. The browser downloads JavaScript, creates the components, and fills the page. CSR works well for interactive applications, but the first meaningful content can arrive late.
In server-side rendering (SSR), Angular runs on the server for each request and sends complete HTML. The browser then hydrates that HTML, which means it connects Angular behavior to the existing DOM instead of rebuilding it.
Prerendering, also called static site generation (SSG), creates HTML during the build. It is fast to serve and suits stable pages, but changing content requires a new build.
| Model | HTML is created | Good fit |
|---|---|---|
| CSR | In the browser | Highly interactive private applications |
| SSR | On each request | Frequently changing, indexable pages |
| Prerendering | During the build | Marketing pages and documentation |
Adding SSR with the Angular CLI
In an existing Angular project, run:
ng add @angular/ssrThe schematic adds server-rendering configuration and usually creates or updates app.config.server.ts, app.routes.server.ts, and server.ts. It also updates the project scripts and build targets. Run the application with the normal development command, then inspect the generated files before customizing them.
Server configuration and entry points
The server configuration merges browser providers with SSR providers:
import { ApplicationConfig, mergeApplicationConfig } from '@angular/core';
import { provideServerRendering, withRoutes } from '@angular/ssr';
import { appConfig } from './app.config';
import { serverRoutes } from './app.routes.server';
const serverConfig: ApplicationConfig = {
providers: [provideServerRendering(withRoutes(serverRoutes))],
};
export const config = mergeApplicationConfig(appConfig, serverConfig);server.ts is the Node.js entry point. It creates the Angular server application, handles HTTP requests, and returns rendered HTML. Keep request-specific data in request-scoped services rather than global variables.
Enabling hydration
Add hydration to the shared browser configuration:
import { provideClientHydration } from '@angular/platform-browser';
export const appConfig = {
providers: [provideClientHydration()],
};Angular reuses the server-rendered elements, text, and structure, then attaches component state and event listeners. The server and browser must produce matching DOM. Avoid direct DOM changes and unguarded uses of window or document during rendering.
Exercise
Which model creates HTML during the build, and what does hydration reuse?
Show answer
Prerendering creates HTML during the build. Hydration reuses the server-rendered DOM and attaches Angular behavior to it.