How to add google adsense to nuxt.js

How to add google adsense to nuxt.js

I was trying to add Google Adsense to a Nuxt.js static site.
I didn't know where to copy and paste my AdSense script tag.
I realized we could add the Adsense script in the <head> tag the same way we add external resources to Nuxt.js with extra keys.

To install globally, add the following snippet to your nuxt.config.js file, replacing xxxx with your own Adsense account number.

// nuxt.config.js 
export default {
   head: {
    script: [{
        src: 'https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js',
        'data-ad-client': "ca-pub-xxxx",
        async: true
    }]
    }
  }
Add the snippet to your nuxt.config.js file for the script to carry across all pages

Or you can add it locally to your vue file.

// page.vue
<script>
export default {
  head () {
    return {
      script: [{
        src: 'https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js',
        'data-ad-client': "ca-pub-xxxx",
        async: true
      }]
    }
  }
}
</script>
Add the snippet to your component for only the corresponding page

Resources

How to use external resources?
How to use external resources with Nuxt.js?
Show Comments