fix(@angular/ssr): redirect to locale pathname instead of full URL

When redirecting to the preferred locale, the previous implementation used the full URL for the 302 redirect to i18n subpaths based on the user's preferred locale. This update ensures that the redirect now uses the locale-specific pathname instead of the full URL.

Closes #29514
This commit is contained in:
Alan Agius 2025-01-29 09:01:19 +00:00 committed by Alan Agius
parent 05f3680525
commit 46581db16b
2 changed files with 5 additions and 7 deletions

View File

@ -97,8 +97,8 @@ export class AngularAppEngine {
const { basePath, supportedLocales } = this.manifest; const { basePath, supportedLocales } = this.manifest;
// If the request is not for the base path, it's not our responsibility to handle it. // If the request is not for the base path, it's not our responsibility to handle it.
const url = new URL(request.url); const { pathname } = new URL(request.url);
if (url.pathname !== basePath) { if (pathname !== basePath) {
return null; return null;
} }
@ -112,12 +112,10 @@ export class AngularAppEngine {
if (preferredLocale) { if (preferredLocale) {
const subPath = supportedLocales[preferredLocale]; const subPath = supportedLocales[preferredLocale];
if (subPath !== undefined) { if (subPath !== undefined) {
url.pathname = joinUrlParts(url.pathname, subPath);
return new Response(null, { return new Response(null, {
status: 302, // Use a 302 redirect as language preference may change. status: 302, // Use a 302 redirect as language preference may change.
headers: { headers: {
'Location': url.toString(), 'Location': joinUrlParts(pathname, subPath),
'Vary': 'Accept-Language', 'Vary': 'Accept-Language',
}, },
}); });

View File

@ -157,12 +157,12 @@ describe('AngularAppEngine', () => {
}); });
it('should redirect to the highest priority locale when the URL is "/"', async () => { it('should redirect to the highest priority locale when the URL is "/"', async () => {
const request = new Request('https://example.com/', { const request = new Request('https://example.com', {
headers: { 'Accept-Language': 'fr-CH, fr;q=0.9, it;q=0.8, en;q=0.7, *;q=0.5' }, headers: { 'Accept-Language': 'fr-CH, fr;q=0.9, it;q=0.8, en;q=0.7, *;q=0.5' },
}); });
const response = await appEngine.handle(request); const response = await appEngine.handle(request);
expect(response?.status).toBe(302); expect(response?.status).toBe(302);
expect(response?.headers.get('Location')).toBe('https://example.com/it'); expect(response?.headers.get('Location')).toBe('/it');
expect(response?.headers.get('Vary')).toBe('Accept-Language'); expect(response?.headers.get('Vary')).toBe('Accept-Language');
}); });