site icon

Hi, I’m Chris

I am a web developer teaching
regular people how to code

~ Welcome to my blog ~

NUXT.js: How to include the lang attribute to the html tag

By default, you may find your NUXT application does not have the language attribute set in the opening HTML element.

This was first brought to my attention by using lighthouse, the result was my accessibility score was reduced because this "lang" attribute was missing.

To add this in NUXT, we need to dive into the nuxt.config.js file, where we can manage all of our head data. If your project was set up using create-nuxt-app, you will have something like this:

export default {
  mode: 'universal',
  head: {
    title: process.env.npm_package_name || '',
    meta: [
      { charset: 'utf-8' },
      { name: 'viewport', content: 'width=device-width, initial-scale=1' },
      { hid: 'description', name: 'description', content: process.env.npm_package_description || '' }
    ],
    link: [
      { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }
    ],
  },

  ......

}

In the head property we can set up our sites meta data just as we do in regular HTML.

To add the language attribute to our HTML tag, we need to add a property to our head called htmlAttrs:

export default {
  mode: 'universal',
  head: {
    title: process.env.npm_package_name || '',
    // add this to your head:
    htmlAttrs: {
      lang: 'en'
    },
    ......

}

My language is English (en), but you can find other country codes here:

HTML Country codes

Now if you view source in the browser, you will have the lang attribute included!

This head metadata is managed by a plugin called vue-meta, and is included in NUXT by default. It can also be installed for regular Vue.js apps, and you can check out the docs for more options and info.

Also, if you are interested in adding data into the head section of a component, rather that for the whole site, you can also do this too by adding a function to the component, here is an example:

export default {
  head() {
    return {
      // set page title
      title: 'Page title',
      // add a script
      script: [{ src: "/script.js" }]
    };
  }
};

This will apply to only the component rather than the whole site, which is useful for including scripts and changing meta data for individual pages.


- By Chris Dixon

Chris Dixon is a web developer and teacher. Teaching thousands of students mainly in Vue.js React.js, WordPress and web development.