/** * Author: Simon-Pierre Boucher * Contact: contact@spboucher.ai * Project: Hilmacorp.ai — Web Platform * File: middleware.ts * Description: Locale-prefix middleware — redirects unprefixed paths to /fr or /en * based on the NEXT_LOCALE cookie or the Accept-Language header */ import { NextRequest, NextResponse } from "next/server"; const LOCALES = ["fr", "en"]; const DEFAULT_LOCALE = "fr"; function detectLocale(request: NextRequest): string { const cookie = request.cookies.get("NEXT_LOCALE")?.value; if (cookie && LOCALES.includes(cookie)) return cookie; const header = request.headers.get("accept-language") ?? ""; for (const part of header.split(",")) { const code = part.split(";")[0].trim().slice(0, 2).toLowerCase(); if (LOCALES.includes(code)) return code; } return DEFAULT_LOCALE; } export function middleware(request: NextRequest) { const { pathname } = request.nextUrl; const hasLocale = LOCALES.some( (locale) => pathname === `/${locale}` || pathname.startsWith(`/${locale}/`) ); if (hasLocale) return NextResponse.next(); const locale = detectLocale(request); const url = request.nextUrl.clone(); url.pathname = `/${locale}${pathname === "/" ? "" : pathname}`; return NextResponse.redirect(url); } export const config = { matcher: ["/((?!api|_next|favicon.ico|icon.svg|robots.txt|sitemap.xml|.*\\..*).*)"], };