Search code examples
reactjsnext.jsinternationalizationnode.js-fsnext-i18next

i18n NextJS "FS Module not found: Can't resolve 'fs'" on component only


this is my first question here so sorry if formatting or doing anything else wrong. Here to learn.

If I run this code from index.js. The correct translation will be pulled and logged.

import React from 'react';
import { withTranslation } from 'next-i18next';
import { serverSideTranslations } from 'next-i18next/serverSideTranslations';

const Homepage = ({ t }) => {
    return (
        <>
            {t('footer.address')}
        </>

);
};

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

export default withTranslation('common')(Homepage);

If I run this code from a component, like navbar.js and insert it in index.js or any other page like such:

import React from 'react';
import { withTranslation } from 'next-i18next';
import { serverSideTranslations } from 'next-i18next/serverSideTranslations';

const Nav = ({ t }) => {
    return (
        <>
            <div>{t('navbar.address')}</div>
        </>
    );
};

export async function getServerSideProps({ locale }) {
    return {
        props: {
            ...(await serverSideTranslations(locale, ['common'])),
        },
    };
}

export default withTranslation('common')(Nav);

then " ⨯ ./node_modules/next-i18next/dist/commonjs/serverSideTranslations.js:35:0 Module not found: Can't resolve 'fs'

https://nextjs.org/docs/messages/module-not-found"

ChatGPT can't help me. At first it said all translations and SSR HAD to be done at pages, not at components. But then in other answers it contradicted itself. Tried server and Static props instead of server side but same problem.

There are other solved fs problems. But I think this is more basic than the other solutions, because it works on my pages but not on the component.

TLDR: Trying to SSG translations from a component for SEO purposes. However, FS error thrown.


Solution

  • From the original documentation:

    Translate in child components You have multiple ways to use the t function in your child component:

    Pass the t function via props down to the children Pass the translated text via props down to the children, like in this example: https://github.com/i18next/next-i18next/blob/master/examples/simple/components/Header.tsx#L12

    Use the useTranslation function, like in this example: https://github.com/i18next/next-i18next/examples/simple/components/Footer.tsx