Nuxt: How to Load Translations from the BackEnd with an API

profile picture

Nuxt: How to Load Translations from the BackEnd with an API

In this quick tutorial we will see how we can use, in a Nuxt FrontEnd project, the translations that are store in a backend project.

In your nuxt project you will want to fetch the nuxt-i18n package:

yarn add nuxt-i18n

In nuxt.config.js add the following configuration

i18n: {
    locales: [
        {
            code: 'raw'
        },
        {
            code: 'de',
            file: 'de.js'
        },
        {
            code: 'fr',
            file: 'fr.js'
        },
        {
            code: 'nl',
            file: 'nl.js'
        }
    ],
    defaultLocale: 'fr',
    strategy: 'no_prefix',
    lazy: true,
    langDir: 'lang/'
},

Every language has its own file where we will execute an API call to our backend.

Let's create lang/fr.js and put this code inside:

export default async (context, locale) => {
    const axios = require('axios').default

    return await new Promise((resolve) => {
        axios.get(context.env.API_URL + '/translations')
            .then((response) => {
                resolve(response.data)
            })
    })
}

context.env.API_URL means that we have stored the backend URL in our .env file

That's it ! When you reload your project you will see the api call to your backend translations endpoint ๐Ÿ‘Œ

locale
api
nuxt
backend
translations

2020 My Dynamic Production SPRL All rights Reserved.