How to customize the locale prefix while keep using browser language auto-detection in nextjs?
Asked Answered
W

2

5

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?

Weizmann answered 2/6, 2024 at 10:29 Comment(0)
Z
5

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;
  }
})
Zeller answered 2/6, 2024 at 11:24 Comment(0)
M
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')
})
Monongahela answered 2/6, 2024 at 10:56 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.