Home » vue » Node.js, Vue.js, read 'HTTP: Accept-Language' set 'import' then serve the app

Node.js, Vue.js, read 'HTTP: Accept-Language' set 'import' then serve the app

Posted by: admin November 26, 2021 Leave a comment

Questions:

I’m setting a vue.js app with i18n, so I have multiple static translation files for different langues, and tow css files one ltr and the other rtl.

For now I’m setting ‘en’ as default lang and ltr as default css, serve them, then check the user locales and resend the right files with dynamic import, depending on the user preferred lang.

I’ve searched a lot, but can’t find a way to read the ‘HTTP: Accept-Language’ set the ‘import’ then serve the app with the right files from the beginning.

I know vue.js is a frontend framework but it’s served from a node.js server, so there must be a way.

Answers:

Not an expert here, but the only correct long-term solution I see is to do server-side rendering, although this requires some work.

As a short-term solution, you could also build all the different versions of your app and serve the correct one, but this is not a very scalable solution.

###

You can get the accepted language by getting the header on the nodejs part.

The desired header is req.headers["accept-language"].

Then you need to pass this information on the vue side. Depending on how you integrate vue there are different paths to be taken.

  • If you are using a template to include vue (pug for instance) you can pass the language as a template variable and include different css files depending on the desired language.
  • If you are including vue using imports then you can do something like this:
    • create a module that exports a variable for the language and set the variable to the value you get from the header
    • on the Vue side import the module and import css based on the value you just set

###

I know this is an old post but……

You can use :

navigator.language

I returns exactly what you want.

Besides that, you can use:

navigator.languages

It returns an array with all browser accepted langs. In my case:

[ "pt-BR", "pt", "en-US", "en" ]

A complete tutorial (using n18i and vuex) can be found here:

https://itnext.io/setting-language-with-i18n-by-os-language-in-vue-router-vuex-e42c9318c9ec

HTH