How to Build a Multi-Language Application with NuxtJS

20 mins read
Nuxtjs i18n and product localization with Crowdin

It’s increasingly common for businesses and organizations to have their applications support multiple languages. Building multi-language applications can be a challenging task. Luckily, there are tools and frameworks available that can make the process easier and more efficient.

One such tool is NuxtJS, a powerful and popular JavaScript framework. Use it to build multi-language applications with its built-in nuxt i18n module. Even better, NuxtJS offers a range of features and benefits that make it well-suited for building multi-language applications, including server-side rendering, code-splitting, and automatic code generation.

This article will explore building multi-language applications with NuxtJS using the nuxt i18n module. We will cover the benefits of using NuxtJS and the nuxt i18n module for this purpose and the key considerations and steps involved. Specifically, we will cover the following topics:

  • Benefits of using NuxtJS and the nuxt i18n module for building multi-language applications
  • How to set up a NuxtJS project for multi-language support using the nuxt i18n module
  • Implementing language detection and switching using the nuxt i18n module
  • Internationalizing and localizing content using the nuxt i18n module
  • Deploying and testing a multi-language NuxtJS application using the nuxt i18n module

Benefits of Using NuxtJS Library and NuxtJS i18n Module

The NuxtJS library and nuxt i18n module offer several advantages that can speed up an application’s development process. These include:

  • Automatic code-splitting: Nuxt.js automatically splits your code into small chunks that you can load on demand, which speeds up an application’s load time.

  • Server-side rendering: Nuxt.js pre-renders the pages of your application on the server. Overall, this improves your application’s performance and SEO.

  • Routing: A major perk of using Nuxt.js is that it provides a powerful and flexible routing system, which makes it easy to build enterprise-level applications.

  • Modules: Nuxt.js has a rich library of modules that add functionality to your application, such as axios for making HTTP requests or @nuxtjs/pwa for integrating a Progressive Web App (PWA) to your application.

Setting Up Your NuxtJS Project

To set up a NuxtJS project for building multi-language applications, you will need to install the dependencies and configure your project for internationalization.

Access the project’s source code on GitHub to provide a practical demonstration.

Installing Dependencies

Here is a step-by-step guide for setting up a simple NuxtJS project and configuring it for multi-language support using the nuxt i18n module:

  1. Install NuxtJS: To install NuxtJS, you will need to have Node.js and npm (the Node.js package manager) installed on your system. Once you have these prerequisites, you can install the NuxtJS CLI (Command-Line Interface) by running the following command:

    Using npm

    npm install -g @nuxt/cli
    

    Using yarn

    yarn global add @nuxt/cli
    
  2. Next, create a new NuxtJS project. You can use the NuxtJS CLI (Command-Line Interface) by running the following command:

    npx create-nuxt-app <project-name>
    

    This creates a new NuxtJS project in the current directory and prompts you to answer a few questions about your project, such as the project name, the package manager to use, and the project type. (See sample details below for a test project)

    Nuxt JS i18n

  3. Install the nuxt i18n module: You need to add multi-language support to your NuxtJS project and install the nuxt i18n module. You can run the following command:

    npm install --save @nuxtjs/i18n
    
  4. Finally, configure the nuxt i18n module in your NuxtJS project. You can add the following configuration to your nuxt.config.js file:

    module.exports = {
      modules: ['@nuxtjs/i18n'],
      i18n: {
        locales: [
          // Add locale options here
        ],
        defaultLocale: 'en',
        vueI18n: {
          fallbackLocale: 'en'
        },
        detectBrowserLanguage: {
          useCookie: true
        }
      }
    }
    

Internationalization: Configuring your NuxtJS Project and the i18n NuxtJS Module

Before getting into internalization, it’s imperative to understand the basic structure of a NuxtJS application first. It comprises several directories and files that are organized hierarchically. These include:

  • package.json: This file contains information about your NuxtJS project, such as the project name, version, dependencies, and scripts.

  • nuxt.config.js: Contains configuration options for your NuxtJS application, such as the build target, modules, plugins, and server options.

  • pages/: This directory contains the Vue.js components that make up your NuxtJS application. Remember, each file in this directory represents a route in your application. The file name and directory structure determine the URL of the route.

  • components/: Contains reusable Vue.js components you can use in multiple pages or layouts in your NuxtJS application.

  • layouts/: Contains layout components that define the overall structure and layout of your NuxtJS application.

  • store/: This directory contains Vuex store modules. These modules manage the state of your NuxtJS application.

