Merge version_3 into main
Merge version_3 into main
This commit was merged in pull request #3.
This commit is contained in:
4
src/i18n.js
Normal file
4
src/i18n.js
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
export const i18n = {
|
||||||
|
defaultLocale: 'en',
|
||||||
|
locales: ['en', 'ar', 'fr'],
|
||||||
|
};
|
||||||
44
src/middleware.ts
Normal file
44
src/middleware.ts
Normal file
@@ -0,0 +1,44 @@
|
|||||||
|
import { NextResponse } from 'next/server';
|
||||||
|
import type { NextRequest } from 'next/server';
|
||||||
|
import { i18n } from './i18n';
|
||||||
|
|
||||||
|
const { locales, defaultLocale } = i18n;
|
||||||
|
|
||||||
|
function getLocaleFromHeaders(request: NextRequest): string {
|
||||||
|
const acceptLanguageHeader = request.headers.get('accept-language');
|
||||||
|
if (acceptLanguageHeader) {
|
||||||
|
const languages = acceptLanguageHeader.split(',').map(l => l.split(';')[0].trim());
|
||||||
|
for (const lang of languages) {
|
||||||
|
if (locales.includes(lang)) {
|
||||||
|
return lang;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return defaultLocale;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function middleware(request: NextRequest) {
|
||||||
|
const pathname = request.nextUrl.pathname;
|
||||||
|
|
||||||
|
// Check if the pathname already contains a locale
|
||||||
|
const pathnameHasLocale = locales.some(
|
||||||
|
(locale) => pathname.startsWith(`/${locale}/`) || pathname === `/${locale}`
|
||||||
|
);
|
||||||
|
|
||||||
|
if (pathnameHasLocale) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Redirect if no locale
|
||||||
|
const locale = getLocaleFromHeaders(request);
|
||||||
|
request.nextUrl.pathname = `/${locale}${pathname}`;
|
||||||
|
return NextResponse.redirect(request.nextUrl);
|
||||||
|
}
|
||||||
|
|
||||||
|
export const config = {
|
||||||
|
matcher: [
|
||||||
|
// Skip all internal paths like /_next/ (static assets, api routes, etc.)
|
||||||
|
// Also skip favicon.ico
|
||||||
|
'/((?!api|_next/static|_next/image|favicon.ico).*)',
|
||||||
|
],
|
||||||
|
};
|
||||||
Reference in New Issue
Block a user