Angular SSR (server-side rendering)

Introduction

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.

CSR

What is server-side rendering (SSR)?

Server-side rendering (SSR) is the process of rendering web pages on the server and sending the fully rendered HTML to the client. In this approach, the server generates the HTML, including any dynamic data, and sends it to the client as a complete page. The client then displays the page without any further processing.

SSR

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.


Similar Articles