How to make your site multi-language using locale
Tags: javascript, webdev, programming, tutorial
Published: 2022-10-18 22:11:59

One thing that will make your site more accessible to your users is making the site translate to the user's preferred language withouth any extension.

In this tutorial I will show a simple way to add multiple languages to your site, using a [Next.js](https://nextjs.org/) app and using the package [locale](https://www.npmjs.com/package/locale).

---

## Creating the app
To do this, we open up a terminal, and type:
```
npx create-next-app multi-language-tutorial
```
This will create our Next.js app, we can now open it with our IDE of preference, and our project will look something like this:

![Folder structure](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ng2ofpkhtp5pqd2wyfxd.png)

---

## Installing our dependencies

This project only needs 1 dependency, **locale**, which we can install by running the next command:
```
npm install --save locale
```


---

## Creating the necessary files

Now that we have our proyect, we'll create a folder called **utils** (On simple words, an util is a function that we use a lot, and we make it into one file so we don't have to repeat code) and a folder called **locales**, this folder will contain our language files.

Inside the utils folder, we will create a file called **pages.js**, because it's an util that we'll use in our pages.

And inside the locales folder, we will create our locale files, using the name of the language code, for example, if I wanted to translate my app to English and Spanish, their codes are **en** and **es**, respectively, so our file names will be: `en.js` and `es.js`

So far, our project looks like this:
![New folder structure](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0rwetaep1gpjuhlwxxjb.png)

_For a list of languages codes, you can visit [this website](https://www.loc.gov/standards/iso639-2/php/code_list.php)_

---

## Creating our locale files
For this, we just need to open either **en.js** or **es.js** and follow this structure:
```js
module.exports = {
    pageName: {
        property: "Translated text",
    },
};
```

For example, for **en.js** we would put:
```js
module.exports = {
    index: {
        welcome: "Welcome to my site",
    },
};
```
And for **es.js** we would put:
```js
module.exports = {
    index: {
        welcome: "Bienvenido a mi sitio",
    },
};
```

_Note that all the locale files **must** have the same propeties, or it might cause an error._

---

## Coding the function
What this function does, is that, by getting the accept-language header from the user, and the supported language files, we can get the language file for the page requested.

Now that we have the files, we'll open the pages.js file, and follow the next steps:

First we'll import locale to the file.
```js
const locale = require("locale")
```
<br/>
Using locale, we'll create our list of locales, and we'll pass an array as a parameter, inside that array should be the language codes of the languages we'll be translating our app to, we did English and Spanish, so we'll add **en** and **es** to the array.
```js
const supportedLanguages = new locale.Locales(["en", "es"]);
```
<br/>
Then we need to import our locale files to our util, for this, we will make an object, and add them like this:
```js
const languages = {
    en: require("../locales/en"),
    es: require("../locales/es"),
};
```
This way we can get our locale files easily later on.
<br/>
Now we'll code the main function, it requires 2 parameters, **header** which is the user's language header, and **page** which is the name of the page we will try to get the language file from.
```js
function getLanguageFile(header, page) {
    // This creates a language list of the user's preferred languages
    const locales = new locale.Locales(header); 

    // This gets the best matching language, considering our supported languages, and the ones the user prefers
    // This will returns an object but we're only interested in the code propety of this object
    // So it will return a code like "en" or "es"
    const languageCode= locales.best(supportedLanguages).code;

    // Using the language code and the page parameter, we can navigate the locale files, and get the one we need
    const langFile = languages[languageCode][page];

    // And then return that locale file
    return langFile;
}
```
<br/>
So our full **pages.js** file will look like this:
```js
const locale = require("locale");

const supportedLanguages = new locale.Locales(["en", "es"]);
const languages = {
    en: require("../locales/en"),
    es: require("../locales/es"),
};

function getLanguageFile(header, page) {
    const locales = new locale.Locales(header);
    const langCode = locales.best(supportedLanguages).code;

    const langFile = languages[langCode][page];
    return langFile;
}

module.exports = { getLanguageFile };
```

---

## Using our function in our pages
Now that we have the function, we can use it on our page, to do this, we will go to to **pages/index.js** and write the following code:

```jsx
// Import our function to the page
import { getLanguageFile } from "../utils/pages"

// Generate the props for our page
export const getServerSideProps = (context) => {
    // Get the language header from our page context
    const languageHeader = context.req.headers["accept-language"]

    // Using that header, get our locale file
    // We pass "index" as argument because that's our page name, and that's what we added to our locale files
    const languageFile = getLanguageFile (languageHeader , "index")

    // Return the props to the page to render
    return {
        props: {
            lang: languageFile,
        },
    };
};

const Index = (props) => {
    return (
        <div>
            {/* Example of usage */}
            <h1>{props.lang.welcome}</h1>
        </div>
    );
};

export default Index;
```
<br/>
As you can see in the following image, They're both related.
![Relationship](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ucernoz80xbh57huuu1t.png)

---

## Adding more languages
To add more languages to your app, you just need to create the file with the language code in the locales folder, and add it to the supported languages array in our util.

---

Thanks for reading, I hope this guide is useful for you, you can ask any question in the comments.