Files
rahavard/middleware.js
2026-06-21 20:20:20 +03:30

51 lines
1.4 KiB
JavaScript
Executable File

import { match } from '@formatjs/intl-localematcher'
import Negotiator from 'negotiator'
// Get the preferred locale, similar to the above or using a library
const locales = ['en', 'fa']
function getLocale(request) {
const hostname = request.headers.get('host')?.split(':')[0]
if (hostname === 'rahavardmgp.ir' || hostname === 'www.rahavardmgp.ir') {
return 'fa'
}
if (hostname === 'rahavardmgp.com' || hostname === 'www.rahavardmgp.com') {
return 'en'
}
const headers = {
'accept-language': request.headers.get('accept-language') || 'fa'
}
const languages = new Negotiator({ headers }).languages()
return match(languages, locales, 'fa')
}
export function middleware(request) {
// Check if there is any supported locale in the pathname
const { pathname } = request.nextUrl
const pathnameHasLocale = locales.some(
(locale) => pathname.startsWith(`/${locale}/`) || pathname === `/${locale}`
)
if (pathnameHasLocale) return
// Redirect if there is no locale
const locale = getLocale(request)
request.nextUrl.pathname = `/${locale}${pathname}`
// e.g. incoming request is /products
// The new URL is now /en-US/products
return Response.redirect(request.nextUrl)
}
export const config = {
matcher: [
// Skip internal Next.js paths and public files.
'/((?!_next|.*\\..*).*)',
// Optional: only run on root (/) URL
// '/'
],
}