Configuring your NuxtJS project for internationalization is easy. For starters, you’ll need to install the nuxt i18n module and add the configurations to your nuxt.config.js file. The configuration options include the languages to support, default language, language detection technique, switching strategies, and localization options.

For instance, to configure your NuxtJS project for multi-language support with English as the default language and German and Arabic as the additional languages, use the below configuration:

module.exports = {
  modules: ['@nuxtjs/i18n'],
  i18n: {
    defaultLocale: 'en',
    locales: ['en',  'dr',  'ar'],
    detectBrowserLanguage: {
      useCookie: true,
      cookieKey: 'i18n_redirected'
    },
    vueI18n: {
      fallbackLocale: 'en'
    }
  }
}

This configuration will enable multi-language support in your NuxtJS project and set English as the default language. It also enables language detection and switching using the cookie strategy and sets the fallback locale to English.

[Free E-book]Localize your content with Crowdin

Learn how to set up a continuous localization workflow to grow with multiple languages faster than with one. Experience and tips from 10+ localization experts.

Defining Your Translation Strings in NuxtJS i18n

Localization software, like Crowdin, will provide a graphical user interface (GUI) that makes it easy to manage and edit your translation strings. Localization software also has features that help you automate the sync of source texts and translations between your repo and localization tool, where translators and content editors work. It also offers features like translation memory, terminology management, QA checks, context, OTA, and more.

To work with a translation management tool, you need to extract the strings from your NuxtJS application and create a translation file for each language you want to support. Please note the translation file typically has a .po extension and is organized as a list of translation entries, each containing the original string (called the “msgid”) and the translated string (called the “msgstr”).

For instance, let’s define a translation string for the “Hello, World!” message in English and French using Poedit. To achieve this, create a translation file with the following content:

msgid  "Hello, World!"  
msgstr "Bonjour, le monde!"

Adding translated content to your NuxtJS application is easy using the nuxt i18n module. For starters, you’ll need to import the translation files and make them accessible in your application. You can achieve this by clearly showing the location of the translation files in the nuxt.config.js file. See the example below.

module.exports = {
  modules: ['@nuxtjs/i18n'],
  i18n: {
    defaultLocale: 'en',
    locales: [
      {
        code: 'en',
        file: 'en.json'
      },
      {
        code: 'fr',
        file: 'fr.json'
      }
    ]
  }
}

This configuration will load the English and French translation files and make them available to your NuxtJS application. You can then access the translation strings using the $t function in your Vue.js components, as shown below:

<template>
  <div>
    { $t('Hello, World!') }
  </div>
</template>

This will render the translated string “Bonjour, le monde!” in the French version of your NuxtJS application and “Hello, World!” in the English version.

How to Render Translated Text using the NuxtJS i18n Module

With the i18n module, you can translate content in your applications’ templates and components.

From a design perspective, the i18n module comes with two built-in functions; $t and $tc. Both functions perform diverse roles. While the former allows you access to translation strings, the latter is more robust and gives you access to translation strings with context.

We can use the $t function in templates and components. Pass the $t function as a key to the translation string you want to access. For instance, here’s an example: we access a translation string for the key “Jane Doe’’.

<template>
  <div>
    <!-- Use the $t function to render a translated string -->
    <h1>{ $t('Jane Doe') }</h1>
  </div>
</template>

<script>
  export default {
    // Inject the i18n property into the component's context
    i18n: {
      inject: true
    }
  }
</script>

How to Customize Translations with Placeholders and Interpolation

You can use placeholders and interpolation to customize translations in your application. This is possible using the $t function and the tpl option (you pass it on to an object containing the placeholder values). With placeholders, you can include variables in your translation strings. This way, interpolation steps in and enables you to substitute the values of the variables at runtime.

For example, the code below shows how to use a placeholder in a translation string:

