43 lines
1.0 KiB
TypeScript
43 lines
1.0 KiB
TypeScript
|
|
import { NextResponse } from 'next/server';
|
||
|
|
import type { NextRequest } from 'next/server';
|
||
|
|
|
||
|
|
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 pathnameIsMissingLocale = locales.every(
|
||
|
|
(locale) => !pathname.startsWith(`/${locale}/`) && pathname !== `/${locale}`
|
||
|
|
);
|
||
|
|
|
||
|
|
if (pathnameIsMissingLocale) {
|
||
|
|
// Redirect to default locale
|
||
|
|
return NextResponse.redirect(
|
||
|
|
new URL(`/${defaultLocale}${pathname}`, request.url)
|
||
|
|
);
|
||
|
|
}
|
||
|
|
|
||
|
|
return NextResponse.next();
|
||
|
|
}
|
||
|
|
|
||
|
|
export const config = {
|
||
|
|
matcher: [
|
||
|
|
/*
|
||
|
|
Match all request paths except for:
|
||
|
|
- static files (/_next/static/)
|
||
|
|
- API routes (/api/)
|
||
|
|
*/
|
||
|
|
'/((?!_next/static|_next/image|favicon.ico|api).*)',
|
||
|
|
],
|
||
|
|
};
|