How to add SSR to existing Angular app
Want to add server-side rendering to your existing Angular application?
All you have to do is run the simple Angular CLI schematics command.
ng add @angular/ssr
You'll be asked to confirm that you want to proceed. Type the Y
option to continue with the Angular SSR set up.
This will download and install the Angular SSR dependencies.
And it will also make some modifications to your Angular project. And set up server-side rendering for you.
All automatically!
So what changed?
First, it will create several new files.
One of these is named server.ts
file. This is the server app for the server-side rendering process.
It will also create a app.config.server.ts
file that will contain the configuration for our server.
import { mergeApplicationConfig, ApplicationConfig } from '@angular/core';
import { provideServerRendering } from '@angular/platform-server';
import { appConfig } from './app.config';
const serverConfig: ApplicationConfig = {
providers: [
provideServerRendering()
]
};
export const config = mergeApplicationConfig(appConfig, serverConfig);
Then it will update some files like angular.json
and also make some changes to the app.config.ts
file by providing client hydration for the server-side hydration process.
import { ApplicationConfig, provideZoneChangeDetection } from '@angular/core';
import { provideRouter } from '@angular/router';
import { routes } from './app.routes';
import { provideClientHydration } from '@angular/platform-browser';
export const appConfig: ApplicationConfig = {
providers: [provideZoneChangeDetection({ eventCoalescing: true }), provideRouter(routes), provideClientHydration()]
};
And last of all, it will edit the package.json
file with some new scripts to run our Angular server-side rendering application.
Conclusion
One of the best features of Angular is the simple CLI and the available schematics scripts that the Angular team has built.
A huge shout out to them for the Angular SSR schematic that makes it so easy to add SSR to an existing Angular app.
👏 👏 👏
Have a happy Angular time!
Daniel Kreider - Angular Expert