• Web Development

How to configure AdSense for static websites with Netlify

March 05, 2022 • 1 min read

Netlify makes it easy to add scripts to your HTML pages

Static site generators, such as Gatsby, Hugo, Nuxt, and more make it really easy to develop web applications. However, it can be hard to use them to manage third party scripts such as those provided by Google Adsense or Google Analytics. Some of these static site generators don't offer an easy way to update the index.html file to add your scripts to the head or body of each page of your site. Furthermore, most of these scripts you don't want running locally while you develop. You only want them to be in the page if the site is running in production. Because of this, you may find yourself adding environment checks to control when the scripts should be included in the page.


Luckily, if you are using Netlify to deploy your site, like I do, these scripts become really easy to integrate and manage.

What Netlify Does


After a site is built, Netlify has certain post processing steps that it can run. One of these steps is Snippet Injection, which makes it possible for scripts to be inserted into the pages of your site when they are served. The snippets can be inserted before the closing head tag, or before the closing body tag. One of the scripts you can add is the Adsense script 🤑.

Configuring Adsense Script


Here are the steps to configure the script.

  1. Copy the Adsense code from your Adsense account.
  2. Go to the Nelify Dashboard for your account. You will have to create an account if you don't have one.
  3. Click on the site you want to update or add a new site if you don't have one.
  4. Click on Site Settings,
  5. Click on Build & deploy on the left menu on the page.
  6. Scroll down to the Post processing section and you should see Snippet injection
  7. Click on Add Snippet.
  8. For Adsense, you will need to have the script injected before the closing head tag. See the following image.

adsense snippet inection in netlify

Paste your script where is says HTML and click save.


Now whenever a page is loaded from your site, the script will be added before the closing head tag.

Conclusion

That is pretty much it. If you want to test it out, paste the following in an incognito browser search bar:


view-source:https://your-domain-name.com/


If you liked this post, don't forget to share it and subscribe to the newsletter.