import { 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(); });