<template>
  <p>{ $t('greeting', { name: 'John' }) }</p>
</template>

<script>
  export default {
    data() {
      return {
        name: 'John'
      }
    }
  }
</script>

<i18n>
  {
    "en": {
      "greeting": "Hello, {name}!"
    },
    "fr": {
      "greeting": "Bonjour, {name}!"
    }
  }
</i18n>

In our code above, we use {name} as a generic placeholder in the translation string for the “greeting” key. Next, we use the $t() function to translate the string. Please note you need to pass the name property from the component data as the second argument; this replaces the {name} placeholder in the translated string.

Language Switching using NuxtJS and nuxt i18n Module

With NuxtJS, you can add language-switching functionality to your application.

We do this by enabling language detection in the nuxt.config.js file. This generates a trigger effect that allows end-users to select their preferred language on your application.

To achieve this, tweak the {detectBrowserLanguage} option in the nuxt.config.js file. This way, you can specify how a browser detects a specific language. This is possible thanks to an embedded cookie in the browser or a query parameter.

Going back to our source code on GitHub, let’s implement this in the code below:

module.exports = {
  modules: ['@nuxtjs/i18n'],
  i18n: {
    defaultLocale: 'en',
    locales: ['en',  'fr',  'es'],
    detectBrowserLanguage: {
      useCookie: true,
      cookieKey: 'i18n_redirected'
    },
    vueI18n: {
      fallbackLocale: 'en'
    }
  }
}

This configuration will enable language detection using the browser language. If the browser doesn’t support the language, it uses the cookie to redirect a user to the specific language version of the application.

Remember, you need to provide a way for the user to select the language. To achieve this, use the switchLocalePath option in the nuxt.config.js file. This option allows you to specify the URL pattern for language switching, using placeholders for the language code and the current route.

Let’s look at how you can enable language switching using the query parameter lang.

module.exports = {
  modules: ['@nuxtjs/i18n'],
  i18n: {
    defaultLocale: 'en',
    locales: ['en', 'fr', 'es'],
    switchLocalePath: '/:lang/:route',
    vueI18n: {
      fallbackLocale: 'en'
    }
  }
}

Handling Language Detection and Storing the Selected Language

Sometimes, you may want to store the selected language in a cookie or local storage.

For this, use the setLocaleCookie and getLocaleCookie options in the nuxt.config.js file. These options allow you to specify the name of the cookie or local storage key to store the selected language.

module.exports = {
  modules: ['@nuxtjs/i18n'],
  i18n: {
    defaultLocale: 'en',
    locales: ['en', 'fr', 'es'],
    switchLocalePath: '/:lang/:route',
    setLocaleCookie: true,
    getLocaleCookie: 'i18n_loc'
  }
}

Advanced Topics on NuxtJs and the NuxtJS i18n Module

While some of these topics are advanced, I recommend learning them to build on your knowledge about building multi-language applications with NuxtJS.

Handling Pluralization in Translations

NuxtJS provides a $tc function that allows you to access translation strings with context and pluralization rules. This is useful when the same string can have different translations depending on the count of an item, such as “1 item” versus “2 items”.

Formatting Dates and Numbers for Different Languages

NuxtJS provides a $d function that allows you to format dates and a $n function that enables you to format numbers according to the language and region settings of the user. Use these functions in your templates and components to format dates and numbers in a localized way.

Translations for Dynamic Content

If you want to check if a translation string exists for a given key, NuxtJS provides the $te function. It’s useful when rendering dynamic content that isn’t translated into all languages.

Wrapping Up on NuxtJS i18n

We have covered how to build multi-language applications with NuxtJS. As a JavaScript library, NuxtJS provides a powerful and flexible way to develop easy-to-use applications for users with varied language backgrounds. We also saw how the nuxt i18n module enables multi-language detection, including features such as switching, pluralization, dates and numbers formatting, and translations for dynamic content.

This was just the tip of the iceberg, as many possibilities and developments exist within the NuxtJS ecosystem. I encourage you to explore more resources:

Automate localization with Crowdin

Integrate Crowdin with your git repo to receive translations as merge requests.
Kelvin Mburu