Search code examples
vuejs3meta-tags

Vue3 Router meta tags


I have been working on a Vue3 website and need the SEO to work well. I am not using Nuxt and I am set on Vue3 and cannot move back to Vue2. Need to find a way to put in dynamic meta data for my site. I did try installing meta3-vue, meta-vue, meta-3-vue, meta-vue@next, and about 5 other SEO meta generating libraries and all did not work. Each were either broken or they had some requirement that I could not fulfill.

How can I get meta tags to be dynamic in just the native router?


Solution

  • I ended up writing my own meta tag solution.

    index.js (router)

    const routes = [
      { 
        path: "/", 
        name: "Home", 
        component: Home,
        meta: {
          title: 'Title of my page',
          metaTags: [
           {
             name: 'description',
             content: "Nice description here"
           },
           {
            name: 'keywords',
            content: "all, of, my, keywords, here"
           }
          ]
        }
      },
      {
        path: "/privacy-policy",
        name: "PrivacyPolicyPage",
        component: PrivacyPolicyPage,
        meta: {
          title: 'Privacy Policy',
        }
      },
    ]
    
    router.beforeResolve((to, from) => {
        document.title = to.meta.title || "my default title"
        if(to.meta.hasOwnProperty('metaTags')) {
          for(let x=0; x < to.meta.metaTags.length; x++) {
            let oldMeta = document.getElementsByTagName('meta');
            for(let m=0; m < oldMeta.length; m++) {
              if(oldMeta[m].name == to.meta.metaTags[x].name) {
                oldMeta[m].remove()
              }
            }
            let meta = document.createElement('meta')
            if(to.meta.metaTags[x] && to.meta.metaTags[x].hasOwnProperty('name')) {
              meta.name = to.meta.metaTags[x].name
              meta.content = to.meta.metaTags[x].content
            }
            if(to.meta.metaTags[x].hasOwnProperty('property')) {
              meta.property = to.meta.metaTags[x].name
              meta.content = to.meta.metaTags[x].content
            }
            document.head.appendChild(meta)
          }
        }
        // next()
    })
    
    export default router;
    

    I built this in my router and it does solve my problem and allows me to manage all of my meta tags in just my native Vue router. I've been playing with it and checking robots and indexing and it seems to be working correctly.