Remove translation handling with cookies

This commit is contained in:
Leonardo Murça 2025-06-05 19:13:50 -03:00
parent cf231feb8e
commit f6578c5bf7
5 changed files with 90 additions and 72 deletions

View file

@ -1,21 +0,0 @@
import type { Handle } from '@sveltejs/kit';
export const handle: Handle = async ({ event, resolve }) => {
// Correct origin behind Nginx
const host = event.request.headers.get('x-forwarded-host') ?? event.request.headers.get('host');
const proto = event.request.headers.get('x-forwarded-proto') ?? 'https';
const origin = `${proto}://${host}`;
// Example: force HTTPS (optional, Nginx should already do this)
if (proto === 'http') {
return new Response(null, {
status: 308,
headers: {
Location: origin + event.url.pathname + event.url.search
}
});
}
// Proceed with default behavior
return resolve(event);
};

View file

@ -127,7 +127,10 @@ export const {
} = new i18n(config); } = new i18n(config);
locale.subscribe(($locale) => { locale.subscribe(($locale) => {
// if (typeof document !== 'undefined') { if (typeof localStorage !== 'undefined' && $locale) {
// document.cookie = `locale=${$locale}; path=/; SameSite=None; Secure`; const existing = localStorage.getItem('locale');
// } if (existing !== $locale) {
localStorage.setItem('locale', $locale);
}
}
}); });

View file

@ -1,17 +1,51 @@
import { setLocale, setRoute } from '$lib/translations'; import { browser } from '$app/environment';
import { loadTranslations, setLocale, setRoute } from '$lib/translations';
import { SUPPORTED_LOCALES } from '$lib/translations';
/** /**
* @typedef {Object} LayoutData * Type guard that checks if a string is a supported locale.
* @property {string} route * @param {string | null} locale
* @property {string} language * @returns {locale is "en-US" | "pt-BR"}
*/ */
function isSupportedLocale(locale) {
// @ts-ignore
return locale !== null && Object.values(SUPPORTED_LOCALES).includes(locale);
}
/** @type {import('@sveltejs/kit').Load<LayoutData>} */ /**
export const load = async ({ data }) => { * Client-side load function to initialize translations based on localStorage or server fallback.
const { route, language } = data ?? {}; *
* This function runs in the browser and:
* - Prioritizes locale from localStorage (if valid)
* - Falls back to the server-provided fallbackLanguage (from Accept-Language)
* - Initializes translations and routing
*
* @type {import('@sveltejs/kit').Load}
*/
export const load = async ({ data, url }) => {
/** @type {string} */
const route = url.pathname;
if (route) await setRoute(route); /** @type {"en-US" | "pt-BR"} */
if (language) await setLocale(language); let language;
return data ?? {}; if (browser) {
/**
* Locale stored in the browser, if any.
* @type {string | null}
*/
const stored = localStorage.getItem('locale');
if (isSupportedLocale(stored)) {
language = stored; // Type narrowed here
} else {
language = data?.fallbackLanguage ?? SUPPORTED_LOCALES.EN_US;
}
await loadTranslations(language, route);
await setLocale(language);
await setRoute(route);
}
return {};
}; };

View file

@ -1,55 +1,44 @@
import { parse } from 'accept-language-parser'; import { parse } from 'accept-language-parser';
import { loadTranslations, setLocale, setRoute } from '$lib/translations';
import { SUPPORTED_LOCALES } from '$lib/translations'; import { SUPPORTED_LOCALES } from '$lib/translations';
/** /**
* A set of all supported locale codes, used to validate and match against * A Set of all supported locale codes for quick validation.
* user preferences from cookies or Accept-Language headers. We're using a
* Set for better performance in lookup.
*
* Example values: "en-US", "pt-BR" * Example values: "en-US", "pt-BR"
* @type {Set<string>} * @type {Set<string>}
*/ */
const SUPPORTED_LOCALE_SET = new Set(Object.values(SUPPORTED_LOCALES)); const SUPPORTED_LOCALE_SET = new Set(Object.values(SUPPORTED_LOCALES));
/** /**
* Returns a valid locale from cookies, or null if not valid/found. * Extracts the best matching locale from an Accept-Language HTTP header.
* @param {{ get: (cookies: string) => any; }} cookies *
*/ * @param {string | null} header - The Accept-Language header value.
function localeFromCookies(cookies) { * @returns {string | null} - A supported locale string like "en-US", or null if none matched.
const locale = cookies.get('locale');
return locale && SUPPORTED_LOCALE_SET.has(locale) ? locale : null;
}
/**
* Parses the Accept-Language header and returns the best matching locale.
* @param {string | null | undefined} header
*/ */
function localeFromHeader(header) { function localeFromHeader(header) {
if (!header) return null; if (!header) return null;
const parsed = parse(header);
const parsedLanguages = parse(header); for (const { code, region } of parsed) {
for (const { code, region } of parsedLanguages) {
const locale = region ? `${code}-${region}` : code; const locale = region ? `${code}-${region}` : code;
if (SUPPORTED_LOCALE_SET.has(locale)) { if (SUPPORTED_LOCALE_SET.has(locale)) return locale;
return locale;
} }
}
return null; return null;
} }
/** @type {import('@sveltejs/kit').ServerLoad}*/ /**
export async function load({ url, request, cookies }) { * Server-side load function that returns the initial route and fallback language.
// const cookieLocale = localeFromCookies(cookies); * The language is inferred from the Accept-Language header.
// const headerLocale = localeFromHeader(request.headers.get('accept-language')); * `localStorage` will take precedence on the client.
// const language = cookieLocale || headerLocale || SUPPORTED_LOCALES.EN_US; *
const language = SUPPORTED_LOCALES.EN_US; * @type {import('@sveltejs/kit').ServerLoad}
*/
export async function load({ url, request }) {
/** @type {string} */
const route = url.pathname; const route = url.pathname;
await loadTranslations(language, route); /** @type {string} */
setLocale(language); const fallbackLanguage =
setRoute(route); localeFromHeader(request.headers.get('accept-language')) ||
SUPPORTED_LOCALES.EN_US;
return { language, route }; return { fallbackLanguage, route };
} }

View file

@ -1,13 +1,26 @@
<script> <script>
import { browser } from '$app/environment';
import { onMount } from 'svelte';
import Header from '$lib/components/Header.svelte'; import Header from '$lib/components/Header.svelte';
import Footer from '$lib/components/Footer.svelte'; import Footer from '$lib/components/Footer.svelte';
let mounted = false;
if (browser) {
onMount(() => {
mounted = true;
});
}
</script> </script>
<Header /> {#if mounted}
<main> <Header />
<main>
<slot /> <slot />
</main> </main>
<Footer /> <Footer />
{/if}
<style> <style>
main { main {