Angular Universal is a technology that allows server-side rendering (SSR) of Angular applications. It enables the application to generate the HTML and CSS on the server-side rather than on the client-side (browser), which is the traditional behavior of Angular applications.
The primary benefits of using Angular Universal for SSR include:
1. Improved performance: By rendering on the server side, the application’s initial loading time is significantly reduced as the browser receives pre-rendered HTML and CSS. This results in a faster time to first paint (TTFP) and time to interactive (TTI), leading to better user experience and Performance Index scores.
2. Better SEO (Search Engine Optimization): As search engine crawlers can now see the rendered HTML, it becomes easier for web crawlers to parse and index the website’s content. This leads to an improved search engine ranking.
3. Enhanced Compatibility: Some older browsers, low-powered devices or users with slow internet connections may struggle to load heavy client-side applications. By utilizing SSR, the initial load is more lightweight, allowing these browsers, devices, and users to better interact with the application.
4. Social Sharing: Many social media platforms rely on the initial static HTML to generate a preview card for sharing. With SSR, the pre-rendered HTML ensures better compatibility with these sharing preview cards.
To implement Angular Universal in a project, you’ll need to proceed with the following steps:
1. Install the required package:
ng add @nguniversal/express-engine --clientProject your_project_name
2. Modify/add files to enable SSR, and adapt your Angular application for SSR. The above command will update your ‘src/app/app.module.ts‘, ‘src/app.app.server.module.ts‘, ‘src/main.ts‘, and create a new ‘src/main.server.ts‘.
3. Modify the Angular application to enable TransferState API to avoid duplicate HTTP requests between the server and client when fetching data.
4. Build and serve the SSR application using the following commands:
npm run build:ssr && npm run serve:ssr
After these steps, your Angular application will be configured to use Angular Universal for server-side rendering.
Finally, consider the following notes when using Angular Universal:
- Be careful with browser-specific code or direct DOM manipulations, as they will not work with SSR.
- Make use of Angular lifecycle hooks, like OnInit or AfterViewInit, to enhance application compatibility with SSR.
- If still not working, wrap browser-dependent code with a platform check using Angular’s ‘isPlatformBrowser‘.
Here’s an example of a schematic explaining Angular Universal:
With Angular Universal, you are now able to perform effective server-side rendering for your Angular application, improving its performance, search engine optimization, and compatibility with a broad range of scenarios.