Skip to content
Open
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
7 changes: 7 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 { SSR_REQUEST_HEADER, createSsrRequestResponse } from './utils/ssr-request';
import { buildUrlWithParams, joinUrlParts, stripLeadingSlash } from './utils/url';
import { getFirstHeaderValue } from './utils/validation';

Expand Down Expand Up @@ -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,
Expand Down
4 changes: 4 additions & 0 deletions packages/angular/ssr/src/routes/route-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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.
Expand Down Expand Up @@ -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;
Expand Down
65 changes: 65 additions & 0 deletions packages/angular/ssr/src/utils/ssr-request.ts
Original file line number Diff line number Diff line change
@@ -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' } }));
};
Comment on lines +30 to +46

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Efficiency & Compatibility Improvements in ssrRequestInterceptorFn

There are a few areas in ssrRequestInterceptorFn that can be optimized for better performance, robustness, and compatibility:

  1. Avoid Double Parsing: Currently, URL.canParse(request.urlWithParams, href) is called first, followed by new URL(request.urlWithParams, href). This parses the URL twice for every outgoing HTTP request during SSR. We can optimize this by using a single try-catch block with new URL() to parse only once.
  2. Environment Compatibility: URL.canParse is a relatively new API. While supported in modern Node.js versions, using new URL inside a try-catch block is 100% backward-compatible and avoids any potential runtime compatibility issues in older or custom environments.
  3. Defensive Injection: inject(PlatformLocation) can throw an error if PlatformLocation is not provided (e.g., in certain test environments or minimal custom platforms). Making it optional via inject(PlatformLocation, { optional: true }) makes the interceptor much more robust.
export const ssrRequestInterceptorFn: HttpInterceptorFn = (request, next) => {
  const platformLocation = inject(PlatformLocation, { optional: true });
  if (!platformLocation) {
    return next(request);
  }

  const { href, hostname } = platformLocation;
  try {
    new URL(href);
  } catch {
    // The URL of the page is unknown, so requests sent to its host cannot be recognized.
    return next(request);
  }

  try {
    const url = new URL(request.urlWithParams, href);
    if (url.hostname !== hostname) {
      return next(request);
    }
  } catch {
    // URLs that cannot be parsed are marked too: some HTTP clients still send a request for them.
  }

  return next(request.clone({ setHeaders: { [SSR_REQUEST_HEADER]: '1' } }));
};

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

URL.canParse is already used in this package (utils/validation.ts runs it on every request) and is available in every supported Node version. PlatformLocation is providedIn: 'platform' with a factory, and platform-server always provides ServerPlatformLocation, so inject() can't throw here.

The extra parse happens once per outgoing HttpClient request during SSR, so I'd rather keep it consistent with the rest of the package.


/**
* 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',
},
});
}
111 changes: 111 additions & 0 deletions packages/angular/ssr/test/app_spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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', () => {
Expand Down Expand Up @@ -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('<title>CSR page</title>');
});

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],
]);
});
});
});
});