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.
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} />;
}
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,
};
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With