Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Initial locale argument was not passed into serverSideTranslations #1091

Closed
fuzunspm opened this issue Mar 22, 2021 · 27 comments
Closed

Initial locale argument was not passed into serverSideTranslations #1091

fuzunspm opened this issue Mar 22, 2021 · 27 comments

Comments

@fuzunspm
Copy link

Describe the bug

It won't work after upgrading both i18next and nextjs. I'm getting

Initial locale argument was not passed into serverSideTranslations

on index.js

Occurs in next-i18next version

"next-i18next": "^8.1.2",

OS (please complete the following information)

  • Device: Ubuntu 20.04, macOS BigSur
  • Browser: Firefox 86

Additional context

next-i18next.config.js

const path = require("path");

module.exports = {
  i18n: {
    defaultLocale: "en",
    locales: ["en", "tr"],
  },
  localePath: path.resolve("./public/static/locales"),
  otherLanguages: ["en", "tr"],
  defaultLanguage: "en",
  fallbackLng: ["en"],
};

next.config.js

const dotEnvResult = require("dotenv").config();
const path = require("path");
const withImages = require("next-images");
const withCSS = require("@zeit/next-css");
const withLess = require("@zeit/next-less");
const { i18n } = require("./next-i18next.config");
...

module.exports = withCSS(
  withLess(
    withImages({
      lessLoaderOptions: {
        javascriptEnabled: true,
      },
      env: {
        ...
      },
      ...
      i18n,
      webpack: (config) => {
        config.node = {
          fs: "empty",
        };
        return config;
      },
    })
  )
);

_app.js

import React from "react";
import App from "next/app";
// import { appWithTranslation } from "../i18n";
import { appWithTranslation } from "next-i18next";
...

class MyApp extends App {
  render() {
    const { Component, pageProps } = this.props;
    return <Component {...pageProps} />;
  }
}

export default appWithTranslation(MyApp);

index.js

import React from "react";
import Link from "next/link";
// import { i18n, Link, withTranslation } from "../i18n";
import { serverSideTranslations } from "next-i18next/serverSideTranslations";
import {withTranslation} from "next-i18next"
...

export async function getServerSideProps(locale) {
  console.log(locale.locale, locale.req.query);
  return {
    props: {
      ...(await serverSideTranslations(locale.locale, ["common"])),
      userQuery:
        typeof locale.req.query === "undefined" ? null : locale.req.query,
    },
  };
}

class Index extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      ...
    };
  }

  ...
  render() {
    return (
        ...
    );
  }
}

export default withTranslation("common")(Index);
@isaachinman
Copy link
Contributor

isaachinman commented Mar 22, 2021

Please post on StackOverflow for help.

@AhsanNissar
Copy link

There should be answer to this. The stackoverflow thread of this query shows an answer but it is not accepted and I tried that way too but it didn't work. My nextjs app build is failing due to this

@AhsanNissar
Copy link

This is the error I am getting on build

Error occurred prerendering page "/account-activate-provider-link". Read more: https://err.sh/next.js/prerender-error

Error: Initial locale argument was not passed into serverSideTranslations

@isaachinman
Copy link
Contributor

The error is self-explanatory:

Initial locale argument was not passed into serverSideTranslations

In @fuzunspm's case, they should double check what locale.locale is, because it's probably undefined.

@AhsanNissar There may indeed be an issue with plugin composition here, but that is going to vary, case-by-case. next-i18next only requires that you pass the i18n object into your next.config.js. How you manage your config will depend on your use case.

@AhsanNissar
Copy link

This is my next-i18next.config.js code

module.exports = {
  i18n: {
    defaultLocale: 'en',
    locales: ['en', 'de'],
    defaultLanguage: 'en',
    fallbackLng: ['en'],
  },
};

and I just passed i18n in next.config.js by requiring it like this const { i18n } = require('./next-i18next.config');
The problem is at places like this

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

