diff --git a/packages/angular/ssr/src/app-engine.ts b/packages/angular/ssr/src/app-engine.ts index 8afa2bbad822..a65dbbf2e413 100644 --- a/packages/angular/ssr/src/app-engine.ts +++ b/packages/angular/ssr/src/app-engine.ts @@ -11,6 +11,7 @@ import { Hooks } from './hooks'; import { getPotentialLocaleIdFromUrl, getPreferredLocale } from './i18n'; import { EntryPointExports, getAngularAppEngineManifest } from './manifest'; import { createRedirectResponse } from './utils/redirect'; +import { createSsrRequestResponse, isSsrRequest } from './utils/ssr-request'; import { joinUrlParts } from './utils/url'; import { getFirstHeaderValue, @@ -212,6 +213,10 @@ export class AngularAppEngine { if (preferredLocale) { const subPath = supportedLocales[preferredLocale]; if (subPath !== undefined) { + if (isSsrRequest(request)) { + return createSsrRequestResponse(request); + } + const prefix = getFirstHeaderValue(request.headers.get('X-Forwarded-Prefix')) ?? ''; return createRedirectResponse( diff --git a/packages/angular/ssr/src/app.ts b/packages/angular/ssr/src/app.ts index fdf13108e95b..c6fb4983d9be 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 { createSsrRequestResponse, isSsrRequest } from './utils/ssr-request'; import { buildUrlWithParams, joinUrlParts, stripLeadingSlash } from './utils/url'; import { getFirstHeaderValue } from './utils/validation'; @@ -159,6 +160,12 @@ export class AngularServerApp { return null; } + if (!this.router && !this.manifest.routes && isSsrRequest(request)) { + // Avoid triggering or awaiting route extraction (which bootstraps the app and may + // deadlock on the in-flight extraction promise) for requests sent during SSR. + return createSsrRequestResponse(request); + } + this.router ??= await ServerRouter.from(this.manifest, url); const matchedRoute = this.router.match(url); @@ -170,6 +177,10 @@ export class AngularServerApp { const { redirectTo, relativeRedirect, status, renderMode, headers } = matchedRoute; if (redirectTo !== undefined) { + if (isSsrRequest(request)) { + return createSsrRequestResponse(request); + } + const location = joinUrlParts( getFirstHeaderValue(request.headers.get('X-Forwarded-Prefix')) ?? '', buildUrlWithParams(redirectTo, url.pathname, relativeRedirect ? undefined : url.search), @@ -271,6 +282,12 @@ export class AngularServerApp { return null; } + if (renderMode !== RenderMode.Client && isSsrRequest(request)) { + // 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(request); + } + const url = new URL(request.url); const platformProviders: StaticProvider[] = []; 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..64cf352001de --- /dev/null +++ b/packages/angular/ssr/src/utils/ssr-request.ts @@ -0,0 +1,46 @@ +/** + * @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 { + ɵSSR_REQUEST_HEADER as SSR_REQUEST_HEADER, + ɵisSsrRequest as isSsrRequest, +} from '@angular/platform-server'; + +export { SSR_REQUEST_HEADER, isSsrRequest }; + +/** + * Creates a non-cached response for an incoming request that carries the + * {@link SSR_REQUEST_HEADER} header, indicating it was sent by an Angular application + * while rendering on the server. + * + * A `404 Not Found` status with `Cache-Control: no-store` is returned instead of `400` + * because some CDNs (such as CloudFront) ignore `Cache-Control: no-store` on `400` + * responses and cache them by default, whereas `404` honors `no-store` without + * triggering 5xx outlier ejection. + * + * @param request - The incoming recursive SSR `Request`. + * @returns A `Response` object with a `404` status code and `Cache-Control: no-store`. + */ +export function createSsrRequestResponse(request: Request): Response { + if (typeof ngDevMode === 'undefined' || ngDevMode) { + // eslint-disable-next-line no-console + console.warn( + `Refusing to handle request for "${request.url}" because it carries the ` + + `"${SSR_REQUEST_HEADER}" header, indicating it was sent while rendering on the server.`, + ); + } + + return new Response('Requests sent while rendering on the server are not rendered.', { + status: 404, + statusText: 'Not Found', + headers: { + 'Content-Type': 'text/plain', + 'Cache-Control': 'no-store', + }, + }); +} diff --git a/packages/angular/ssr/test/app-engine_spec.ts b/packages/angular/ssr/test/app-engine_spec.ts index db03015b85f1..4190619a2ef2 100644 --- a/packages/angular/ssr/test/app-engine_spec.ts +++ b/packages/angular/ssr/test/app-engine_spec.ts @@ -16,6 +16,7 @@ import { destroyAngularServerApp, getOrCreateAngularServerApp } from '../src/app import { AngularAppEngine } from '../src/app-engine'; import { setAngularAppEngineManifest } from '../src/manifest'; import { RenderMode } from '../src/routes/route-config'; +import { SSR_REQUEST_HEADER } from '../src/utils/ssr-request'; import { setAngularAppTestingManifest } from './testing-utils'; @Component({ @@ -235,6 +236,28 @@ describe('AngularAppEngine', () => { const response = await appEngine.handle(request); expect(response).toBeNull(); }); + + it('should return a non-cached 404 instead of redirecting on "/" for recursive SSR requests', async () => { + spyOn(console, 'warn'); + const request = new Request('https://example.com', { + headers: { + 'Accept-Language': 'it', + [SSR_REQUEST_HEADER]: '1', + }, + }); + const response = await appEngine.handle(request); + expect(response?.status).toBe(404); + expect(response?.headers.get('Location')).toBeNull(); + expect(response?.headers.get('Cache-Control')).toBe('no-store'); + }); + + it('should still return null for unknown paths carrying the SSR request header', async () => { + const request = new Request('https://example.com/unknown/page', { + headers: { [SSR_REQUEST_HEADER]: '1' }, + }); + const response = await appEngine.handle(request); + expect(response).toBeNull(); + }); }); }); diff --git a/packages/angular/ssr/test/app_spec.ts b/packages/angular/ssr/test/app_spec.ts index 45e501af4e84..d2b68e9882ba 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,16 @@ import { REQUEST, RESPONSE_INIT, inject, + provideAppInitializer, + 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 { ServerRouter } from '../src/routes/router'; +import { SSR_REQUEST_HEADER } from '../src/utils/ssr-request'; import { setAngularAppTestingManifest } from './testing-utils'; describe('AngularServerApp', () => { @@ -818,5 +823,234 @@ 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(); + spyOn(console, 'warn'); + }); + + afterEach(() => { + setupManifest(); + }); + + it('should reject recursive SSR requests before route extraction on cold start', async () => { + const fromSpy = spyOn(ServerRouter, 'from').and.callThrough(); + const response = await app.handle( + new Request('http://localhost/home', { + headers: { [SSR_REQUEST_HEADER]: '1' }, + }), + ); + + expect(fromSpy).not.toHaveBeenCalled(); + expect(response?.status).toBe(404); + expect(Object.fromEntries(response?.headers.entries() ?? [])).toEqual({ + 'cache-control': 'no-store', + 'content-type': 'text/plain', + }); + }); + + it('should avoid deadlocking when route extraction triggers a self-request on cold start', async () => { + setAngularAppTestingManifest( + [ + { path: 'home', component: HomeComponent }, + { path: '**', component: HomeComponent }, + ], + [{ path: '**', renderMode: RenderMode.Server }], + undefined, + undefined, + undefined, + undefined, + [ + provideHttpClient(), + provideAppInitializer(() => { + const http = inject(HttpClient); + + return new Promise((resolve) => { + http.get('/api', { responseType: 'text' }).subscribe({ + next: () => resolve(), + error: () => resolve(), + }); + }); + }), + ], + ); + + const coldApp = new AngularServerApp(); + const handledResponses: Array = []; + spyOn(globalThis, 'fetch').and.callFake(async (input, init) => { + if (handledResponses.length >= 5) { + return new Response(null, { status: 508 }); + } + + const response = await coldApp.handle(new Request(input, init)); + handledResponses.push(response); + + return response ?? new Response(null, { status: 500 }); + }); + + const response = await coldApp.handle(new Request('http://localhost/home')); + expect(await response?.text()).toContain('Home works'); + expect(handledResponses.length).toBe(2); + for (const handled of handledResponses) { + expect(handled?.status).toBe(404); + expect(handled?.headers.get('cache-control')).toBe('no-store'); + } + }); + + it('should return a non-cached 404 response for SSR routes requested while rendering', async () => { + // Warm the router so the request proceeds past cold-start extraction. + await app.handle(new Request('http://localhost/home')); + + const response = await app.handle( + new Request('http://localhost/page-with-headers', { + headers: { [SSR_REQUEST_HEADER]: '' }, + }), + ); + + expect(response?.status).toBe(404); + expect(response?.statusText).toBe('Not Found'); + expect(Object.fromEntries(response?.headers.entries() ?? [])).toEqual({ + 'cache-control': 'no-store', + 'content-type': 'text/plain', + }); + }); + + it('should return a non-cached 404 response for static redirects requested while rendering', async () => { + await app.handle(new Request('http://localhost/home')); + + const response = await app.handle( + new Request('http://localhost/redirect', { + headers: { [SSR_REQUEST_HEADER]: '1' }, + }), + ); + + expect(response?.status).toBe(404); + expect(response?.headers.get('location')).toBeNull(); + expect(Object.fromEntries(response?.headers.entries() ?? [])).toEqual({ + 'cache-control': 'no-store', + 'content-type': 'text/plain', + }); + }); + + it('should serve prerendered pages and client-side rendered routes requested while rendering', async () => { + await app.handle(new Request('http://localhost/home')); + + const headers = { [SSR_REQUEST_HEADER]: '1' }; + + const prerendered = await app.handle(new Request('http://localhost/home-ssg', { headers })); + expect(prerendered?.status).toBe(200); + expect(await prerendered?.text()).toContain('Home SSG works'); + + const clientSide = await app.handle(new Request('http://localhost/home-csr', { headers })); + expect(clientSide?.status).toBe(200); + expect(await clientSide?.text()).toContain('CSR page'); + }); + + it('should reject on-demand rendering of prerendered routes when allowStaticRouteRender is true', async () => { + setAngularAppTestingManifest( + [ + { path: 'home', component: HomeComponent }, + { path: 'ssg-missing', component: HomeComponent }, + ], + [ + { path: 'home', renderMode: RenderMode.Server }, + { path: 'ssg-missing', renderMode: RenderMode.Prerender }, + ], + ); + + const devApp = new AngularServerApp({ allowStaticRouteRender: true }); + await devApp.handle(new Request('http://localhost/home')); + + const devResponse = await devApp.handle( + new Request('http://localhost/ssg-missing', { + headers: { [SSR_REQUEST_HEADER]: '1' }, + }), + ); + expect(devResponse?.status).toBe(404); + expect(devResponse?.headers.get('cache-control')).toBe('no-store'); + + const prodApp = new AngularServerApp({ allowStaticRouteRender: false }); + await prodApp.handle(new Request('http://localhost/home')); + + const prodResponse = await prodApp.handle( + new Request('http://localhost/ssg-missing', { + headers: { [SSR_REQUEST_HEADER]: '1' }, + }), + ); + expect(prodResponse).toBeNull(); + }); + + it('should return null for non-Angular routes when router is initialized', async () => { + setAngularAppTestingManifest( + [{ path: 'home', component: HomeComponent }], + [{ path: 'home', renderMode: RenderMode.Server }], + ); + + const limitedApp = new AngularServerApp(); + await limitedApp.handle(new Request('http://localhost/home')); + + const response = await limitedApp.handle( + new Request('http://localhost/api/users', { + headers: { [SSR_REQUEST_HEADER]: '1' }, + }), + ); + expect(response).toBeNull(); + }); + + it('should not render the requests that a page sends to its own host', async () => { + const requestingApp = createAppRequesting('/api'); + const handledResponses: Array = []; + spyOn(globalThis, 'fetch').and.callFake(async (input, init) => { + // Stop the loop that renders the page again for each of its own requests. + if (handledResponses.length >= 5) { + return new Response(null, { status: 508 }); + } + + const response = await requestingApp.handle(new Request(input, init)); + handledResponses.push(response); + + return response ?? new Response(null, { status: 500 }); + }); + + const response = await requestingApp.handle(new Request('http://localhost/page')); + expect(await response?.text()).toContain('Request failed'); + expect(handledResponses.length).toBe(1); + expect(handledResponses[0]?.status).toBe(404); + expect(handledResponses[0]?.headers.get('cache-control')).toBe('no-store'); + }); + }); }); }); diff --git a/packages/angular/ssr/test/utils/ssr-request_spec.ts b/packages/angular/ssr/test/utils/ssr-request_spec.ts new file mode 100644 index 000000000000..8b8a8381b218 --- /dev/null +++ b/packages/angular/ssr/test/utils/ssr-request_spec.ts @@ -0,0 +1,69 @@ +/** + * @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 { SSR_REQUEST_HEADER, createSsrRequestResponse } from '../../src/utils/ssr-request'; + +describe('SSR Request Utils', () => { + describe('createSsrRequestResponse', () => { + it('should return a 404 response with Cache-Control: no-store', async () => { + spyOn(console, 'warn'); + const response = createSsrRequestResponse( + new Request('https://example.com/api', { + headers: { [SSR_REQUEST_HEADER]: '1' }, + }), + ); + + expect(response.status).toBe(404); + expect(response.statusText).toBe('Not Found'); + expect(Object.fromEntries(response.headers.entries())).toEqual({ + 'cache-control': 'no-store', + 'content-type': 'text/plain', + }); + expect(await response.text()).toBe( + 'Requests sent while rendering on the server are not rendered.', + ); + }); + + it('should emit a warning in dev mode', () => { + // @ts-expect-error accessing global + const previousNgDevMode = globalThis.ngDevMode; + // @ts-expect-error accessing global + globalThis.ngDevMode = true; + + try { + const warnSpy = spyOn(console, 'warn'); + createSsrRequestResponse(new Request('https://example.com/api')); + + expect(warnSpy).toHaveBeenCalledWith( + `Refusing to handle request for "https://example.com/api" because it carries the ` + + `"${SSR_REQUEST_HEADER}" header, indicating it was sent while rendering on the server.`, + ); + } finally { + // @ts-expect-error accessing global + globalThis.ngDevMode = previousNgDevMode; + } + }); + + it('should not emit a warning when ngDevMode is false', () => { + // @ts-expect-error accessing global + const previousNgDevMode = globalThis.ngDevMode; + // @ts-expect-error accessing global + globalThis.ngDevMode = false; + + try { + const warnSpy = spyOn(console, 'warn'); + createSsrRequestResponse(new Request('https://example.com/api')); + + expect(warnSpy).not.toHaveBeenCalled(); + } finally { + // @ts-expect-error accessing global + globalThis.ngDevMode = previousNgDevMode; + } + }); + }); +});