diff --git a/packages/angular/ssr/src/app.ts b/packages/angular/ssr/src/app.ts index fdf13108e95b..77c9b16090f6 100644 --- a/packages/angular/ssr/src/app.ts +++ b/packages/angular/ssr/src/app.ts @@ -24,6 +24,7 @@ import { ServerRouter } from './routes/router'; import { AngularBootstrap, renderAngular } from './utils/ng'; import { promiseWithAbort } from './utils/promise'; import { createRedirectResponse } from './utils/redirect'; +import { SSR_REQUEST_HEADER, createSsrRequestResponse } from './utils/ssr-request'; import { buildUrlWithParams, joinUrlParts, stripLeadingSlash } from './utils/url'; import { getFirstHeaderValue } from './utils/validation'; @@ -317,6 +318,12 @@ export class AngularServerApp { return new Response(html, responseInit); } + if (request.headers.has(SSR_REQUEST_HEADER)) { + // The application sent this request to its own host while it was rendered on the server. + // Rendering it could render a page that sends the same request again, without bound. + return createSsrRequestResponse(); + } + if (locale !== undefined) { platformProviders.push({ provide: LOCALE_ID, diff --git a/packages/angular/ssr/src/routes/route-config.ts b/packages/angular/ssr/src/routes/route-config.ts index 62127f82f966..1b79f038ea7e 100644 --- a/packages/angular/ssr/src/routes/route-config.ts +++ b/packages/angular/ssr/src/routes/route-config.ts @@ -6,6 +6,7 @@ * found in the LICENSE file at https://angular.dev/license */ +import { ɵHTTP_ROOT_INTERCEPTOR_FNS as HTTP_ROOT_INTERCEPTOR_FNS } from '@angular/common/http'; import { EnvironmentProviders, InjectionToken, @@ -17,6 +18,7 @@ import { } from '@angular/core'; import { provideServerRendering as provideServerRenderingPlatformServer } from '@angular/platform-server'; import { type DefaultExport, ROUTES, type Route } from '@angular/router'; +import { ssrRequestInterceptorFn } from '../utils/ssr-request'; /** * The internal path used for the app shell route. @@ -448,6 +450,8 @@ export function provideServerRendering( const providers: (Provider | EnvironmentProviders)[] = [ provideServerRenderingPlatformServer(options), + // Registered after the platform server providers, so that relative URLs are already resolved. + { provide: HTTP_ROOT_INTERCEPTOR_FNS, useValue: ssrRequestInterceptorFn, multi: true }, ]; let hasAppShell = false; diff --git a/packages/angular/ssr/src/utils/ssr-request.ts b/packages/angular/ssr/src/utils/ssr-request.ts new file mode 100644 index 000000000000..faeb45c25d02 --- /dev/null +++ b/packages/angular/ssr/src/utils/ssr-request.ts @@ -0,0 +1,65 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +import { PlatformLocation } from '@angular/common'; +import type { HttpInterceptorFn } from '@angular/common/http'; +import { inject } from '@angular/core'; + +/** + * The header added to the HTTP requests that an application sends to its own host while it is + * rendered on the server. The server does not render requests that carry it. + */ +export const SSR_REQUEST_HEADER = 'x-angular-ssr-request'; + +/** + * Adds the {@link SSR_REQUEST_HEADER} header to the requests sent to the host of the page being + * rendered. Such a request could otherwise be rendered as a page that sends the same request again, + * without bound. + * + * Host names are compared rather than origins: behind a proxy that terminates TLS, the page is + * rendered for `http:` while the application may call its public `https:` URL. + * + * This interceptor must run after the `@angular/platform-server` interceptor that resolves relative + * URLs. Requests that are not sent through the `HttpClient` interceptors are not marked. + */ +export const ssrRequestInterceptorFn: HttpInterceptorFn = (request, next) => { + const { href, hostname } = inject(PlatformLocation); + if (!URL.canParse(href)) { + // The URL of the page is unknown, so requests sent to its host cannot be recognized. + return next(request); + } + + // URLs that cannot be parsed are marked too: some HTTP clients still send a request for them. + if ( + URL.canParse(request.urlWithParams, href) && + new URL(request.urlWithParams, href).hostname !== hostname + ) { + return next(request); + } + + return next(request.clone({ setHeaders: { [SSR_REQUEST_HEADER]: '1' } })); +}; + +/** + * Creates the response to a request that the application sent to its own host while it was + * rendered on the server. The request is not rendered. The response is only meaningful to the + * render that sent the request, so it does not include the headers configured for the route and + * must not be stored. + * + * @returns A `Response` object with a 400 status code. + */ +export function createSsrRequestResponse(): Response { + return new Response('Requests sent while rendering on the server are not rendered.', { + status: 400, + statusText: 'Bad Request', + headers: { + 'Content-Type': 'text/plain', + 'Cache-Control': 'no-store', + }, + }); +} diff --git a/packages/angular/ssr/test/app_spec.ts b/packages/angular/ssr/test/app_spec.ts index 45e501af4e84..566e7e9ed59e 100644 --- a/packages/angular/ssr/test/app_spec.ts +++ b/packages/angular/ssr/test/app_spec.ts @@ -12,6 +12,7 @@ import '@angular/compiler'; /* eslint-enable import/no-unassigned-import */ import { APP_BASE_HREF } from '@angular/common'; +import { HttpClient, provideHttpClient } from '@angular/common/http'; import { Component, DestroyRef, @@ -20,12 +21,14 @@ import { REQUEST, RESPONSE_INIT, inject, + signal, } from '@angular/core'; import { ActivatedRoute, CanActivateFn, Router } from '@angular/router'; import { setTimeout } from 'node:timers/promises'; import { AngularServerApp } from '../src/app'; import { Hooks } from '../src/hooks'; import { RenderMode } from '../src/routes/route-config'; +import { SSR_REQUEST_HEADER } from '../src/utils/ssr-request'; import { setAngularAppTestingManifest } from './testing-utils'; describe('AngularServerApp', () => { @@ -818,5 +821,113 @@ describe('AngularServerApp', () => { }); }); }); + + describe('requests sent while rendering on the server', () => { + @Component({ + selector: 'app-request', + template: `{{ response() }}`, + }) + class RequestComponent { + protected readonly response = signal(''); + + constructor() { + inject(HttpClient) + .get(inject(ActivatedRoute).snapshot.data['url'], { responseType: 'text' }) + .subscribe({ + next: (value) => this.response.set(value), + error: () => this.response.set('Request failed'), + }); + } + } + + /** Creates an application whose pages request the given URL while they are rendered. */ + function createAppRequesting(url: string): AngularServerApp { + setAngularAppTestingManifest( + [{ path: '**', component: RequestComponent, data: { url } }], + [{ path: '**', renderMode: RenderMode.Server }], + undefined, + undefined, + undefined, + undefined, + [provideHttpClient()], + ); + + return new AngularServerApp(); + } + + beforeEach(() => { + setupManifest(); + }); + + it('should return a 400 response that is not stored for routes requested while rendering', async () => { + const response = await app.handle( + new Request('http://localhost/page-with-headers', { + headers: { [SSR_REQUEST_HEADER]: '' }, + }), + ); + + expect(response?.status).toBe(400); + expect(Object.fromEntries(response?.headers.entries() ?? [])).toEqual({ + 'cache-control': 'no-store', + 'content-type': 'text/plain', + }); + }); + + it('should serve prerendered pages, redirects and client-side rendered routes requested while rendering', async () => { + const headers = { [SSR_REQUEST_HEADER]: '1' }; + + const redirect = await app.handle(new Request('http://localhost/redirect', { headers })); + expect(redirect?.headers.get('location')).toBe('/home'); + + const prerendered = await app.handle(new Request('http://localhost/home-ssg', { headers })); + expect(await prerendered?.text()).toContain('Home SSG works'); + + const clientSide = await app.handle(new Request('http://localhost/home-csr', { headers })); + expect(await clientSide?.text()).toContain('CSR page'); + }); + + it('should not render the requests that a page sends to its own host', async () => { + const requestingApp = createAppRequesting('/api'); + let requestCount = 0; + let requestStatus: number | undefined; + spyOn(globalThis, 'fetch').and.callFake(async (input, init) => { + // Stop the loop that renders the page again for each of its own requests. + if (++requestCount > 5) { + return new Response(null, { status: 508 }); + } + + const response = + (await requestingApp.handle(new Request(input, init))) ?? + new Response(null, { status: 404 }); + requestStatus = response.status; + + return response; + }); + + const response = await requestingApp.handle(new Request('http://localhost/page')); + expect(await response?.text()).toContain('Request failed'); + expect(requestCount).toBe(1); + expect(requestStatus).toBe(400); + }); + + it(`should add the '${SSR_REQUEST_HEADER}' header only to requests sent to the host of the page`, async () => { + const fetchSpy = spyOn(globalThis, 'fetch').and.callFake( + async () => new Response('Request works'), + ); + + for (const url of ['http://example.com/api', 'https://localhost:8443/api']) { + const response = await createAppRequesting(url).handle( + new Request('http://localhost/page'), + ); + expect(await response?.text()).toContain('Request works'); + } + + const requests = fetchSpy.calls.allArgs().map(([input, init]) => new Request(input, init)); + expect(requests.map(({ url, headers }) => [url, headers.has(SSR_REQUEST_HEADER)])).toEqual([ + ['http://example.com/api', false], + ['https://localhost:8443/api', true], + ]); + }); + }); }); });