skip to Main Content

I am using next-international package for i18n in my nextjs application.
Mostly working well but I want to customize the prefix of the locale.

In short, what we want is localhost:3000/ for default locale, but localhost:3000/us for english locale, not localhost:3000/en from accept-languages. But, want to keep using browser language detection.

In my middleware.ts, currently only works with /en.

export const I18nMiddleware = createI18nMiddleware({
  locales: ["en", "de"],
  defaultLocale: "de",
  urlMappingStrategy: "rewriteDefault",
})

export default async function middleware(request: NextRequest) {
  return I18nMiddleware(request)
}

Because we detect the first language from browser header (accept-language), we can’t set like locales: ['us', 'de'] since browser just tell us en value otherwise it redirects to the defaultLocale.

Is there anyway to handle this?

2

Answers


  1. I didn’t try, but I think you can try:
    so you can update:

    enter image description here

    export const { useI18n, useScopedI18n, I18nProviderClient } = createI18nClient({
      us: () => import('./en'),
      de: () => import('./de')
    })
    
    Login or Signup to reply.
  2. You can do this using resolveLocaleFromRequest method from next-international:

    // middleware.ts
    const I18nMiddleware = createI18nMiddleware({
      locales: ['en', 'de'],
      defaultLocale: 'de',
      urlMappingStrategy: "rewriteDefault",
      resolveLocaleFromRequest: request => {
          // 1. Retrieve locale from the Accept-Language header
          const acceptLanguage = request.headers.get('accept-language');
          const browserLocale = acceptLanguage.split(',')[0].split('-')[0];  
    
           // 2. If locale is equal to "en", then return "us"
          if (browserLocale === "en") {
               return "us"
          }
      
          return browserLocale;
      }
    })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search