refactor: Creation d'un provider et d'un systeme de middleware

This commit is contained in:
Luc SORIGNET
2025-02-22 13:05:01 +01:00
parent c861239d48
commit 508847940c
18 changed files with 218 additions and 69 deletions

View File

@ -0,0 +1,42 @@
import { NextResponse } from 'next/server';
import createIntlMiddleware from 'next-intl/middleware';
import { routing } from '@/i18n/routing';
const withLocale = (next) => {
const intlMiddleware = createIntlMiddleware(routing);
return async (request, event) => {
const { pathname, search } = request.nextUrl;
// Ignorer les ressources statiques et API routes
if (pathname.startsWith('/_next') || pathname.startsWith('/api') || pathname.includes('.')) {
return next(request, event);
}
// Déterminer la locale
let locale = 'fr';
if (pathname.startsWith('/fr') || pathname.startsWith('/en')) {
locale = pathname.split('/')[1];
}
// Si pas de locale dans l'URL, rediriger vers /fr
if (!pathname.startsWith('/fr') && !pathname.startsWith('/en')) {
return NextResponse.redirect(new URL(`/fr${pathname}${search}`, request.url));
}
// Appliquer le middleware next-intl
const response = await intlMiddleware(request, event);
if (response) {
// Ajouter la locale aux headers
response.headers.set('x-locale', locale);
return response;
}
const nextResponse = await next(request, event);
// Ajouter la locale aux headers même pour les réponses suivantes
nextResponse.headers.set('x-locale', locale);
return nextResponse;
};
};
export { withLocale };