Search code examples
configlocalemiddlewarenext.js13react-i18next

next-i18n-router automatically changing the locale variable to a random locale variable sometimes


I have used three packages for implementing i18n on a website.

"next-i18n-router": "^5.4.0",
"i18next-resources-to-backend": "^1.2.0",
"react-i18next": "^14.1.0",

Here is my i18nConfig:

{
locales: locales,
defaultLocale: "en", 
prefixDefault: false, 
}

The problem is, the cookie variable "NEXT_LOCALE" changes automatically sometimes even if I try to access any route with the defaultLocale. Let's say I try to access mywebsite.com/products, for some unknown reasons, I will be redirected to mywebsite.com/de/products.

I've tried setting the value of the "NEXT_LOCALE" to "en" too but that din't work. I also created a client component that checks the cookie and if "NEXT_LOCALE" cookie does not exist, the component will set the cookie with value "en" which din't help either. How can I fix this issue?


Solution

  • You can try using different packages. For my case, I've used "negotiator" and "@formatjs/intl-localematcher".

    Here is a simple middleware with those two packages for detecting locale from the url parameter:

    import { NextResponse } from 'next/server'
    import type { NextRequest } from 'next/server'
    
    import { i18n } from '@/i18n.config'
    
    import { match as matchLocale } from '@formatjs/intl-localematcher'
    import Negotiator from 'negotiator'
    
    function getLocale(request: NextRequest): string | undefined {
      const negotiatorHeaders: Record<string, string> = {}
      request.headers.forEach((value, key) => (negotiatorHeaders[key] = value))
    
      // @ts-ignore locales are readonly
      const locales: string[] = i18n.locales
      const languages = new Negotiator({ headers: negotiatorHeaders }).languages()
    
      const locale = matchLocale(languages, locales, i18n.defaultLocale)
      return locale
    }
    
    export function middleware(request: NextRequest) {
      const pathname = request.nextUrl.pathname
      const pathnameIsMissingLocale = i18n.locales.every(
        locale => !pathname.startsWith(`/${locale}/`) && pathname !== `/${locale}`
      )
    
      // Redirect if there is no locale
      if (pathnameIsMissingLocale) {
        const locale = getLocale(request)
        return NextResponse.redirect(
          new URL(
            `/${locale}${pathname.startsWith('/') ? '' : '/'}${pathname}`,
            request.url
          )
        )
      }
    }
    
    export const config = {
      // Matcher ignoring `/_next/` and `/api/`
      matcher: ['/((?!api|_next/static|_next/image|favicon.ico).*)']
    }