Angular Universal provides server-side rendering (SSR) capabilities for Angular applications. SSR improves performance and SEO by rendering the initial HTML on the server before sending it to the client. This documentation outlines the steps to implement Angular SSR using Angular Universal.

What is client-side rendering (CSR)?
Client-side rendering (CSR) is the process of rendering web pages in the browser using JavaScript. The server sends a minimal HTML file along with JavaScript, which then dynamically generates and updates the content. This approach enables more interactive and responsive web pages by allowing specific parts of the page to be updated without a full page reload.


Server-side rendering (SSR): what is it?
The process of rendering web pages on the server and delivering the completely rendered HTML to the client is known as server-side rendering, or SSR. With this method, the client receives the HTML page in its entirety, generated by the server together with any dynamic data. After that, the client shows the page without doing any additional processing.


Steps to implement Angular SSR using Angular Universal.

Step 1. Set Up Angular Application

Create a new Angular application if you don't have one already.
ng new project-name

Step 2. Add Angular Universal
Add Angular Universal to your application.
ng add @nguniversal/express-engine

Step 3. Add non-destructive hydration

To enable non-destructive hydration, we need to import the provideClientHydration function as the provider of AppModule.
import { provideClientHydration } from '@angular/platform-browser';
// ...

@NgModule({
  // ...
  providers: [provideClientHydration()],  // add this line
  bootstrap: [AppComponent]
})
export class AppModule {
  // ...
}

Step 4. Update the Angular Configuration

Ensure your angular.json includes SSR configurations. This should be done automatically when you add Angular Universal.

Step 5. Update Server Files
const ssrRoutes = ['/test'];

// All regular routes use the Universal engine
server.get('*', (req, res) => {
  if (ssrRoutes.some((route) => req.url.startsWith(route))) {
    res.render(indexHtml, {
      req,
      providers: [{ provide: APP_BASE_HREF, useValue: req.baseUrl }]
    });
  } else {
    res.sendFile(join(distFolder, 'index.html'));
  }
});

Step 6. Serve the Application

npm run dev:ssr

Conclusion

By following these steps, you can implement server-side rendering in your Angular application using Angular Universal. SSR enhances performance and improves SEO by serving pre-rendered HTML content to the client.