From ab09a3f50fe17242c32c7e82f2b94e409561e73e Mon Sep 17 00:00:00 2001 From: Keith Stevens Date: Sun, 22 Jan 2023 16:13:35 +0900 Subject: [PATCH] Adding a valid language check --- website/src/lib/users.ts | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/website/src/lib/users.ts b/website/src/lib/users.ts index 3dbe5a08..3f1cb65d 100644 --- a/website/src/lib/users.ts +++ b/website/src/lib/users.ts @@ -3,13 +3,26 @@ import type { NextApiRequest } from "next"; import prisma from "src/lib/prismadb"; import type { BackendUserCore } from "src/types/Users"; +import { i18n } from "src/../next-i18next.config"; + +const LOCALE_SET = new Set(i18n.locales); + +/** + * Returns the most appropriate user language using the following priority: + * + * 1. The `NEXT_LOCALE` cookie which is set by the client side and will be in + * the set of supported locales. + * 2. The `accept-language` header if it contains a supported locale as set by + * the i18n module. + * 3. "en" as a final fallback. + */ const getUserLanguage = (req: NextApiRequest) => { const cookieLanguage = req.cookies["NEXT_LOCALE"]; if (cookieLanguage) { return cookieLanguage; } const headerLanguages = parser.parse(req.headers["accept-language"]); - if (headerLanguages.length > 0) { + if (headerLanguages.length > 0 && LOCALE_SET.has(headerLanguages[0].code)) { return headerLanguages[0].code; } return "en";