When you just start creating projects in Nuxt, you may not yet know the features of the framework, in particular how to make Nuxt SEO-friendly?

In order for your project to be well optimized for search engines, you need the information on the site to appear in the process of server-side rendering (SSR), it means, all information that is important for search engines is immediately visible in the source code of the page.

One of the most important things in SEO is the title of the page and the meta description tag. You can set their default values in Nuxt as follows.

export default {
  head: {
    title: 'Category',
    meta: [
      {
        hid: 'description',
        name: 'description',
        content: 'My category page'
      }
    ],
  }
}

In Crome, you can view the source code of the page by pressing the Ctrl + U key combination. If you see your title and description tags in the code, then you did everything right.

title and description tags in the code

But what if you need to load information dynamically (for example, via API)? Then you can do as follows.

export default {
      head() {
          return {
              title: this.title,
              meta: [
                  {hid: 'description', name: 'description', content: this.description}
              ]
          }
      },
      data() {
          return {
              title: '',
              description: '',
          }
      },
      mounted() {
          this.$axios.get('/get_category_info/').then(response => {
              this.title = response.data.title;
              this.description = response.data.description;
          });
      },
  }

But assigning values inside mounted will cause the values in the tags to be assigned already on the client side (after the page had loaded). That is, in the browser tab, you will see your title tag, but if you look at the source code of the page, it will not be there.

To fix this and load title, description and, possibly, some content on the page dynamically – then use getting it inside asyncData, and not in mounted.

asyncData(context) {
    if (process.server) {
        return context.app.$axios.get('/get_category_info/').then(response => {
            return {
                title: response.data.title,
                description: response.data.description,
            }
        }).catch(error => {
            console.log(error);
        })
    }
},

Congratulations, your Nuxt project will now have much better SEO, and your title and description will appear in the source code of your page.

Share post
Twitter Facebook