import { NextResponse } from 'next/server'; import Negotiator from 'negotiator'; import { match } from '@formatjs/intl-localematcher'; const locales = ['de', 'en']; const defaultLocale = 'de'; // Get the preferred locale function getLocale(request) { const headers = { 'accept-language': request.headers.get('accept-language') }; const languages = new Negotiator({ headers }).languages(); return match(languages, locales, defaultLocale); } export function middleware(request) { // Check if there is any supported locale in the pathname const pathname = request.nextUrl.pathname; const pathnameIsMissingLocale = locales.every( (locale) => !pathname.startsWith(`/${locale}/`) && pathname !== `/${locale}` ); // Redirect if there is no locale if (pathnameIsMissingLocale) { //console.log(request); const locale = getLocale(request); // Redirect to new URL return NextResponse.redirect(new URL(`/${locale}${pathname}`, request.url)); } } export const config = { matcher: [ // Skip all internal paths (_next) '/((?!_next|assets|favicon.ico).*)', // Optional: only run on root (/) URL // '/' ], };