Javascript Web Development

Creating a Multi-Language Website with Next.js

December 5th, 2023 | By Ejiro Thankgod | 13 min read

In the current digital landscape, the need for websites to transcend language barriers has become more vital than ever before. As the online audience becomes increasingly diverse and global, the ability to communicate effectively in multiple languages has transformed from a mere feature to an essential requirement. In response to this demand, Next.js, a versatile and advanced framework for building React applications, offers a robust foundation for creating dynamic and user-friendly multi-language websites.


By seamlessly blending the power of server-side rendering, dynamic routing, and integration with translation libraries, Next.js empowers developers to craft immersive and culturally relevant online experiences that resonate with audiences around the world. 


To reach a global audience and give non-native English speakers a better user experience, you must build a multilingual website. Although there are many ways to add multi-language support to a web application, Next.js' integrated support for server-side rendering and static site generation streamlines the procedure. 


Importance of Multi-Language


Incorporating multiple languages into websites is a strategic decision that not only broadens your audience but also demonstrates a commitment to effective communication, inclusivity, cultural appreciation, and business success. The following are the importance of multi-language.


  1. Global Reach: A multi-language website expands your audience on a global scale by overcoming language barriers.

  2. Cultural Connection: Providing content in users' native languages fosters stronger connections and trust, showing cultural sensitivity.

  3. User Satisfaction: Catering to users in their preferred languages enhances their experience and satisfaction on your website.

  4. Diversified Risk: Expanding into multiple markets reduces dependency on a single market, spreading business risk.

  5. Competitive Advantage: Websites offering multi-language support stand out, retaining visitors, and establishing authority.

  6. Global Reputation: Multi-language websites contribute to building a global reputation and credibility for your brand.

  7. SEO and Discoverability: Content in multiple languages can improve search engine visibility in various regions.

  8. Educational Resources: Websites catering to multiple languages can serve as valuable educational resources for language learners.


What Is next-i18next?


next-i18next is a popular internationalization (i18n) library designed specifically for use with Next.js applications. It streamlines the process of implementing multi-language support in Next.js projects, facilitating the development of websites that can be shown in several languages.


To serve a varied user base, internationalization entails adapting a website's content to different linguistic and cultural contexts.


 next-i18next simplifies this complex task by providing tools and utilities that seamlessly integrate with Next.js's server-side rendering capabilities.


Key features of next-i18next include:


  1. Automatic Language Detection: 

  2. Server-Side Rendering (SSR): 

  3. Translation Management: 

  4. Variable Replacement: 

  5. Pluralization and Context: 

  6. Custom Routing:

  7. Hot Module Replacement (HMR): 

  8. Comprehensive Documentation: 


By leveraging next-i18next, developers can efficiently create multi-language Next.js applications without getting bogged down in the complexities of internationalization. This library simplifies the integration of translation management, rendering, and routing, allowing developers to focus more on building user-friendly and culturally relevant web experiences.


Set Up Development Environment


To begin with, we’ll have to create our Next app, and to do that, we’ll have to run the command line below:


npx create-next-app@latest


Note: For us not to get disoriented while building our website, we should take note that Nextjs has two ways of creating their directory (app and page), which plays a major role in how we build our multi-language website. For this tutorial, we’ll be building with the Page directory.


Follow all prompts after running the command above by selecting “NO” at every step of the way.

select-no-stepOnce created, we’ll now have a project located in the my-app folder with the following file structure:


my-app
├── README.md
├── jsconfig.json
├── next.config.js
├── node_modules
├── package-lock.json
├── package.json
├── pages
│   ├── app.js
│   ├──
document.js
│   ├── api
│   └── index.js
├── public
└── styles


Install Dependencies

The major dependencies we need are next-i18next, which helps in the translation of text to other languages, and we’ll be installing it as well as other dependencies needed.


npm install next-i18next
npm install react-intl


As for the react-intl it’s used in formatting messages in a way that's culturally appropriate for different locales.


Translating the Content


For us to begin, first we have to configure our next.config.js file by letting the website know that we’re using i18n.



/** @type {import('next').NextConfig} */
const nextConfig = {  
reactStrictMode: true,  
i18n: {    
locales: ["en", "fr"],    
defaultLocale: "en",    
localeDetection: false  
}
}
module.exports = nextConfig


Create i18n Folder

We’re going to create an i18n folder in the root folder of our app and we’re going to create a JSON file which is where we’re going to do the translation for the pages of our website.

For en.json

//i18n/en.json//
{
    "page.home.head.title": "Next.js i18n example",
    "page.home.head.meta.description": "Next.js i18n example - English",
    "page.home.title": "Welcome to <b>the home page</b>",
    "page.home.description": "The home page that you are currently viewing is in English."
}


For fr.json

//i18n/fr.json//
{
    "page.home.head.title": "Next.js i18n exemple",
    "page.home.head.meta.description": "Next.js i18n exemple - Français",
    "page.home.title": "Bienvenue sur <b>la page d'accueil</b>",
    "page.home.description": "La page d'accueil que vous consultez actuellement est en français.""La page d'accueil que vous consultez actuellement est en français.""La page d'accueil que vous consultez actuellement est en français."
}


Define our Localized Page

It's time to create a Next.js page with some material in multiple languages. Update the pages/index.js file to change your website's home page:


