Nuxt3 multilanguage : internationalization is easy

you might want to try the nuxt3 module i18n to internationlize your nuxt3 application. It is full of nice features like automatic language detection and redirection, domain name switching, automatic route generateion and custom paths. The is a very extensive set of features, and I have to admit I prefered to code my own light language switching alternative composable, in order to remain light. The code below will display language string depending on the domain name of your application, which can be hosted on a single multi domain base.

Two composables : one for domain testing, the other one for string rendering

domain testing composable

first I define a global function in a plugin. Remember that plugins in nuxt are automatically imported :

plugins/wave.js

export default defineNuxtPlugin((/* nuxtApp */) => {
    return {
        provide: {
         
            waveDomain:() => {return window.location.host},
            waveCheckDomain:(str) => {
                if(window.location.host.search(str)>-1) return true; else return false;
            },

        }
    }
})

composables/domains.ts

in this function i simply test domain name against extension. Could by any other string of choice

export function useIsDomainEs()
{
    const nuxtApp =  useNuxtApp()
      return true;
    if (nuxtApp.$waveCheckDomain(".es")  ) return true;
    return false;
}

String rendering composable

composables / lang.ts

import {useIsDomainEs} from "~/composables/domain";

export function t(str){
    if (useIsDomainEs()) return es(str)
    else return fr(str);
}

export function es(str) {
    switch( str){
        case "--t-hello":return "hola"
        default:return str;
    }

}
export function fr(str) {
    switch( str){
        case "--t-hello":return "Salut"
        default:return str;
    }

}

then in your components, simply use t("--t-hello")

Leave a Comment

Your email address will not be published. Required fields are marked *

To top