Developer
Developer

Reputation: 81

Nextjs 13 get locale from server component

I want to get locale from component without using 'use client'. Is it possible with nextjs 13 with app router?

import en from '@/public/locales/en.json';
import ru from '@/public/locales/ru.json';
    const Header = () => {
       const router = useRouter();
       const {locale} = router;
       const t = locale === 'en' ? en : ru;
       return <div>{t.title}</div>
    }

    const nextConfig = {
        i18n: {
            locales: ['en', 'ru']
        }
    }

It gives an error "useRouter only works in Client Components. Add the "use client" directive at the top of the file to use it". 'use client' solve this. How to get locale code, example 'en' to get locale from local file?

Upvotes: 0

Views: 8082

Answers (3)

Sirawich voungchuy
Sirawich voungchuy

Reputation: 352

import { getLocale } from "next-intl/server";

export default async function Home() {
  const locale = await getLocale();
  return (
     <main>
       <div>{locale}</div>
     </main>
   );
}

you need to put await cause getLocale return promise value and make sure the component

Upvotes: 0

FlexCoco
FlexCoco

Reputation: 48

If anyone still need it, you can use {useLocale} from "next-intl" and use it inside your server component.

import { useLocale } from "next-intl/server";
    
export default function ServerComponent() {
    const locale = useLocale()
      
    return (
      <div>{locale}</div>
    );
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

Upvotes: 0

hamdi islam
hamdi islam

Reputation: 1521

you can import getLocale from "next-intl/server" and use it inside your server component

import { getLocale } from "next-intl/server";

export default function Home() {
  const locale = getLocale();
  return (
     <main>
       <div>{locale}</div>
     </main>
   );
}

Upvotes: 1

Related Questions