Files
spliit/src/lib/locale.ts
Julen Dixneuf 409784672c Add health check endpoint and resolve locale detection bug (#387)
* Add health check API endpoint with database connectivity

* Update locale handling to fallback to default language on invalid input

* Add health check endpoints for application readiness and liveness

- Introduced `/api/health/readiness` endpoint to check if the application can serve requests, including database connectivity.
- Introduced `/api/health/liveness` endpoint to verify if the application is running independently of external dependencies.
- Updated the health check logic to streamline database connectivity checks and response handling.

* Refactor health check logic

---------

Co-authored-by: Julen Dixneuf <julen.d@padoa-group.com>
2025-09-05 09:53:12 +02:00

44 lines
1.0 KiB
TypeScript

'use server'
import { Locale, Locales, defaultLocale, locales } from '@/i18n'
import { match } from '@formatjs/intl-localematcher'
import Negotiator from 'negotiator'
import { cookies, headers } from 'next/headers'
const COOKIE_NAME = 'NEXT_LOCALE'
function getAcceptLanguageLocale(requestHeaders: Headers, locales: Locales) {
let locale
const languages = new Negotiator({
headers: {
'accept-language': requestHeaders.get('accept-language') || undefined,
},
}).languages()
try {
locale = match(languages, locales, defaultLocale)
} catch (e) {
// invalid language - fallback to default
locale = defaultLocale
}
return locale
}
export async function getUserLocale() {
let locale
// Prio 1: use existing cookie
locale = cookies().get(COOKIE_NAME)?.value
// Prio 2: use `accept-language` header
// Prio 3: use default locale
if (!locale) {
locale = getAcceptLanguageLocale(headers(), locales)
}
return locale
}
export async function setUserLocale(locale: Locale) {
cookies().set(COOKIE_NAME, locale)
}