Something went wrong. Try again.
https://clembs.com
Something went wrong. Try again.
12345678910111213141516171819202122232425262728293031323334353637383940414243import { DEFAULT_LOCALE, LOCALE_CODES, removeTrailingSlash, useTranslatedPaths } from '@i18n';import { defineMiddleware } from 'astro:middleware';import { handleRedirect } from './redirects';
export const onRequest = defineMiddleware((context, next) => { const [_, langParam, ...restUrl] = context.url.pathname.split('/');
const noLangPathname = LOCALE_CODES.includes(langParam) ? `/${restUrl.join('/')}` : context.url.pathname;
// if it's an astro-reserved path, // or an api path, skip it if (noLangPathname.startsWith('/_') || noLangPathname.startsWith('/api')) { return next(); }
// check for redirections first const redirectedUrl = handleRedirect(noLangPathname) ?? handleRedirect(context.url.pathname); if (redirectedUrl) { return context.redirect(removeTrailingSlash(redirectedUrl)); }
// if there's no lang parameter, detect language and redirect if (!langParam || !LOCALE_CODES.includes(langParam)) { const headerLang = context.request.headers.get('Accept-Language'); const pathnameWithParams = context.url.href.replace(context.url.origin, ''); const path = removeTrailingSlash(pathnameWithParams);
// if the lang is french, serve the content in french if (headerLang?.includes('fr')) { const translatePaths = useTranslatedPaths('fr'); return context.redirect(translatePaths(path)); }
// otherwise serve english const translatePaths = useTranslatedPaths(DEFAULT_LOCALE); return context.redirect(translatePaths(path)); }
return next();});