### Create New Angular Project with SSR Source: https://angular.dev/guide/ssr/index This command initializes a new Angular project with server-side rendering capabilities enabled by default. ```bash ng new --ssr ``` -------------------------------- ### Add SSR to Existing Angular Project Source: https://angular.dev/guide/ssr/index This command integrates server-side rendering support into an existing Angular application. ```bash ng add @angular/ssr ``` -------------------------------- ### Provide Server Rendering with Routes Source: https://angular.dev/guide/ssr/index Configures the application to use server rendering with the specified server routes. This is done in the `app.config.server.ts` file. ```typescript import {provideServerRendering, withRoutes} from '@angular/ssr'; import {serverRoutes} from './app.routes.server'; // app.config.server.ts const serverConfig: ApplicationConfig = { providers: [ provideServerRendering(withRoutes(serverRoutes)), // ... other providers ... ], }; ``` -------------------------------- ### Inject and Use Analytics Service in Angular Component Source: https://angular.dev/guide/ssr/index This example shows how to inject the `AnalyticsService` into an Angular component using the `inject` function. The component can then use the injected service to track events, leveraging the platform-specific implementation provided during configuration. ```typescript import {Component, inject} from '@angular/core'; import {AnalyticsService} from './analytics.service'; // Adjust path as needed @Component({ selector: 'checkout-cmp', template: ``, }) export class Checkout { private analytics = inject(AnalyticsService); onAction(): void { this.analytics.trackEvent('checkout_action'); } } ``` -------------------------------- ### Configure HttpClient Caching with HttpTransferCacheOptions Source: https://angular.dev/guide/ssr/index Illustrates how to configure HttpClient caching options for server-side rendering and client hydration in Angular. This example uses `provideClientHydration` with `withHttpTransferCacheOptions` to customize caching behavior, including specific headers, request filtering, and handling POST requests. ```typescript import { bootstrapApplication } from '@angular/platform-browser'; import { provideClientHydration, withHttpTransferCacheOptions } from '@angular/platform-browser'; bootstrapApplication(App, { providers: [ provideClientHydration( withHttpTransferCacheOptions({ includeHeaders: ['ETag', 'Cache-Control'], filter: (req) => !req.url.includes('/api/profile'), includePostRequests: true, includeRequestsWithAuthHeaders: false, }), ), ], }); ``` -------------------------------- ### Provide Server Rendering with App Shell Source: https://angular.dev/guide/ssr/index Configures server rendering to use a specified App Shell component for client-side rendered routes, enhancing the initial user experience. This is done in `app.config.server.ts`. ```typescript import {provideServerRendering, withRoutes, withAppShell} from '@angular/ssr'; import {AppShell} from './app-shell'; const serverConfig: ApplicationConfig = { providers: [ provideServerRendering(withRoutes(serverRoutes), withAppShell(AppShell)), // ... other providers ... ], }; ``` -------------------------------- ### Configure Server Routes for Hybrid Rendering Source: https://angular.dev/guide/ssr/index Defines an array of ServerRoute objects to configure how different routes are rendered (Client, Prerender, Server). This configuration is typically placed in `app.routes.server.ts`. ```typescript // app.routes.server.ts import {RenderMode, ServerRoute} from '@angular/ssr'; export const serverRoutes: ServerRoute[] = [ { path: '', // This renders the "/" route on the client (CSR) renderMode: RenderMode.Client, }, { path: 'about', // This page is static, so we prerender it (SSG) renderMode: RenderMode.Prerender, }, { path: 'profile', // This page requires user-specific data, so we use SSR renderMode: RenderMode.Server, }, { path: '**', // All other routes will be rendered on the server (SSR) renderMode: RenderMode.Server, }, ]; ``` -------------------------------- ### Configure Fallback Strategies for Prerendered Routes Source: https://angular.dev/guide/ssr/index Define how to handle requests for paths not prerendered when using `RenderMode.Prerender`. Options include falling back to server-side rendering (default), client-side rendering, or no fallback at all. ```typescript import {RenderMode, PrerenderFallback, ServerRoute} from '@angular/ssr'; export const serverRoutes: ServerRoute[] = [ { path: 'post/:id', renderMode: RenderMode.Prerender, fallback: PrerenderFallback.Client, // Fallback to CSR if not prerendered async getPrerenderParams() { // This function returns an array of objects representing prerendered posts at the paths: // `/post/1`, `/post/2`, and `/post/3`. // The path `/post/4` will utilize the fallback behavior if it's requested. return [{id: 1}, {id: 2}, {id: 3}]; }, }, ]; ``` -------------------------------- ### Implement Server-Specific Analytics Service in Angular Source: https://angular.dev/guide/ssr/index This code defines the server-side implementation of the `AnalyticsService`. The `ServerAnalyticsService` implements the `trackEvent` method to record events on the server, which can be useful for logging or other server-side analytics. ```typescript import {Injectable} from '@angular/core'; import {AnalyticsService} from './analytics.service'; // Assuming AnalyticsService is in the same directory @Injectable() export class ServerAnalyticsService implements AnalyticsService { trackEvent(name: string): void { // Records the event on the server console.log(`Recording event on server: ${name}`); } } ``` -------------------------------- ### Implement Browser-Specific Analytics Service in Angular Source: https://angular.dev/guide/ssr/index This snippet provides a concrete implementation of the `AnalyticsService` for browser environments. The `BrowserAnalyticsService` implements the `trackEvent` method to send events to a third-party analytics provider in the browser. ```typescript import {Injectable} from '@angular/core'; import {AnalyticsService} from './analytics.service'; // Assuming AnalyticsService is in the same directory @Injectable() export class BrowserAnalyticsService implements AnalyticsService { trackEvent(name: string): void { // Sends the event to the browser-based third-party analytics provider console.log(`Tracking event on browser: ${name}`); } } ``` -------------------------------- ### Specify Headers for HttpClient Caching Source: https://angular.dev/guide/ssr/index Demonstrates how to use the `includeHeaders` option within `withHttpTransferCacheOptions` to specify which response headers should be included in cached HTTP entries during Angular SSR. By default, no headers are included. ```typescript withHttpTransferCacheOptions({ includeHeaders: ['ETag', 'Cache-Control'], }); ``` -------------------------------- ### Configure Browser Analytics Service in Angular App Source: https://angular.dev/guide/ssr/index This configuration snippet shows how to register the `BrowserAnalyticsService` as the provider for `AnalyticsService` in the main Angular application configuration (`app.config.ts`). This ensures that the browser implementation is used when the application runs in a browser environment. ```typescript import {ApplicationConfig} from '@angular/core'; import {BrowserAnalyticsService} from './browser-analytics.service'; // Adjust path as needed export const appConfig: ApplicationConfig = { providers: [{provide: AnalyticsService, useClass: BrowserAnalyticsService}], }; ``` -------------------------------- ### Customize Build-Time Prerendering with Parameterized Routes Source: https://angular.dev/guide/ssr/index Control which specific parameters generate separate prerendered documents for routes using `RenderMode.Prerender`. The `getPrerenderParams` function returns a promise resolving to an array of parameter objects, enabling dynamic route generation at build time. It can inject dependencies and handle catch-all routes. ```typescript import {RenderMode, ServerRoute, inject} from '@angular/ssr'; export const serverRoutes: ServerRoute[] = [ { path: 'post/:id', renderMode: RenderMode.Prerender, async getPrerenderParams() { const dataService = inject(PostService); // Assuming PostService is available const ids = await dataService.getIds(); // Example: returns ['1', '2', '3'] return ids.map((id) => ({id})); // Generates paths like: /post/1, /post/2, /post/3 }, }, { path: 'post/:id/**', renderMode: RenderMode.Prerender, async getPrerenderParams() { return [ {id: '1', '**': 'foo/3'}, {id: '2', '**': 'bar/4'}, ]; // Generates paths like: /post/1/foo/3, /post/2/bar/4 }, }, ]; ``` -------------------------------- ### Configure Angular SSR Output Mode to Static Source: https://angular.dev/guide/ssr/index Shows how to configure an Angular project to generate a fully static application by setting the `outputMode` to `static` in the `angular.json` file. This disables the generation of a server file, making the application suitable for static hosting. ```json { "projects": { "your-app": { "architect": { "build": { "options": { "outputMode": "static" } } } } } } ``` -------------------------------- ### Configure Server Analytics Service in Angular Server App Source: https://angular.dev/guide/ssr/index This configuration snippet demonstrates how to override the `AnalyticsService` with the `ServerAnalyticsService` in the server-side application configuration (`app.config.server.ts`). This ensures that the server implementation is used during server-side rendering. ```typescript import {ApplicationConfig} from '@angular/core'; import {ServerAnalyticsService} from './server-analytics.service'; // Adjust path as needed const serverConfig: ApplicationConfig = { providers: [{provide: AnalyticsService, useClass: ServerAnalyticsService}], }; export default serverConfig; ``` -------------------------------- ### Set Custom Headers and Status Codes for Server Routes Source: https://angular.dev/guide/ssr/index Configure custom HTTP headers and status codes for individual server routes using the `headers` and `status` properties within the `ServerRoute` configuration. This allows for fine-grained control over responses for specific routes. ```typescript import {RenderMode, ServerRoute} from '@angular/ssr'; export const serverRoutes: ServerRoute[] = [ { path: 'profile', renderMode: RenderMode.Server, headers: { 'X-My-Custom-Header': 'some-value', }, status: 201, }, // ... other routes ]; ``` -------------------------------- ### Enable Caching for POST Requests in HttpClient Source: https://angular.dev/guide/ssr/index Shows how to enable caching for POST requests in Angular's HttpClient during SSR using the `includePostRequests` option within `withHttpTransferCacheOptions`. This is useful for idempotent POST operations like GraphQL queries. ```typescript withHttpTransferCacheOptions({ includePostRequests: true, }); ``` -------------------------------- ### Define Abstract Analytics Service in Angular Source: https://angular.dev/guide/ssr/index This code defines an abstract base class for an analytics service. It declares an abstract method `trackEvent` that must be implemented by concrete subclasses. This pattern allows for platform-specific implementations of analytics tracking. ```typescript export abstract class AnalyticsService { abstract trackEvent(name: string): void; } ``` -------------------------------- ### Access Request Object in Angular SSR Component Source: https://angular.dev/guide/ssr/index Demonstrates how to inject and use the REQUEST token within an Angular component during server-side rendering to access request details like the URL. This token is provided by `@angular/core` and is only available in SSR environments. ```typescript import { inject, REQUEST } from '@angular/core'; @Component({ selector: 'app-my-component', template: `