2025-06-08 15:52:05 +03:30
|
|
|
import { NextResponse } from 'next/server';
|
|
|
|
|
import type { NextRequest } from 'next/server';
|
2025-06-07 16:31:52 +03:30
|
|
|
|
2025-06-08 15:52:05 +03:30
|
|
|
const PUBLIC_FILE = /\.(.*)$/;
|
|
|
|
|
const locales = ['en', 'fa'];
|
|
|
|
|
const defaultLocale = 'en';
|
|
|
|
|
|
|
|
|
|
export function middleware(request: NextRequest) {
|
|
|
|
|
const { pathname } = request.nextUrl;
|
|
|
|
|
|
|
|
|
|
// Ignore public files and API routes
|
|
|
|
|
if (pathname.startsWith('/api') || PUBLIC_FILE.test(pathname)) {
|
|
|
|
|
return NextResponse.next();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Check if the pathname already includes a locale
|
|
|
|
|
const matchedLocale = locales.find(
|
|
|
|
|
(locale) => pathname.startsWith(`/${locale}/`) || pathname === `/${locale}`,
|
|
|
|
|
);
|
|
|
|
|
|
2026-07-19 07:59:16 +03:30
|
|
|
const cookieLocale = request.cookies.get('locale')?.value;
|
|
|
|
|
const preferredLocale = locales.includes(cookieLocale || '')
|
2026-07-21 12:25:19 +03:30
|
|
|
? cookieLocale!
|
2026-07-19 07:59:16 +03:30
|
|
|
: defaultLocale;
|
|
|
|
|
const locale = matchedLocale || preferredLocale;
|
2025-06-08 15:52:05 +03:30
|
|
|
|
|
|
|
|
let response: NextResponse;
|
|
|
|
|
|
|
|
|
|
// If locale is missing, redirect and set cookie
|
|
|
|
|
const pathnameIsMissingLocale = !matchedLocale;
|
|
|
|
|
if (pathnameIsMissingLocale) {
|
|
|
|
|
response = NextResponse.redirect(
|
2026-07-19 07:59:16 +03:30
|
|
|
new URL(`/${preferredLocale}${pathname}`, request.url),
|
2025-06-08 15:52:05 +03:30
|
|
|
);
|
|
|
|
|
} else {
|
|
|
|
|
response = NextResponse.next();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Set the locale cookie for all responses
|
|
|
|
|
response.cookies.set('locale', locale, { path: '/' });
|
|
|
|
|
|
|
|
|
|
return response;
|
|
|
|
|
}
|
2025-06-07 16:31:52 +03:30
|
|
|
|
|
|
|
|
export const config = {
|
2025-06-08 15:52:05 +03:30
|
|
|
matcher: ['/((?!_next/static|_next/image|favicon.ico|api).*)'],
|
2025-06-07 16:31:52 +03:30
|
|
|
};
|