Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions packages/angular/ssr/src/app-engine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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(
Expand Down
17 changes: 17 additions & 0 deletions packages/angular/ssr/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand Down Expand Up @@ -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);

Expand All @@ -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),
Expand Down Expand Up @@ -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[] = [];

Expand Down
46 changes: 46 additions & 0 deletions packages/angular/ssr/src/utils/ssr-request.ts
Original file line number Diff line number Diff line change
@@ -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',
},
});
}
23 changes: 23 additions & 0 deletions packages/angular/ssr/test/app-engine_spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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({
Expand Down Expand Up @@ -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();
});
});
});

Expand Down
Loading
Loading