Adding hreflang alternate links in head

lucpotage
76
lucpotage
commented a year ago

I'm trying to automatically add the hreflang links in the head but it's not that easy.

I moved the locales array outside of the module.exports and added the following code in thenuxt.config.js file and it kinda works:

const locales = [
  { code: 'en', ... },
  { code: 'fr', ... }
]

module.exports = {
  ...
  head: {
    link: [
      ...
    ].concat((function () {
      let alternates = []
      locales.forEach((locale) => {
        alternates.push({
          hid: `alternate-${locale.code}`,
          rel: 'alternate',
          hreflang: locale.code,
          href: `https://example.com/${locale.code}`
        })
      })
      return alternates
    })())
  }
}

However, I didn't find a way to dynamically change the href value. The method switchLocalePath() is not accessible from the nuxt.config.js file and it seems we can't access to this.$route.name too.

Any idea on how to do that? What about nuxt-i18n injecting theses alternate links by default since Nuxt is sold as SEO-friendly out of the box. It would be a great addition to the module.

Finally an unrelated question. Why nuxt-i18n is not a scoped package like the sitemap module for instance @nuxtjs/sitemap?

2
paulgv
3.1k
paulgv
commented a year ago

Hi @lucpotage
Just released v2.2.0 with alternate links generation, more here: https://github.com/nuxt-community/nuxt-i18n#seo
Hope you can give it a try to confirm it works as expected.
One thing I noted is that alternate tags disappear when you navigate in the app manually (they reappear if you refresh the page) but I guess it does not matter since Google bot accesses each page directly as far as I know.
Thanks for the suggestion!

0
matsrietdijk
5
matsrietdijk
commented a year ago

@paulgv the hreflang tags should not be added to pages which are in ignorePaths as they do not have alternatives. Currently they render as invalid html (validated with https://validator.w3.org) and looks like:

<link data-n-head="true" data-hid="alternate-hreflang-nl-NL" rel="alternate" href="" hreflang="nl-NL"/>
<link data-n-head="true" data-hid="alternate-hreflang-en-US" rel="alternate" href="" hreflang="en-US"/>

Note the empty href attribute.

0
paulgv
3.1k
paulgv
commented a year ago

Thanks @matsrietdijk ! It should be fixed in v2.3.0!

0
matsrietdijk
5
matsrietdijk
commented 2 months ago

@paulgv currently on v5.4.4 and again for ignored pages (by setting nuxtI18n: false on the component) these link tags are added. Now also causing vue-router warnings because <routename>___<code> does not exist.

0
Informations
Question โ€ข Resolved
#c4 - Created a year ago