Skip to content

custom language selection not working SSR #176

@HANYUNSEONG

Description

@HANYUNSEONG

Hi, using ni18n in Next.js.

I want locale code hide to url.
So, I made it according to the example (customer-language-selection)

Then the desired function was realized but, SSR not working.
When the page is delivered on the server side, it looks like English and changes to the language you set on the client after it is loaded.

next.config.js

/** @type {import('next').NextConfig} */
const nextConfig = {
  reactStrictMode: true,
};

module.exports = nextConfig;

_app.tsx

import { appWithI18Next, useSyncLanguage } from "ni18n";
import { ni18nConfig } from "../../ni18n.config";

const MyApp = ({ Component, pageProps }: any) => {
  const locale =
    typeof window !== "undefined"
      ? (window.localStorage.getItem("MY_LANGUAGE") as string)
      : "";

  useSyncLanguage(locale);

  return <Component {...pageProps} />;
};

export default appWithI18Next(MyApp, ni18nConfig);

ni18n.config.js

const supportedLngs = ["en-US", "ko-KR"];

export const ni18nConfig = {
  /**
   * Set `fallbackLng` to the `supportedLngs` array in order for them all to be loaded
   */
  fallbackLng: supportedLngs,
  supportedLngs,
  ns: ["translation"],
  react: {
    useSuspense: false,
  },
};

index.tsx

import { loadTranslations } from "ni18n";
import { useTranslation } from "react-i18next";
import { ni18nConfig } from "../../ni18n.config";

/**
 * Manually change the language and store the selected on localStorage
 */
const changeLanguage = (i18n: any, language: any) => {
  window.localStorage.setItem("MY_LANGUAGE", language);
  i18n.changeLanguage(language);
};

const languages = [
  { code: "en-US", translateKey: "english" },
  { code: "ko-KR", translateKey: "korean" },
];

function Home() {
  const { t, i18n } = useTranslation();

  return (
    <div>
      <h1>{t("test")}</h1>
      {i18n.language}
      {languages.map((language) => (
        <button
          data-id={`${language.code}-button`}
          className={i18n.language === language.code ? "active" : undefined}
          onClick={() => changeLanguage(i18n, language.code)}
          key={language.code}
        >
          {t(language.translateKey)}
        </button>
      ))}
    </div>
  );
}

export const getServerSideProps = async (props) => {
  return {
    props: {
      ...(await loadTranslations(ni18nConfig, props.locale, ["translation"])),
    },
  };
};

export default Home;

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions