Search code examples
typescriptnext.jsi18next

Configure next-i18next with NextJS and Typescript


Using the next-i18next library on NextJS and Typescript I encountered the problem reported at the bottom. How can I fix it? I also uploaded the code of the files where I use the library, nothing special.

_app.tsx

import { appWithTranslation } from "next-i18next"

const MyApp = ({ Component, pageProps }: AppProps) => {
  return <Component {...pageProps} />
}

export default appWithTranslation(MyApp);

index.tsx

export const getStaticProps = async ({ locales }:{locales: string}) => {
    return {
        props: { ...(await serverSideTranslations(locales, ['common'])) }
    };
};

next-i18next.config.js

module.exports = {
    i18n: {
      defaultLocale: 'en',
      locales: ['en', 'it']
    },
} 

next.config.js

const { i18n } = require('./next-i18next.config');

module.exports = {
    i18n
}

ERROR:

 Error: Initial locale argument was not passed into serverSideTranslations
enter code here

Solution

  • Parameter name is locale not locales . You're passing current locale not all locales. My code snippet

    index.tsx

     import { getStaticPropsTranslations } from '@/utils/i18n'    
     export async function getServerSideProps({ locale }: { locale: string }) {
        return {
            props: {
                ...(await getStaticPropsTranslations(locale)),
            },
        }
    }
    

    @/utils/i18n.ts

    import { serverSideTranslations } from 'next-i18next/serverSideTranslations'
    
    export const getStaticPropsTranslations = async (locale: string) => {
          return {
             ...(await serverSideTranslations(locale, ['instructions',])),
          }
    }