import { defineMiddleware } from "astro:middleware"; import { config, isDev } from "./config.ts"; export const onRequest = isDev && defineMiddleware((context, next) => { const { url } = context; // Get the locale from the domain const host = context.request.headers.get("x-forwarded-host") || context.request.headers.get("host") || url.host; // Find which locale this domain corresponds to let domainLocale: string | undefined; for (const [locale, domain] of Object.entries(config.domains)) { const domainHost = new URL(domain as string).host; if (host === domainHost) { domainLocale = locale; break; } } // If we're on a domain-mapped locale and the path doesn't start with the locale prefix, // internally rewrite to add the prefix if (domainLocale && url.pathname === "/") { // Rewrite / to /{locale}/ return context.rewrite(`/${domainLocale}/`); } // For other paths without locale prefix, also rewrite if ( domainLocale && !url.pathname.startsWith(`/${domainLocale}/`) && !url.pathname.startsWith(`/${domainLocale}`) && !url.pathname.startsWith("/_") ) { // Check if the path starts with any other locale const startsWithOtherLocale = config.locales.some( (l: string) => l !== domainLocale && (url.pathname.startsWith(`/${l}/`) || url.pathname === `/${l}`), ); if (!startsWithOtherLocale) { return context.rewrite(`/${domainLocale}${url.pathname}`); } } return next(); });