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
10 changes: 5 additions & 5 deletions server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -495,14 +496,13 @@ function checkCacheForRequest(cacheName: string, cache: LRUCache<string, any>, 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);
}

/**
Expand Down
50 changes: 50 additions & 0 deletions src/app/core/locale/ssr-cache-key.spec.ts
Original file line number Diff line number Diff line change
@@ -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<string, string> = {}, 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'));
});
});
48 changes: 48 additions & 0 deletions src/app/core/locale/ssr-cache-key.ts
Original file line number Diff line number Diff line change
@@ -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;
}
Loading