File: /var/www/affiliate.casatrade/src/hooks.server.ts
import { base } from '$app/paths';
import { defaultLocale, loadTranslations, locales } from '$lib/translations';
import type { Handle, HandleServerError } from '@sveltejs/kit';
const routeRegex = new RegExp(/^\/[^.]*([?#].*)?$/);
/** @type {import('@sveltejs/kit').Handle} */
export const handle: Handle = async ({ event, resolve }) => {
const { url, request } = event;
const { pathname } = url;
// If this request is a route request
if (routeRegex.test(pathname)) {
// Get defined locales
const supportedLocales = locales.get().map((l) => l.toLowerCase());
// Try to get locale from `pathname`.
// let locale = supportedLocales.find((l) => l === `${pathname.match(/[^/lp/]+?(?=\/|$)/)}`.toLowerCase());
const baseCatalogs = base.split('/');
let locale = supportedLocales.find(
(l) =>
l === `${pathname.match(`(?<=${baseCatalogs.map(elem => elem+'\/').join('')})([^\/]+)`)}`.toLowerCase().split(',')[0]
);
// We want to redirect the default locale to "no-locale" path
if (locale === defaultLocale && !request.headers.get('prevent-redirect')) {
const localeRegex = new RegExp(`\/${locale}`);
const location = `${pathname}`.replace(localeRegex, '') || '/';
console.log(location, pathname, localeRegex);
return new Response(undefined, { headers: { location }, status: 301 });
// If route locale is not supported
} else if (!locale) {
locale = defaultLocale;
}
// Add html `lang` attribute
return resolve(
{ ...event, locals: { lang: locale } },
{
transformPageChunk: ({ html }) => html.replace('%lang%', `${locale}`),
}
);
}
return resolve(event);
};
/** @type {import('@sveltejs/kit').HandleServerError} */
export const handleError: ({
event,
}: {
event: HandleServerError & { locals: { [name: string]: string } };
}) => Promise<App.Locals> = async ({ event }) => {
const { locals } = event;
const { lang } = locals;
await loadTranslations(lang, 'error');
return locals;
};