next.jsnext.js13

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?


Solution

  • 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>