/**
* @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
*/
// The compiler is needed as tests are in JIT.
/* eslint-disable import/no-unassigned-import */
import '@angular/compiler';
/* eslint-enable import/no-unassigned-import */
import { APP_BASE_HREF } from '@angular/common';
import {
Component,
DestroyRef,
PendingTasks,
PlatformRef,
REQUEST,
RESPONSE_INIT,
inject,
} 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 { setAngularAppTestingManifest } from './testing-utils';
describe('AngularServerApp', () => {
let app: AngularServerApp;
let slowRouteHook: (() => void) | undefined;
@Component({
selector: 'app-home',
template: `Home works`,
})
class HomeComponent {
constructor() {
const data = inject(ActivatedRoute).snapshot.data;
if (data['destroyApp']) {
inject(PlatformRef).destroy();
}
if (data['slow']) {
slowRouteHook?.();
}
}
}
@Component({
selector: 'app-redirect',
})
class RedirectComponent {
constructor() {
const responseInit = inject(RESPONSE_INIT);
if (responseInit) {
responseInit.status = 308;
const headers = responseInit.headers;
if (headers) {
(headers as Headers).set('X-Redirect-Header', 'custom-value');
}
}
void inject(Router).navigate([], {
queryParams: { filter: 'test' },
});
}
}
const queryParamAdderGuard: CanActivateFn = (_route, state) => {
const urlTree = inject(Router).parseUrl(state.url);
if (urlTree.queryParamMap.has('filter')) {
return true;
}
urlTree.queryParams = {
filter: 'test',
};
return urlTree;
};
function setupManifest(): void {
setAngularAppTestingManifest(
[
{ path: 'home', component: HomeComponent },
{ path: 'home-csr', component: HomeComponent },
{ path: 'home-ssg', component: HomeComponent },
{ path: 'home-ssg-non-ascii/دليل', component: HomeComponent },
{ path: 'page-with-headers', component: HomeComponent },
{ path: 'page-with-status', component: HomeComponent },
{ path: 'page-destroy-app', component: HomeComponent, data: { destroyApp: true } },
{ path: 'page-slow', component: HomeComponent, data: { slow: true } },
{ path: 'redirect', redirectTo: 'home' },
{ path: 'redirect-via-navigate', component: RedirectComponent },
{
path: 'redirect-via-guard',
canActivate: [queryParamAdderGuard],
component: HomeComponent,
},
{ path: 'redirect/relative', redirectTo: 'home' },
{ path: 'redirect/:param/relative', redirectTo: 'home' },
{ path: 'redirect/absolute', redirectTo: '/home' },
{ path: 'redirect-with-query', redirectTo: 'home?param=value' },
{ path: 'redirect-nested/:param', children: [{ path: 'old', redirectTo: 'new' }] },
{ path: 'redirect-param/:a/:b', redirectTo: '/home/:b/:a' },
{ path: 'redirect-param-relative/:id', redirectTo: 'target/:id' },
{
path: 'redirect-query-placeholder',
redirectTo: '/home?q=:term&id=:missing&static=value',
},
{
path: 'redirect-query-trailing-slash',
redirectTo: '/home?next=/a/',
},
{
path: 'redirect-fragment-trailing-slash',
redirectTo: '/home#section/',
},
{
path: 'redirect-to-function',
redirectTo: () => 'home',
pathMatch: 'full',
},
],
[
{
path: 'home-csr',
renderMode: RenderMode.Client,
},
{
path: 'home-ssg',
renderMode: RenderMode.Prerender,
headers: {
'X-Some-Header': 'value',
},
},
{
path: 'home-ssg-non-ascii/دليل',
renderMode: RenderMode.Prerender,
},
{
path: 'page-with-status',
renderMode: RenderMode.Server,
status: 201,
},
{
path: 'page-with-headers',
renderMode: RenderMode.Server,
headers: {
'Cache-Control': 'no-cache',
'X-Some-Header': 'value',
},
},
{
path: '**',
renderMode: RenderMode.Server,
},
],
undefined,
{
'home-ssg/index.html': {
text: async () =>
`
SSG home page
Home SSG works
`,
size: 28,
hash: 'f799132d0a09e0fef93c68a12e443527700eb59e6f67fcb7854c3a60ff082fde',
},
'home-ssg-non-ascii/دليل/index.html': {
text: async () =>
`
SSG non-ascii page
Home SSG non-ascii works
`,
size: 38,
hash: 'a1b2c3d4e5f6',
},
},
undefined,
undefined,
[
{
provide: APP_BASE_HREF,
useFactory: () => inject(REQUEST)?.headers.get('X-Forwarded-Prefix'),
},
],
);
app = new AngularServerApp();
}
beforeAll(() => {
setupManifest();
});
describe('handle', () => {
it('should return null for well-known non-angular URLs', async () => {
const response = await app.handle(
new Request('http://localhost/.well-known/appspecific/com.chrome.devtools.json'),
);
expect(response).toBeNull();
});
describe('CSR and SSG pages', () => {
it('should correctly render the content for the requested page', async () => {
const response = await app.handle(new Request('http://localhost/home'));
expect(await response?.text()).toContain('Home works');
});
it(`should correctly render the content when the URL ends with 'index.html'`, async () => {
const response = await app.handle(new Request('http://localhost/home/index.html'));
expect(await response?.text()).toContain('Home works');
});
it('should correctly handle top level redirects', async () => {
const response = await app.handle(new Request('http://localhost/redirect'));
expect(response?.headers.get('location')).toBe('/home');
expect(response?.status).toBe(302);
});
it('should correctly handle relative redirects on multi-segment routes', async () => {
const response = await app.handle(new Request('http://localhost/redirect/relative'));
expect(response?.headers.get('location')).toBe('/home');
expect(response?.status).toBe(302);
});
it('should correctly handle relative redirects on multi-segment routes with parameter', async () => {
const response = await app.handle(new Request('http://localhost/redirect/param/relative'));
expect(response?.headers.get('location')).toBe('/home');
expect(response?.status).toBe(302);
});
it('should correctly handle relative redirects of parameterized parent routes', async () => {
const response = await app.handle(new Request('http://localhost/redirect-nested/x/old'));
expect(response?.headers.get('location')).toBe('/redirect-nested/x/new');
expect(response?.status).toBe(302);
});
it('should correctly handle absolute redirects on multi-segment routes', async () => {
const response = await app.handle(new Request('http://localhost/redirect/absolute'));
expect(response?.headers.get('location')).toBe('/home');
expect(response?.status).toBe(302);
});
it('should preserve query parameters on relative redirects', async () => {
const response = await app.handle(new Request('http://localhost/redirect?filter=test'));
expect(response?.headers.get('location')).toBe('/home?filter=test');
expect(response?.status).toBe(302);
});
it('should ignore query parameters of relative redirect targets', async () => {
const response = await app.handle(
new Request('http://localhost/redirect-with-query?filter=test'),
);
expect(response?.headers.get('location')).toBe('/home?filter=test');
expect(response?.status).toBe(302);
});
it('should not preserve query parameters on absolute redirects', async () => {
const response = await app.handle(
new Request('http://localhost/redirect/absolute?filter=test'),
);
expect(response?.headers.get('location')).toBe('/home');
expect(response?.status).toBe(302);
});
it('should resolve route parameters in absolute redirect targets', async () => {
const response = await app.handle(new Request('http://localhost/redirect-param/x/y'));
expect(response?.headers.get('location')).toBe('/home/y/x');
expect(response?.status).toBe(302);
});
it('should resolve route parameters in relative redirect targets', async () => {
const response = await app.handle(
new Request('http://localhost/redirect-param-relative/7?filter=test'),
);
expect(response?.headers.get('location')).toBe('/target/7?filter=test');
expect(response?.status).toBe(302);
});
it('should resolve query parameters in absolute redirect targets', async () => {
const response = await app.handle(
new Request('http://localhost/redirect-query-placeholder?term=cats&term=dogs'),
);
expect(response?.headers.get('location')).toBe(
'/home?q=cats&q=dogs&id=undefined&static=value',
);
expect(response?.status).toBe(302);
});
it('should preserve trailing slashes in query parameters and fragments of redirect targets', async () => {
const queryResponse = await app.handle(
new Request('http://localhost/redirect-query-trailing-slash'),
);
expect(queryResponse?.headers.get('location')).toBe('/home?next=/a/');
expect(queryResponse?.status).toBe(302);
const fragmentResponse = await app.handle(
new Request('http://localhost/redirect-fragment-trailing-slash'),
);
expect(fragmentResponse?.headers.get('location')).toBe('/home#section/');
expect(fragmentResponse?.status).toBe(302);
});
it('should handle request abortion gracefully', async () => {
const controller = new AbortController();
const request = new Request('http://localhost/home', { signal: controller.signal });
// Schedule the abortion of the request in the next microtask
queueMicrotask(() => {
controller.abort();
});
await expectAsync(app.handle(request)).toBeRejectedWithError(
DOMException,
/Request for: http:\/\/localhost\/home was aborted/,
);
});
it('should destroy the platform and stop rendering when an in-flight request is aborted', async () => {
let resolveTaskReady!: () => void;
const taskReady = new Promise((resolve) => {
resolveTaskReady = resolve;
});
let appDestroyed = false;
let destroySpy: jasmine.Spy | undefined;
slowRouteHook = () => {
destroySpy = spyOn(inject(PlatformRef), 'destroy').and.callThrough();
const pendingTasks = inject(PendingTasks);
const removeTask = pendingTasks.add();
inject(DestroyRef).onDestroy(() => {
appDestroyed = true;
removeTask();
});
resolveTaskReady();
};
try {
const controller = new AbortController();
const request = new Request('http://localhost/page-slow', { signal: controller.signal });
const handlePromise = app.handle(request);
// Wait until the component is instantiated and holding a pending task
await taskReady;
expect(appDestroyed).toBeFalse();
// Abort the request while `applicationRef.whenStable()` is still pending
controller.abort();
await expectAsync(handlePromise).toBeRejectedWithError(
DOMException,
/Request for: http:\/\/localhost\/page-slow was aborted/,
);
// Wait for the macrotask queue to clear since platform destruction is scheduled via setTimeout(0)
await setTimeout(0);
expect(destroySpy).toHaveBeenCalledTimes(1);
expect(appDestroyed).toBeTrue();
} finally {
slowRouteHook = undefined;
}
});
it('should not bootstrap the platform if the request signal is already aborted', async () => {
// Warm up the router so route extraction does not create a PlatformRef during this test
const warmupResponse = await app.handle(new Request('http://localhost/home'));
await warmupResponse?.text();
await setTimeout(0);
const destroySpy = spyOn(PlatformRef.prototype, 'destroy').and.callThrough();
const controller = new AbortController();
controller.abort();
const request = new Request('http://localhost/home', { signal: controller.signal });
await expectAsync(app.handle(request)).toBeRejectedWithError(DOMException);
await setTimeout(0);
expect(destroySpy).not.toHaveBeenCalled();
});
it('should clean up the abort event listener on request.signal after rendering completes', async () => {
const controller = new AbortController();
const request = new Request('http://localhost/home', { signal: controller.signal });
const addEventListenerSpy = spyOn(request.signal, 'addEventListener').and.callThrough();
const removeEventListenerSpy = spyOn(
request.signal,
'removeEventListener',
).and.callThrough();
const response = await app.handle(request);
expect(await response?.text()).toContain('Home works');
await setTimeout(0);
const addedAbortListeners = addEventListenerSpy.calls
.allArgs()
.filter(([event]) => event === 'abort')
.map(([, listener]) => listener);
const removedAbortListeners = removeEventListenerSpy.calls
.allArgs()
.filter(([event]) => event === 'abort')
.map(([, listener]) => listener);
expect(addedAbortListeners.length).toBeGreaterThan(0);
expect(removedAbortListeners).toEqual(jasmine.arrayWithExactContents(addedAbortListeners));
});
it('should skip html:transform:pre hooks when request signal is already aborted', async () => {
try {
setAngularAppTestingManifest(
[{ path: 'home', component: HomeComponent }],
[{ path: '**', renderMode: RenderMode.Server }],
);
const hooks = new Hooks();
const transformSpy = jasmine.createSpy('htmlTransform').and.callFake(({ html }) => html);
hooks.on('html:transform:pre', transformSpy);
const customApp = new AngularServerApp({ hooks });
// Warm up router.
const warmup = await customApp.handle(new Request('http://localhost/home'));
await warmup?.text();
await setTimeout(0);
expect(transformSpy).toHaveBeenCalledTimes(1);
transformSpy.calls.reset();
const controller = new AbortController();
controller.abort();
await expectAsync(
customApp.handle(new Request('http://localhost/home', { signal: controller.signal })),
).toBeRejectedWithError(
DOMException,
/Request for: http:\/\/localhost\/home was aborted/,
);
await setTimeout(0);
expect(transformSpy).not.toHaveBeenCalled();
} finally {
setupManifest();
}
});
it('should reject reading response body if request is aborted after handle() resolves but before rendering completes', async () => {
const controller = new AbortController();
const response = await app.handle(
new Request('http://localhost/home', { signal: controller.signal }),
);
expect(response).not.toBeNull();
controller.abort();
await expectAsync(response?.text()).toBeRejectedWithError(
DOMException,
/Request for: http:\/\/localhost\/home was aborted/,
);
await setTimeout(0);
});
it('should return configured headers for pages with specific header settings', async () => {
const response = await app.handle(new Request('http://localhost/page-with-headers'));
const headers = response?.headers.entries() ?? [];
expect(Object.fromEntries(headers)).toEqual({
'cache-control': 'no-cache',
'x-some-header': 'value',
'content-type': 'text/html;charset=UTF-8',
});
});
it('should return only default headers for pages without specific header configurations', async () => {
const response = await app.handle(new Request('http://localhost/home'));
const headers = response?.headers.entries() ?? [];
expect(Object.fromEntries(headers)).toEqual({
'content-type': 'text/html;charset=UTF-8', // default header
});
});
it('should return the configured status for pages with specific status settings', async () => {
const response = await app.handle(new Request('http://localhost/page-with-status'));
expect(response?.status).toBe(201);
});
it('should not throw an error when app destroys itself', async () => {
const response = await app.handle(new Request('http://localhost/page-destroy-app'));
// The test expects response to be null, which is reasonable - if the app destroys
// itself, there's nothing to render.
expect(response).toBeNull();
});
it('should return static `index.csr.html` for routes with CSR rendering mode', async () => {
const response = await app.handle(new Request('http://localhost/home-csr'));
const content = await response?.text();
expect(content).toContain('CSR page');
expect(content).not.toContain('ng-server-context');
});
it('should include `ng-server-context="ssr"` for SSR rendering mode', async () => {
const response = await app.handle(new Request('http://localhost/home'));
expect(await response?.text()).toContain('ng-server-context="ssr"');
});
});
describe('SSG pages', () => {
it('should correctly serve the content for the requested prerendered page', async () => {
const response = await app.handle(new Request('http://localhost/home-ssg'));
expect(await response?.text()).toContain('Home SSG works');
});
it('should return null if the requested prerendered page is accessed with a non-GET and non-HEAD method', async () => {
const responseHead = await app.handle(
new Request('http://localhost/home-ssg', { method: 'HEAD' }),
);
expect(await responseHead?.text()).toContain('Home SSG works');
const responsePost = await app.handle(
new Request('http://localhost/home-ssg', { method: 'POST' }),
);
expect(responsePost).toBeNull();
});
it(`should correctly serve the content for the requested prerendered page when the URL ends with 'index.html'`, async () => {
const response = await app.handle(new Request('http://localhost/home-ssg/index.html'));
expect(await response?.text()).toContain('Home SSG works');
});
it('should correctly serve prerendered page with non-ASCII path', async () => {
const response = await app.handle(
new Request('http://localhost/home-ssg-non-ascii/%D8%AF%D9%84%D9%8A%D9%84'),
);
expect(await response?.text()).toContain('Home SSG non-ascii works');
});
it(`should correctly serve prerendered page with non-ASCII path when the URL ends with 'index.html'`, async () => {
const response = await app.handle(
new Request('http://localhost/home-ssg-non-ascii/%D8%AF%D9%84%D9%8A%D9%84/index.html'),
);
expect(await response?.text()).toContain('Home SSG non-ascii works');
});
it('should correctly serve prerendered page when requested with decoded non-ASCII characters', async () => {
const response = await app.handle(new Request('http://localhost/home-ssg-non-ascii/دليل'));
expect(await response?.text()).toContain('Home SSG non-ascii works');
});
it('should correctly serve prerendered page with non-ASCII path when baseHref is configured', async () => {
setAngularAppTestingManifest(
[{ path: 'home-ssg-non-ascii/دليل', component: HomeComponent }],
[
{
path: 'home-ssg-non-ascii/دليل',
renderMode: RenderMode.Prerender,
},
],
'/ar/',
{
'home-ssg-non-ascii/دليل/index.html': {
text: async () => 'SSG with baseHref works',
size: 47,
hash: '123456',
},
},
);
const customApp = new AngularServerApp();
const response = await customApp.handle(
new Request('http://localhost/ar/home-ssg-non-ascii/%D8%AF%D9%84%D9%8A%D9%84'),
);
expect(await response?.text()).toContain('SSG with baseHref works');
});
it('should correctly serve prerendered page when baseHref contains non-ASCII characters', async () => {
setAngularAppTestingManifest(
[{ path: 'page', component: HomeComponent }],
[
{
path: 'page',
renderMode: RenderMode.Prerender,
},
],
'/دليل/',
{
'page/index.html': {
text: async () => 'SSG with non-ASCII baseHref works',
size: 57,
hash: 'abcdef',
},
},
);
const customApp = new AngularServerApp();
const response = await customApp.handle(
new Request('http://localhost/%D8%AF%D9%84%D9%8A%D9%84/page'),
);
expect(await response?.text()).toContain('SSG with non-ASCII baseHref works');
});
it('should return configured headers for pages with specific header settings', async () => {
const response = await app.handle(new Request('http://localhost/home-ssg'));
const headers = response?.headers.entries() ?? [];
expect(Object.fromEntries(headers)).toEqual({
'etag': '"f799132d0a09e0fef93c68a12e443527700eb59e6f67fcb7854c3a60ff082fde"',
'content-length': '28',
'x-some-header': 'value',
'content-type': 'text/html;charset=UTF-8',
});
});
it('should return 304 Not Modified when ETag matches', async () => {
const url = 'http://localhost/home-ssg';
const initialResponse = await app.handle(new Request(url));
const etag = initialResponse?.headers.get('etag');
expect(etag).toBeDefined();
const conditionalResponse = await app.handle(
new Request(url, {
headers: {
'If-None-Match': etag as string,
},
}),
);
// Check that the response status is 304 Not Modified
expect(conditionalResponse?.status).toBe(304);
expect(await conditionalResponse?.text()).toBe('');
});
it('should return null for a non-prerendered page', async () => {
const response = await app.handle(new Request('http://localhost/unknown'));
expect(response).toBeNull();
});
});
describe('SSR pages', () => {
it('returns a 302 status and redirects to the correct location when `redirectTo` is a function', async () => {
const response = await app.handle(new Request('http://localhost/redirect-to-function'));
expect(response?.headers.get('location')).toBe('/home');
expect(response?.status).toBe(302);
});
it('returns a 302 status and redirects to the correct location when `router.navigate` is used', async () => {
const response = await app.handle(new Request('http://localhost/redirect-via-navigate'));
expect(response?.headers.get('location')).toBe('/redirect-via-navigate?filter=test');
expect(response?.status).toBe(308);
expect(response?.headers.get('X-Redirect-Header')).toBe('custom-value');
});
it('returns a 302 status and redirects to the correct location when `urlTree` is updated in a guard', async () => {
const response = await app.handle(new Request('http://localhost/redirect-via-guard'));
expect(response?.headers.get('location')).toBe('/redirect-via-guard?filter=test');
expect(response?.status).toBe(302);
});
it('should work with complex and encoded URLs', async () => {
const urls = [
'http://localhost/home?email=xyz%40xyz.com',
'http://localhost/home?empty',
'http://localhost/home?scope=email+profile',
'http://localhost/home?bbb=1&aaa=2&bbb=3',
];
for (const url of urls) {
const request = new Request(url);
const response = await app.handle(request);
expect(response?.status).withContext(`url: ${url}`).toBe(200);
expect(await response?.text())
.withContext(`url: ${url}`)
.toContain('Home works');
}
});
it('should work with decoded characters', async () => {
const request = new Request('http://localhost/home?email=xyz@xyz.com');
const response = await app.handle(request);
expect(response?.status).toBe(200);
expect(await response?.text()).toContain('Home works');
});
it('should destroy the platform when the response stream is cancelled', async () => {
const destroySpy = spyOn(PlatformRef.prototype, 'destroy').and.callThrough();
const response = await app.handle(new Request('http://localhost/home'));
expect(response?.body).toBeInstanceOf(ReadableStream);
await response?.body?.cancel();
// Wait for the macrotask queue to clear since destroy is called asynchronously
await setTimeout(0);
expect(destroySpy).toHaveBeenCalled();
});
describe('APP_BASE_HREF / X-Forwarded-Prefix', () => {
const headers = new Headers({ 'X-Forwarded-Prefix': '/base/' });
it('should return a rendered page for known paths', async () => {
const request = new Request('https://example.com/home', { headers });
const response = await app.handle(request);
expect(await response?.text()).toContain('Home works');
});
it('returns a 302 status and redirects to the correct location when `redirectTo` is a function', async () => {
const response = await app.handle(
new Request('http://localhost/redirect-to-function', {
headers,
}),
);
expect(response?.headers.get('location')).toBe('/base/home');
expect(response?.status).toBe(302);
});
it('returns a 302 status and redirects to the correct location when `redirectTo` is a string', async () => {
const response = await app.handle(
new Request('http://localhost/redirect', {
headers,
}),
);
expect(response?.headers.get('location')).toBe('/base/home');
expect(response?.status).toBe(302);
});
it('returns a 302 status and keeps the query string for relative redirects', async () => {
const response = await app.handle(
new Request('http://localhost/redirect?filter=test', {
headers,
}),
);
expect(response?.headers.get('location')).toBe('/base/home?filter=test');
expect(response?.status).toBe(302);
});
it('should only use the first value of the "X-Forwarded-Prefix" header in redirects', async () => {
const response = await app.handle(
new Request('http://localhost/redirect', {
headers: { 'X-Forwarded-Prefix': '/base, /"' },
}),
);
expect(response?.headers.get('location')).toBe('/base/home');
expect(response?.status).toBe(302);
});
});
describe('Critical CSS inlining', () => {
afterEach(() => {
setupManifest();
});
it('should inline critical CSS when inlineCriticalCss is provided', async () => {
setAngularAppTestingManifest(
[{ path: 'home', component: HomeComponent }],
[{ path: 'home', renderMode: RenderMode.Server }],
'/',
{
'index.server.html': {
size: 100,
hash: '123',
text: async () =>
``,
},
},
undefined,
undefined,
undefined,
{ 'styles.css': 'app-home{color:blue}' },
);
const customApp = new AngularServerApp();
const response = await customApp.handle(new Request('http://localhost/home'));
const html = await response?.text();
expect(html).toContain('');
expect(html).toContain('data-beasties-media="all"');
expect(html).toContain("document.querySelectorAll('link[data-beasties-media]')");
});
it('should apply CSP nonce to inlined style and script tags when nonce is configured', async () => {
setAngularAppTestingManifest(
[{ path: 'home', component: HomeComponent }],
[{ path: 'home', renderMode: RenderMode.Server }],
'/',
{
'index.server.html': {
size: 100,
hash: '123',
text: async () =>
``,
},
},
undefined,
undefined,
undefined,
{ 'styles.css': 'app-home{color:blue}' },
'{% nonce %}',
);
const customApp = new AngularServerApp();
const response = await customApp.handle(new Request('http://localhost/home'));
const html = await response?.text();
expect(html).toContain('');
expect(html).toContain('