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?

2 Answers 2

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;
  }
})
Sign up to request clarification or add additional context in comments.

Comments

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')
})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.