Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect browser language with NextJS built-in i18n

Is there a way to implement language detection in Next with the default language detection, or will I have to use a 3rd party package? Couldn't find anything in the docs.

I want the initial language be based on user's browser language.

like image 562
Filip Avatar asked Sep 11 '25 04:09

Filip


2 Answers

import { useEffect } from 'react';
import { useRouter } from 'next/router';

export default function MyApp({ Component, pageProps }) {
  const router = useRouter();

  useEffect(() => {
    // Detect the browser's preferred language
    const browserLang = navigator.language || navigator.userLanguage;
    const supportedLocales = ['en', 'tr'];
    let detectedLocale = 'en'; // fallback to 'en-US' if the browser's language is not supported

    if (supportedLocales.includes(browserLang)) {
      detectedLocale = browserLang;
    }

    // If the user hits the root path, redirect based on the browser's language
    if (router.pathname === '/') {
      router.replace(`/${detectedLocale}`);
    }
  }, [router.pathname]);

  return <Component {...pageProps} />;
}
like image 123
Kaan Avatar answered Sep 13 '25 18:09

Kaan


https://next-intl-docs.vercel.app/docs/getting-started/app-router/without-i18n-routing#i18nts

i18n.ts

import { getRequestConfig } from "next-intl/server";
import { cookies, headers } from "next/headers";

export default getRequestConfig(async () => {
  // Provide a static locale, fetch a user setting,
  // read from `cookies()`, `headers()`, etc.
  const headersList = headers();
  const defaultLocale = headersList.get("accept-language");
  const locale = cookies().get("NEXT_LOCALE")?.value || defaultLocale || "en";
  // const locale = 'en';

  return {
    locale,
    messages: (await import(`../messages/${locale}.json`)).default,
  };
});
like image 41
Kun Luo Avatar answered Sep 13 '25 19:09

Kun Luo