ReactJS
How to Implement SSR & CSR in Next.js for Multilingual Websites
Introduction
Next.js allows us to quickly support multi language with simple configurations and code. In this blog, we'll walk you through the process of creating a multilingual website using Next.js, covering setup, routing, translations and best practices.
Why Choose Next.js for Multilingual Websites?
Next.js provides a number of features that make it the perfect choice for multilingual website development:
- Internationalized Routing: Native support for localized routing.
- Static Site Generation (SSG): Pre rendered pages for improved performance and SEO.
- Dynamic Import: Load only the required translations for a specific locale efficiently.
- Rich Ecosystem: Easy implementation with popular libraries such as i18next and next-i18next.
- Flexibility: Provide (SSR,CSR) options for dynamic content
Setting Up a Multilingual Next.js Project
Step 1: Initialize the Project
npx create-next-app multilingual-sitecd multilingual-site
Step 2: Configure Internationalized Routing
Next.js simplifies multilingual routing with its i18n configuration. Open the next.config.js file and add the following:
module.exports = { i18n: { locales: ['en', 'fr', 'es'], // Supported languages defaultLocale: 'en', // Default language },};
This configuration enables localized routes such as /fr and /es for French and Spanish, respectively.
Step 3: Install Translation Libraries
npm install next-i18next react-i18next i18nextStep 4: Set Up the Translation Files
Create a public/locales directory and add subfolders for each language. Inside each folder, create a common.json file for shared translations. For example:
Structure:
public/ locales/ en/ common.json fr/ common.json es/ common.json
Example common.json (English):
{ "welcome": "Welcome to our website!", "description": "This is a multilingual site."}
Step 5: Initialize next-i18next
Create a file named i18n.js in the root of your project:
import i18n from 'i18next';import { initReactI18next } from 'react-i18next';import Backend from 'i18next-http-backend';import LanguageDetector from 'i18next-browser-languagedetector';i18n .use(Backend) .use(LanguageDetector) .use(initReactI18next) .init({ fallbackLng: 'en', lng: 'en', interpolation: { escapeValue: false, // React already escapes by default }, backend: { loadPath: '/locales/{{lng}}/{{ns}}.json', }, });export default i18n;
Step 6: Wrap Your App with the Translation Provider
Modify the pages/_app.js file to include the translation provider:
import '../styles/globals.css';import { appWithTranslation } from 'next-i18next';function MyApp({ Component, pageProps }) { return <Component {...pageProps} />;}export default appWithTranslation(MyApp);
Step 7: Use Translations in Components
To use translations in your components, import the useTranslation hook:
import { useTranslation } from 'react-i18next';export default function Home() { const { t } = useTranslation('common'); return ( <div> <h1>{t('welcome')}</h1> <p>{t('description')}</p> </div> );}
Step 8: Add a Language Switcher
Create a simple language switcher component to allow users to change languages:
import { useRouter } from 'next/router';export default function LanguageSwitcher() { const router = useRouter(); const { locales, locale, pathname } = router; const switchLanguage = (lang) => { router.push(pathname, pathname, { locale: lang }); }; return ( <div> {locales.map((lang) => ( <button key={lang} onClick={() => switchLanguage(lang)} style={{ fontWeight: lang === locale ? 'bold' : 'normal' }} > {lang} </button> ))} </div> );}
Step 5: Initialize next-i18next
It is easy and effective to build a multilingual website with Next.js due to its internationalization capabilities built in and direct integration with translation libraries. If you follow the above steps and use best practices, you can build a friendly, accessible to the world website that serves international audiences.
Ready to transform your business with our technology solutions? Contact Us today to Leverage Our ReactJS Expertise.
Comment