Search code examples
htmlnuxt.jsfavicon

Nuxt change favicon by page


I have certain cases where certain routes need a different favicon. I've tried throwing this code in the head, and while this does work, it adds another favicon underneath the previous one, and does not overwrite it.

page.vue:

head () {
    return {
        title: 'my website title',
        link: [{
            rel: 'icon', type: 'image/x-icon', href: 'https://s.yimg.com/rz/l/favicon.ico'
        }]
    }
}
<link data-n-head="ssr" rel="icon" type="image/x-icon" href="/favicon.ico">
<link data-n-head="ssr" rel="icon" type="image/x-icon" href="https://s.yimg.com/rz/l/favicon.ico">

How do you go about overwriting a favicon?


Solution

  • Add a hid to the favicon in nuxt.config.js:

    link: [{
        hid: 'icon',
        rel: 'icon',
        type: 'image/x-icon',
        href: 'link-to-fallback-favicon.png'
    }]
    
    

    You can now overwrite it in the pages head method by using the same hid:

    head()
        return {
            link: [{
            hid: 'icon',
            rel: 'icon',
            type: 'image/x-icon',
            href: 'link-to-new-favicon.png'
    }]
    
    

    Nuxt will automatically overwrite once you navigate to that page, and use the general once from nuxt.config.js when you navigate away.