From 009db44eff97c3b3a4f497ae883a4254c10261f6 Mon Sep 17 00:00:00 2001 From: Juraj Roka <95219754+jr-rk@users.noreply.github.com> Date: Wed, 28 Oct 2026 13:10:25 +0100 Subject: [PATCH] Include the render language in the SSR cache key The server-side page caches (bot cache, enabled by default, and the anonymous cache) were keyed by req.url only. The language of an SSR render depends on the dsLanguage cookie and the Accept-Language header, so a page rendered in one language was served from the cache to visitors who asked for another one. The key is now the URL followed by the language the request is rendered in, resolved the same way LocaleService/ServerLocaleService do for anonymous requests (active cookie language, then the first active Accept-Language entry, then the fallback language). Using the resolved language instead of the raw header keeps header variants that ask for the same language in one cache entry. The key still starts with the URL, so /reload paths are still excluded from caching. The key logic moves to src/app/core/locale/ssr-cache-key.ts so it can be unit tested. --- server.ts | 10 ++--- src/app/core/locale/ssr-cache-key.spec.ts | 50 +++++++++++++++++++++++ src/app/core/locale/ssr-cache-key.ts | 48 ++++++++++++++++++++++ 3 files changed, 103 insertions(+), 5 deletions(-) create mode 100644 src/app/core/locale/ssr-cache-key.spec.ts create mode 100644 src/app/core/locale/ssr-cache-key.ts diff --git a/server.ts b/server.ts index ab1693af041..2b95b4a08c6 100644 --- a/server.ts +++ b/server.ts @@ -50,6 +50,7 @@ import { extendEnvironmentWithAppConfig } from './src/config/config.util'; import { ServerHashedFileMapping } from './src/modules/dynamic-hash/hashed-file-mapping.server'; import { logStartupMessage } from './startup-message'; import { TOKENITEM } from '@dspace/core/auth/models/auth-token-info.model'; +import { getSsrCacheKey } from '@dspace/core/locale/ssr-cache-key'; import { CommonEngine } from '@angular/ssr/node'; import { APP_BASE_HREF } from '@angular/common'; import { @@ -412,7 +413,7 @@ function anonymousCacheEnabled(): boolean { /** * Check if the currently requested page is in our server-side, in-memory cache. - * Caching is ONLY done for SSR requests. Pages are cached base on their path (e.g. /home or /search?query=test) + * Caching is ONLY done for SSR requests. Pages are cached base on their path (e.g. /home or /search?query=test) and language */ function cacheCheck(req, res, next) { // Authenticated users are never served via SSR @@ -495,14 +496,13 @@ function checkCacheForRequest(cacheName: string, cache: LRUCache, r /** * Create a cache key from the current request. - * The cache key is the URL path (NOTE: this key will also include any querystring params). - * E.g. "/home" or "/search?query=test" + * The cache key is the URL path (NOTE: this key will also include any querystring params) and the render language. + * E.g. "/home|en" or "/search?query=test|de" * @param req current request * @returns cache key to use for this page */ function getCacheKey(req): string { - // NOTE: this will return the URL path *without* any baseUrl - return req.url; + return getSsrCacheKey(req, appConfig.languages, appConfig.fallbackLanguage); } /** diff --git a/src/app/core/locale/ssr-cache-key.spec.ts b/src/app/core/locale/ssr-cache-key.spec.ts new file mode 100644 index 00000000000..a4d5da63b89 --- /dev/null +++ b/src/app/core/locale/ssr-cache-key.spec.ts @@ -0,0 +1,50 @@ +import { LangConfig } from '@dspace/config/lang-config.interface'; +import { Request } from 'express'; + +import { LANG_COOKIE } from './locale.service'; +import { getSsrCacheKey } from './ssr-cache-key'; + +describe('getSsrCacheKey', () => { + const languages: LangConfig[] = [ + { code: 'en', label: 'English', active: true }, + { code: 'de', label: 'Deutsch', active: true }, + { code: 'cs', label: 'Čeština', active: true }, + { code: 'fr', label: 'Français', active: false }, + ]; + + function getKey(cookies: Record = {}, acceptLanguage?: string, url = '/home'): string { + const req = { url, cookies, headers: { 'accept-language': acceptLanguage } } as unknown as Request; + return getSsrCacheKey(req, languages, 'en'); + } + + it('should start with the URL path, so that /reload paths can still be recognized', () => { + expect(getKey({}, undefined, '/reload/123').startsWith('/reload')).toBeTrue(); + }); + + it('should differ for the same URL requested in different languages', () => { + expect(getKey({ [LANG_COOKIE]: 'de' })).not.toEqual(getKey({ [LANG_COOKIE]: 'cs' })); + expect(getKey({}, 'de')).not.toEqual(getKey({}, 'cs')); + expect(getKey({}, 'de')).not.toEqual(getKey()); + }); + + it('should be the same for requests resolving to the same language', () => { + expect(getKey({ [LANG_COOKIE]: 'de' })).toEqual(getKey({}, 'de-DE,de;q=0.9')); + expect(getKey({ [LANG_COOKIE]: '"de"' })).toEqual(getKey({ [LANG_COOKIE]: 'de' })); + expect(getKey({}, 'de;q=0.8')).toEqual(getKey({}, 'de')); + }); + + it('should prefer an active language cookie over Accept-Language', () => { + expect(getKey({ [LANG_COOKIE]: 'cs' }, 'de')).toEqual(getKey({ [LANG_COOKIE]: 'cs' })); + }); + + it('should fall back to the default language key for unsupported or inactive languages', () => { + const defaultKey = getKey(); + expect(getKey({ [LANG_COOKIE]: 'xx' })).toEqual(defaultKey); + expect(getKey({ [LANG_COOKIE]: 'fr' })).toEqual(defaultKey); + expect(getKey({}, 'xx-YY,fr;q=0.9')).toEqual(defaultKey); + }); + + it('should use Accept-Language when the language cookie is not an active language', () => { + expect(getKey({ [LANG_COOKIE]: 'fr' }, 'de')).toEqual(getKey({}, 'de')); + }); +}); diff --git a/src/app/core/locale/ssr-cache-key.ts b/src/app/core/locale/ssr-cache-key.ts new file mode 100644 index 00000000000..c8516c147b1 --- /dev/null +++ b/src/app/core/locale/ssr-cache-key.ts @@ -0,0 +1,48 @@ +import { LangConfig } from '@dspace/config/lang-config.interface'; +import { Request } from 'express'; + +import { LANG_COOKIE } from './locale.service'; + +/** + * Create the key of a server-side rendered page in the SSR caches (see server.ts). + * The key is the URL path (including any querystring params) followed by the language the page is rendered in, + * e.g. "/home|en" or "/search?query=test|de". Without the language, a page rendered in one language would be + * served from the cache to visitors who asked for another one. + * @param req current request + * @param languages configured languages + * @param fallbackLanguage language to render in when the request asks for no active language + * @returns cache key to use for this page + */ +export function getSsrCacheKey(req: Request, languages: LangConfig[], fallbackLanguage: string): string { + // NOTE: req.url is the URL path *without* any baseUrl. Language codes contain no '|', so keys are unambiguous. + return `${req.url}|${getSsrLanguage(req, languages, fallbackLanguage)}`; +} + +/** + * Get the language an anonymous SSR request is rendered in. The resolved language is used rather than the raw + * Accept-Language header, so that header variants asking for the same language share one cache entry. + * This mirrors LocaleService.getCurrentLanguageCode() with ServerLocaleService.getLanguageCodeList() + * and must stay in sync with them, otherwise a page could be cached under the wrong language: + * an active language from the language cookie, else the first Accept-Language entry that is an active language, + * else the fallback language. + */ +function getSsrLanguage(req: Request, languages: LangConfig[], fallbackLanguage: string): string { + const activeCodes = languages.filter((lang: LangConfig) => lang.active).map((lang: LangConfig) => lang.code); + + let cookieLang = req.cookies?.[LANG_COOKIE]; + try { + // Same parsing as ServerCookieService.get() + cookieLang = JSON.parse(cookieLang); + } catch { + // not JSON, keep the raw value + } + if (activeCodes.includes(cookieLang)) { + return cookieLang; + } + + // Like ServerLocaleService, entries are not trimmed and only the part before ';' is compared. + return req.headers['accept-language']?.split(',') + .map((browserLang: string) => browserLang.split(';')[0]) + .find((browserLang: string) => activeCodes.some((code: string) => code.toLowerCase() === browserLang.toLowerCase())) + || fallbackLanguage; +}