### 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: `

My Component

`, }) export class MyComponent { constructor() { const request = inject(REQUEST); console.log(request?.url); } } ``` -------------------------------- ### Disable HTTP Caching Globally Source: https://angular.dev/guide/ssr/index Disables HTTP caching for all requests originating from the server. This is achieved by using the `withNoHttpTransferCache` feature during the application's bootstrap process. This is useful for ensuring that no server-side cached data is used. ```typescript import { bootstrapApplication, provideClientHydration, withNoHttpTransferCache, } from '@angular/platform-browser'; bootstrapApplication(App, { providers: [provideClientHydration(withNoHttpTransferCache())], } ); ``` -------------------------------- ### Override Caching for Specific Requests Source: https://angular.dev/guide/ssr/index Provides a mechanism to override the default HTTP caching behavior for individual requests using the `transferCache` option within the request configuration. This allows for fine-grained control over which requests are cached or excluded from caching. ```typescript // Include specific headers for this request http.get('/api/profile', {transferCache: {includeHeaders: ['CustomHeader']}}); ``` -------------------------------- ### Disable Caching for Individual Requests Source: https://angular.dev/guide/ssr/index Disables HTTP caching for a single, individual request by specifying `transferCache: false` within the `HttpRequest` options. This provides the most granular control over caching, allowing specific requests to bypass the cache entirely. ```typescript httpClient.get('/api/sensitive-data', {transferCache: false}); ``` -------------------------------- ### Configure Non-Node.js Server Request Handler Source: https://angular.dev/guide/ssr/index Sets up a request handler for Angular SSR on platforms other than Node.js using the core `@angular/ssr` package. It leverages standard Web API `Request` and `Response` objects, allowing integration into various server environments. The `createRequestHandler` function facilitates the rendering of Angular applications on these platforms. ```typescript // server.ts import {AngularAppEngine, createRequestHandler} from '@angular/ssr'; const angularApp = new AngularAppEngine(); /** * This is a request handler used by the Angular CLI (dev-server and during build). */ export const reqHandler = createRequestHandler(async (req: Request) => { const res: Response | null = await angularApp.render(req); // ... }); ``` -------------------------------- ### Selectively Disable Caching with Filter Source: https://angular.dev/guide/ssr/index Allows selective disabling of HTTP caching for specific requests using the `filter` option within `withHttpTransferCacheOptions`. This is useful for excluding endpoints that serve user-specific or dynamic data, such as profile information or sensitive data APIs. ```typescript import { bootstrapApplication, provideClientHydration, withHttpTransferCacheOptions, } from '@angular/platform-browser'; bootstrapApplication(App, { providers: [ provideClientHydration( withHttpTransferCacheOptions({ filter: (req) => !req.url.includes('/api/sensitive-data'), }), ), ], } ); ``` -------------------------------- ### Access Document Object Safely with DOCUMENT Token in Angular Source: https://angular.dev/guide/ssr/index This snippet illustrates how to safely access the `document` object in an Angular service, especially when dealing with server-side rendering. It uses the `DOCUMENT` injection token provided by Angular, which resolves to the browser's `document` object in the browser and a different representation on the server, preventing runtime errors. ```typescript import {Injectable, inject, DOCUMENT, ElementRef} from '@angular/core'; @Injectable({providedIn: 'root'}) export class CanonicalLinkService { private readonly document = inject(DOCUMENT); // During server rendering, inject a tag // so the generated HTML includes the correct canonical URL setCanonical(href: string): void { const link = this.document.createElement('link'); link.rel = 'canonical'; link.href = href; this.document.head.appendChild(link); } } ``` -------------------------------- ### Configure Node.js Server Request Handler Source: https://angular.dev/guide/ssr/index Sets up a request handler for Angular SSR within a Node.js environment using `@angular/ssr/node`. It integrates with Express.js to handle incoming requests, process them with the Angular application engine, and write the response back to the Node.js response object. This is essential for running Angular SSR on a Node.js server. ```typescript // server.ts import { AngularNodeAppEngine, createNodeRequestHandler, writeResponseToNodeResponse, } from '@angular/ssr/node'; import express from 'express'; const app = express(); const angularApp = new AngularNodeAppEngine(); app.use('*', (req, res, next) => { angularApp .handle(req) .then((response) => { if (response) { writeResponseToNodeResponse(response, res); } else { next(); // Pass control to the next middleware } }) .catch(next); }); /** * The request handler used by the Angular CLI (dev-server and during build). */ export const reqHandler = createNodeRequestHandler(app); ``` -------------------------------- ### Configure HTTP Transfer Cache Options Source: https://angular.dev/guide/ssr/index Allows customization of HTTP caching behavior, specifically for requests containing authentication headers. By default, requests with 'Authorization' or 'Proxy-Authorization' headers are excluded from caching to prevent caching user-specific responses. Setting `includeRequestsWithAuthHeaders` to `true` enables caching for these requests, which should only be done when authentication headers do not affect the response content. ```typescript withHttpTransferCacheOptions({ includeRequestsWithAuthHeaders: true, }); ``` -------------------------------- ### Execute Browser-Specific Code with afterNextRender in Angular Source: https://angular.dev/guide/ssr/index This snippet demonstrates how to safely execute browser-specific code, such as accessing DOM properties like `scrollHeight`, within an Angular component. It utilizes the `afterNextRender` lifecycle hook, ensuring the code only runs in the browser environment and is skipped during server-side rendering. This prevents errors related to missing browser APIs on the server. ```typescript import {Component, viewChild, afterNextRender, ElementRef} from '@angular/core'; @Component({ selector: 'my-cmp', template: `{{ ... }}`, }) export class MyComponent { contentRef = viewChild.required('content'); constructor() { afterNextRender(() => { // Safe to check `scrollHeight` because this will only run in the browser, not the server. console.log('content height: ' + this.contentRef().nativeElement.scrollHeight); }); } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.