The locale is not initialized when making a build but when runningg the application it takes into account the deaultLocale and works fine.

@isaachinman
Copy link
Contributor

@AhsanNissar If you believe as though you have found a bug in next-i18next, please open a GitHub issue with a reproducible repository. Thanks!

@fuzunspm
Copy link
Author

@AhsanNissar There is an issue about next-i18next but I don't know how to debug or fix it and maintainers don't have any desire to accept and fix it. I used getStaticProps as a workaround like below. In addition to that you may have to modify your package.json for react and react-dom to use "next" version

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

@isaachinman
Copy link
Contributor

@fuzunspm Fixing a bug starts with a reproducible example, which I have not yet seen. Thanks.

@fuzunspm
Copy link
Author

your first reply was about directing me to stackoverflow and I can see many examples in the issues. Anyway, I already commented a workaround for the issue

@AhsanNissar
Copy link

@fuzunspm My application is built with nextjs and not with reactjs so I do not need to add any workaround and according to example in this repo they are already using getStatucProps. Nevertheless, I know there is an issue and I have already created a repl for it but I need to give that repo the same structure as my application just to reproduce that error. @isaachinman I'll try on this weekend to create a reproducible example and if successfull, then I will provide you with a link in my issue that I have opened today.

@fuzunspm

This comment has been minimized.

@isaachinman
Copy link
Contributor

Thanks @AhsanNissar, let's continue discussion there.

@AhsanNissar
Copy link

@fuzunspm maybe you need to see this https://stackoverflow.com/a/67066847/11746564

@NVS89
Copy link

NVS89 commented May 28, 2021

Hello everybody. I faced with this issue today during docker deployment. Please be sure that you copy your next.config.js and next-i18next.config.js in your docker container (or deployment service). If you missed next.config.js then next.js after deployment will use default settings without next-i18next.config.js and as result initial local will be undefined. I hope it helps some one. Happy coding.
https://nextjs.org/docs/deployment
image

@keremcanb
Copy link

Hello everybody. I faced with this issue today during docker deployment. Please be sure that you copy your next.config.js and next-i18next.config.js in your docker container (or deployment service). If you missed next.config.js then next.js after deployment will use default settings without next-i18next.config.js and as result initial local will be undefined. I hope it helps some one. Happy coding.

Thanks a lot, I got it working. I added these 2 lines according to your message:

COPY --from=builder /app/next.config.js ./
COPY --from=builder /app/next-i18next.config.js ./

@fuzunspm
Copy link
Author

fuzunspm commented Jun 6, 2021

Finally! Main issue is, even if you have default language is set, you have to render first page, index.js, with /en/index or /tr/index, or use routing to / instead of /index, after that everything works as expected

@jason-crawford-xio
Copy link

Finally! Main issue is, even if you have default language is set, you have to render first page, index.js, with /en/index or /tr/index, or use routing to / instead of /index, after that everything works as expected

Congrats. Unfortunately I don't understand what you're saying. Could you explain further what you've done to resolve this?

In my case I'm not using i18n routing and have not modified next.config.js to include i18n. At this point I don't know where/how the locale.locale should be set and what the value of locale.locale should be. Ex. a string, an object, or...?

@fuzunspm
Copy link
Author

locale is string. to solve my issue I had to replace all of my /index routers to / path

@Shariaty
Copy link

Hello everybody. I faced with this issue today during docker deployment. Please be sure that you copy your next.config.js and next-i18next.config.js in your docker container (or deployment service). If you missed next.config.js then next.js after deployment will use default settings without next-i18next.config.js and as result initial local will be undefined. I hope it helps some one. Happy coding.
https://nextjs.org/docs/deployment
image

Thanks a lot man. You saved my day

@mattcrn
Copy link

mattcrn commented Jul 5, 2021

For me, upgrading next to the latest version solved the issue.

@ClarenceC
Copy link

I update Next version or downgrade next-i18next solved the issue.

@ziedHamdi
Copy link

