Localisation with Next.js
In this article I am going to explain you about the a simple way that we can use to handle localisation in Next.js.
- Step 1 => Install next-intl package using below command.
npm i next-intl
2. Step 2 is configure the next.config.js file => This configuration helps us to implement the localization very easy with next.js. If you do not have next.config.js file create it in the root level of the application.
module.exports = {
i18n: {
locales: ['en', 'sn'],
defaultLocale: 'en',
},
};
From above configuration we are enable too locales. From “en” I am consider english and from “sn” I am consider Sinhala. From defaultLocale
we indicate to use english as default locale.
3. Step 3
Create folder with any name you like. I will create it as locales. Then add two json files inside the locale folder.
project
| ...
| locales/
| pages/
| ...
In those file I include json data like below.
# en.json
{
"Main": {
"title": "Good Day"
}
}
Then sn.json
# sn.json
{
"Main": {
"title": "සුබ දවසක්"
}
}
Our idea is to render “Good Day” for the localhost:3000 and “සුබ දවසක්” for localhost:3000/sn
4. Step 4
Then go to _app.js file and edit it like this. In here we config to get title props from the every page component.
import "../styles/globals.css";
import { NextIntlProvider } from "next-intl";function MyApp({ Component, pageProps }) {
return (
<NextIntlProvider messages={pageProps.title}>
<Component {...pageProps} />
</NextIntlProvider>);}export default MyApp;
5. Step 5
Then go to the index.js file and create the component like this. In here we have both normal render function and getStaticProps function. In here we use In this example we can change the locale and the language by clicking the button.
import { useRouter } from "next/router";
import { useTranslations } from "next-intl";const Home = (props) => { const tra = useTranslations("Main");
const router = useRouter(); const langHandler = () => {
router.push("/", "/", { locale: "sn" });
};return (
<div> <h1>{tra("title")}</h1> <button onClick={langHandler}> Turn to fr</button> </div>);};export default Home;
# get statics props for static generation.export const getStaticProps = async ({ locale }) => { return { props: { title: require(`../locales/${locale}.json`), }, };};
So I think from this example you get the basic idea how we can add localisation to the Next.js application.
If you want you can get the repo from here.
If you want to see the simple application demo you can see it here