Posts Learn Categories Tags About
/
How to add Google Adsense for Nuxt Js Application cover

How to add Google Adsense for Nuxt Js Application

Learn how you can add Google Adsens to Nuxt Js to generate side income

5 months ago

10 mins read

12 views

In this post, you'll learn how to add / setup Google Adsense in Nuxt Js. There are 3 ways to implement this and we'll be starting with the simplest method.

1 - Using the Community Package
The first method is to use the community package nuxt-community/google-adsense-module and this will ensure the right configuration be placed in the application.
yarn add @nuxtjs/google-adsense

First, you just have to include it in the project, and secondly define the required configuration in nuxt.config.js file.
const config = {
  modules: [
    ['@nuxtjs/google-adsense']
  ],

 'google-adsense': {
    id: 'ca-pub-#########'
  }
}

export default config

2 - Override App.html Template
The 2nd method will override the default app template that Nuxt has by default. By default, every page will extend from this template and it's perfect to define global changes.
<!DOCTYPE html>
<html {{ HTML_ATTRS }}>
  <head {{ HEAD_ATTRS }}>
    {{ HEAD }}
    <script data-ad-client="ca-pub-#########" async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
  </head>
  <body {{ BODY_ATTRS }}>
    {{ APP }}
  </body>
</html>

3 - Update nuxt.config.js head configuration
The last method would be to update the head configuration of the nuxt.config.js file. It will look as follow.
const config = {
  head: {
    script: [
      {
        src: 'https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js',
        'data-ad-client': 'ca-pub-#########',
        async: true
      }
    ]
  }
}

export default config

Make sure to update "ca-pub-#########" with your Google Adsense id. Now run "yarn dev" and then inspect the page to see the head section. You will now see the Google Adsense code there.