amannn / next-intl

🌐 Internationalization (i18n) for Next.js
https://next-intl-docs.vercel.app
MIT License
2.49k stars 226 forks source link

Locale Detection: Option to change order #1020

Closed Kacper-Arendt closed 6 months ago

Kacper-Arendt commented 6 months ago

Is your feature request related to a problem? Please describe.

There should be an option to change the order of detection or remove some of them. In my app, I want to force the use of only cookies or the default locale. But right now, if there is no cookie, next-intl will take the accept-language header

The locale is detected based on these priorities:

  1. A locale prefix is present in the pathname (e.g. /en/about)
  2. A cookie is present that contains a previously detected locale
  3. A locale can be matched based on the accept-language header
  4. As a last resort, the defaultLocale is used

Describe the solution you'd like

There should be default array of priorites ["prefix", "cookie", "header", "defaultLocale"] which can be changeg for example ["cookie", "defaultLocale"]

Describe alternatives you've considered

Dont have any

amannn commented 6 months ago

Can you include some background on why you'd not want to negotiate the locale based on the accept-language header?

What you can do, is compose the middleware, assign the default locale based on the cookie and turning off localeDetection:

import createIntlMiddleware from 'next-intl/middleware';
import {NextRequest} from 'next/server';

export default async function middleware(request: NextRequest) {
  const defaultLocale = request.cookies.get('NEXT_LOCALE')?.value || 'en';

  const handleI18nRouting = createIntlMiddleware({
    locales: ['en', 'de'],
    localeDetection: false,
    defaultLocale
  });

  return handleI18nRouting(request);
}

export const config = {
  matcher: ['/', '/(de|en)/:path*']
};

Therefore if no prefix is available, the cookie value will be used, with ultimately a fallback to en.

Hope this helps!

I'll close this for the time being as additional configuration on the middleware level is currently not intended and there's already a way to achieve this.