This section describes how to use react-i18next with getServerSideProps (SSR).
For information on how to install react-i18next, please refer to this section.
[Nextjs] Using i18next to make it multilingual. | Tsukurue
Do other languages on the same page, such as Japanese pages, English pages and other language pages in Next.js. Internat
目次
Add getServerSideProps middleware.
Add middleware for use with getServerSideProps.
In the middleware, we do reloadResources, because the translation load is not guaranteed at SSR timing, so we reload it in the middleware.
We then add a t-function to translate to the Context and return it.
import i18n from "@/i18n";
import { TFunction } from "i18next";
import { NextPageContext } from "next";
interface CustomAppContext {
t: TFunction;
}
export function getServerSidePropsMiddleware<T extends any>(
f: (context: NextPageContext, { t }: CustomAppContext) => Promise<T>
) {
return async (context: NextPageContext) => {
const locale = typeof context.locale === "string" ? context.locale : "ja";
await i18n.reloadResources();
const t = i18n.getFixedT(locale, null, null);
const pageProps = await f(context, { t });
return pageProps;
};
}
GetServerSideProps to get translated text per language.
It receives t-functions and translates them via getServerSidePropsMiddleware.
import { getServerSidePropsMiddleware } from "@/getServerSidePropsMiddleware";
export const getServerSideProps = getServerSidePropsMiddleware(
async (context, { t }) => {
const metaTitle = t("header.mypage");
...略
}
);
Summary
I had never used i18next with getServerSideProps before, so I did a lot of research and got support to make this happen.
I realised that my experience is to research things that I am struggling with or confused about.