ziedHamdi commented Aug 26, 2021

I started having the issue since I added next-compose-plugins to be able to run bundle-analyzer along with i18next

next.config.js

const withPlugins = require('next-compose-plugins')
const { i18n } = require('./next-i18next.config');
const withBundleAnalyzer = require("@next/bundle-analyzer")({
    enabled: process.env.ANALYZE === "true",
});

module.exports = withPlugins([
    [withBundleAnalyzer],
    i18n
])

Things were working fine with this config:

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

module.exports = {
    i18n,
};

Now I'm stuck for an hour trying to figure out what started to be missing to i18next.
I think this is a topic worth considering by the i18next team since it is something everyone will encounter when he will want to optimize his app

This is the error I get:

Error occurred prerendering page "/". Read more: https://nextjs.org/docs/messages/prerender-error
Error: Initial locale argument was not passed into serverSideTranslations
    at _callee$ (D:\Work\WeAlly.org\node_modules\next-i18next\dist\commonjs\serverSideTranslations.js:169:19)
    at tryCatch (D:\Work\WeAlly.org\node_modules\regenerator-runtime\runtime.js:63:40)
    at Generator.invoke [as _invoke] (D:\Work\WeAlly.org\node_modules\regenerator-runtime\runtime.js:293:22)

image

@grace618
Copy link

grace618 commented Sep 2, 2021

how to solve this problem

@edward-tes
Copy link

Hello everybody. I faced with this issue today during docker deployment. Please be sure that you copy your next.config.js and next-i18next.config.js in your docker container (or deployment service). If you missed next.config.js then next.js after deployment will use default settings without next-i18next.config.js and as result initial local will be undefined. I hope it helps some one. Happy coding. https://nextjs.org/docs/deployment image


This solution is right. And need to copy the next-i18next.config.js to the root directory for the project.

COPY --from=builder /app/next-i18next.config.js ./

@Abdelrhmangad
Copy link

Abdelrhmangad commented Jan 25, 2022

Hi @fuzunspm, I don't know if you still facing this issue or not, but I was getting the same error message, however I found that next/link component the one was making the bug.

I was using it like this

< Link href="/register" >
{t("registerNow")}
< / Link>

, and I was able to solve it by converting it to this

< Link href="/register">
< a > {t("registerNow")}</ a >
</ Link>

after doing this the error not shown again, I think you can check this on your side.
note: the space in tags just to show the code

@fuzunspm
Copy link
Author

@Abdelrhmangad Thank you for your suggestion and reply. I eventually replaced this package with a custom made one but I will try it anyway on a test project.

@AnubhavGuptaVeative
Copy link

AnubhavGuptaVeative commented Jul 28, 2022

I had similar problem.

Turns out the mechanism I was using wasn't appropriate.

I wasn't using locale in the URL when it comes to the defaultLocale

For example, my URLs are of type http://localhost:3000/auth/live-counselling while they should be of type http://localhost:3000/en/auth/live-counselling

Further, in my configuration, I have declared localeDetection false for some clash in headers coming from foreign region where pages were failing (niche bug reported over sentry)

module.exports = {
  i18n: {
    defaultLocale: 'en',
    locales: ['en', 'hi'],
    /**
     * Turn off automatic locale detection based on header (Accept-Language) or domain
     */
    localeDetection: false
  },
  /**
   * updates to your translation JSON files without having
   * to restart your development server
   */
  reloadOnPrerender: true,
  // react: { useSuspense: false } //this line
  /**
   * Preload the translations
   */
  ns: ['common']
};

So, what was essentially happening was my locale in getStaticProps was always undefined

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

The fix I made was to involve defaultLocale voila everything is working again

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

My packages are as follows

    "next": "^12.2.3",
    "next-auth": "^4.10.2",
    "next-i18next": "^11.3.0",
    "next-redux-wrapper": "^7.0.5",
    "next-transpile-modules": "^9.0.0",

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests