Server-side rendering with Angular | Alain Chautard | ng-conf 2024

Learn how to implement Server-Side Rendering in Angular 17+ for better SEO, faster initial loads, and improved performance. Covers SSR setup, hydration, and best practices.

Key takeaways
  • Server-Side Rendering (SSR) in Angular 17+ can be enabled with a single command: ng add @angular/ssr or by creating new projects with ng new --SSR

  • Key benefits of SSR:

    • Improved initial page load performance
    • Better SEO rankings as content is pre-rendered
    • Reduced cumulative layout shift (CLS)
    • Better performance on mobile and slower devices
  • Two main SSR approaches:

    • Full SSR: Dynamic rendering on server per request (requires Node.js)
    • Static Site Generation (SSG): Pre-renders pages at build time (no Node.js required)
  • Angular hydration allows reusing server-rendered DOM instead of rebuilding everything on client side

  • New lifecycle hooks for SSR:

    • afterRender
    • afterNextRender
    • Help manage server vs client-side code execution
  • Browser-specific APIs (window, document, navigator) must be handled carefully:

    • Only available on client side
    • Need to be wrapped in lifecycle hooks
    • Cannot be used during server-side rendering
  • SSR automatically caches HTTP request results from server and transfers them to client

  • Route discovery is automatic by default but can be customized:

    • Control which routes get pre-rendered
    • Specify routes manually in configuration
    • Mix SSR and client-side rendering as needed
  • Performance improvements:

    • Lighthouse scores can reach 99-100%
    • Instant initial page render
    • Reduced layout shifts
    • Better perceived performance
  • No major code changes required for existing Angular applications when adding SSR