//pages/index.js//
import { useRouter } from "next/router";
import { FormattedMessage, useIntl } from "react-intl";
import Link from "next/link";

import Head from "next/head";

export default function Home({ dir }) {  
const { locales } = useRouter();  
const intl = useIntl();  

const title = intl.formatMessage({ id: "page.home.head.title" });  
const description = intl.formatMessage({    
id: "page.home.head.meta.description",  
});  

return (    
<>      
<Head>        
<title>{title}</title>       
 <meta name="description" content={description} />      
</Head>      
<main dir={dir}>        
<h1>          
<FormattedMessage            id="page.home.title"            
values={{ b: (info) => <b>{info}</b> }}          
/>        
</h1>        
<p>          
<FormattedMessage id="page.home.description" />        
</p>      
</main>    
</>  );
}


  • We define the Home component. The Home component takes a prop, dir, It indicates the content's textual orientation.

  • We use the useRouter hook to get the current locale, which is the language and region that the user is currently using.

  • The Home component then uses the useIntl hook to get the Intl context. The Intl context provides access to the translation files.

  • The Home component then calls the intl.formatMessage() method to get the translated title and description for the page. The intl.formatMessage() method takes two arguments:

    • The ID of the message in the translation file.

    • An object that maps message variables to their values.

  • The message's ID in this instance is "page.home.head.title" for the title and "page.home.head.meta.description" for the description. 

  • The intl.formatMessage() method returns a string that contains the translated message. The Home component then uses the FormattedMessage component to render the translated message.


Finally, before we run our application, we should update our pages/_app.js file below else we might run into some errors:

//_app.js//

import { useRouter } from 'next/router'
import { IntlProvider } from 'react-intl'
import en from '../i18n/en.json'
import fr from '../i18n/fr.json';
const messages = {
  en,fr
}
function getDirection(locale) {
  return "Itr";
}
export default function App({ Component, pageProps }) {
  const {locale} = useRouter();
  return (
    <IntlProvider locale={locale} messages={messages [locale]}>
      <Component {...pageProps} dir={getDirection(locale)} />
    </IntlProvider>
)}


_app.js is the entry point for which our app has to run and also to know which language we should switch between. First, we’ll import the JSON files (en, fr) and specify their properties. the useRouter() hook to get the current locale so that whichever language we switch to, we remain on the same page. Also, we need to wrap the entire Component with the IntlProvider tag to let our website know we are using a translator.


Overall, the user's current locale is used to determine which translation file to use. The messages in the translation file are then rendered using the IntlProvider component. This allows the messages to be dynamically updated based on the user's locale. So if we go over to our web page, we can see that we’ve rendered a multi-language website beautifully.

welcome-to-the-homepage-example

As we can see above, the current page will change to the corresponding language page when we switch between English (en) and French (fr) via the url. However, it would be helpful to have a link or button that the user could click to quickly switch to the other language page. For example, if the user is currently viewing the page in English and they want to switch to French, they could click on a link or button that says "French" or “fr”. This would take them to the French language page of the same content. This would be a helpful feature for users who want to quickly switch between languages without having to memorize URLs. It would also be helpful for users who are not sure which language page they want to view.

[LEARN MORE] How To Protect Next.js Apps with Jscrambler

Switching Between Languages


The dynamic routing facilitated by the useRouter hook lays the groundwork for the language switcher, allowing users to effortlessly toggle between languages. Through useIntl, the code enables message translation and formatting tailored to the user's locale, enhancing user engagement. With that said we’ll create a language switcher component that dynamically generates links for switching between different language versions of a webpage.

<div>
          {[...locales].sort().map((locale) => (
            <Link key={locale} href="/" locale={locale}>
              <div>{locale}</div>
            </Link>
          ))}
        </div>


The combination of the locales array obtained from useRouter() and the intl object from useIntl() enables the generation of a language switcher component. Using the Link component from next/link, this component generates links for the available language versions. The ease with which users can switch between languages improves the website's accessibility and usefulness. The intl object ensures that user interface elements, including the labels in the language switcher, are presented in the user's preferred language.


Now if we go to our website, you can see that we’ll be able to switch between languages by clicking on the initials of the language.


Conclusion


Crafting a multi-language website using Next.js brings a seamless and engaging user experience to the forefront of modern web development. By harnessing Next.js's dynamic routing and server-side rendering capabilities, developers can effortlessly tailor content to diverse linguistic audiences. This endeavor not only expands a website's global reach but also exemplifies a commitment to inclusivity and accessibility.


Through efficient integration of translation libraries and proper structuring of language-specific components, a multi-language website becomes an elegant fusion of cutting-edge technology and user-centric design. As businesses and creators strive to break down language barriers, Next.js emerges as a powerful tool that empowers the realization of truly connected and multilingual online platforms.


Jscrambler

The leader in client-side Web security. With Jscrambler, JavaScript applications become self-defensive and capable of detecting and blocking client-side attacks like Magecart.

View All Articles

Must read next

Application Security

How To Protect Next.js Apps with Jscrambler

In this article, we’ll look at how you can integrate Jscrambler into your Next.js app development workflow.

September 1, 2021 | By Jscrambler | 6 min read

Web Development

Understanding Routing in Next.js

In this tutorial, you'll learn the basics of how to route pages in your Next.js application.

February 28, 2023 | By Jay Raj | 9 min read

Section Divider