nuxt / vue-meta

Manage HTML metadata in Vue.js components with SSR support
https://vue-meta.nuxtjs.org
Other
4.08k stars 247 forks source link

Remove 'data-n-head' and 'data-hid' attributes in meta tags #776

Closed davinma closed 12 months ago

davinma commented 2 years ago

My website need to be authenticated to search engines for SEO, but they can't be authenticated, which caused by data-n-head and data-hid attributes in meta tags.

I have tried these hooks in nuxt.config.ts:

{
  // ...
  hooks: {
    generate: {
      page(page: { html: string }) {
        const cheerio = require('cheerio')
        const $ = cheerio.load(page.html, { decodeEntities: false })

        const attrs = [
          'data-n-head-ssr',
          'data-n-head',
          'data-hid',
          'data-vue-ssr-id',
          'data-server-rendered'
        ]

        attrs.forEach(value => {
          $('*[' + value + ']').removeAttr(value)
        })

        page.html = $.html()
      }
    }
  }
  // ...
}

or this:

{
  // ...
  hooks: {
    'render:route': (_url: URL, result: { html: string }) => {
      result.html = result.html
        .replace(/ data-n-head=".*?"/gi, '')
        .replace(/ data-hid=".*?"/gi, '')
    }
  }
  // ...
}

But twice meta tags are generated, the first is Okay, but the second is repeat, data-n-head and data-hid attributes still in meta tags. I'm so confused!

ShahabDadKhan commented 12 months ago

I am facing the same issue and looking for a solution. Have you solved this issue?

davinma commented 12 months ago

I am facing the same issue and looking for a solution. Have you solved this issue?

You can try about this in nuxt.config.ts:

import * as cheerio from 'cheerio'

{
  // ...
  hooks: {
    generate: {
      page: (page: { html: string }) => {
        const $ = cheerio.load(page.html, { decodeEntities: false })
        page.html = $.html().replace(/ data-n-head="(.*?)"/gm, '')
      }
    }
  }
  // ...
}

The 2nd code in my issue 'render:route' is wrong, it should be like this:

hooks: {
  render: {
-    'render:route': (_url: URL, result: { html: string }) => {
+    route: (_url: string, result: { html: string }) => {
      // your code here
    }
  }
}

Also, it's useless. According to the documentation, render:route means:

Every time a route is server-rendered. Called before sending back the request to the browser.

And now, I've upgrade to the latest Nuxt 3.0, without 'data-n' question, really awesome!