DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 970,177 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Anden Acitelli
Anden Acitelli

Posted on • Originally published at andenacitelli.com

Using AdSense Ad Units in Next.js

Overview

My blog is built from tailwind-nextjs-starter-blog, which you can find on GitHub here. It makes for a very quick start to a blog and is well architected.

Although it came directly with Google Analytics, it didn't provide any existing infrastructure for AdSense, so I figured I'd document my trials and tribulations getting it working.

What To Do

1. Get your site correctly linked to AdSense

Before you even get the code, you'll need to make sure your site is AdSense-ready. You may need to put a script into your header, or add a meta tag to your head - the site should walk you throguh it. You know you're set whenever the "Sites" menu in the AdSense dashboard shows your site as "Ready".

2. Overall AdSense Header

Go to "Ads" in the AdSense dashboard, then hit the "By ad unit" header. Create the one you like, then it'll provide you code. You need to copy the first script tag into your header, which looks something like this:

<script
  async
  src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-7827406820675555"
  crossorigin="anonymous"
></script>
Enter fullscreen mode Exit fullscreen mode

Note that crossorigin will likely need swapped to crossOrigin; my code editor has unfortunately decided to automatically format it back to all lowercase on save.

3. Individual Ad Units

Insert the following code wherever you need an ad unit:

<ins
  class="adsbygoogle"
  style="display:block; text-align:center;"
  data-ad-layout="in-article"
  data-ad-format="fluid"
  data-ad-client="ca-pub-ADSENSE_ID"
  data-ad-slot="SLOT_ID"
></ins>
<script>
  ;(adsbygoogle = window.adsbygoogle || []).push({})
</script>
Enter fullscreen mode Exit fullscreen mode

The script tag essentially signifies to AdSense that there's one more ad unit on the page. AdSense will give you values for all of these, it's mostly just copy-paste.

Common Issues

403: Forbidden

I ran into this error because I was on localhost. AdSense won't work on localhost, because it's not the same as the full site URL you need to add to your AdSense account as part of the update process. You shouldn't get this error on the actual live version of your site.

If you see push() missing an argument or similar, I believe it was also due to this.

Window Dimensions Not Working

Google AdSense switched to fully responsive ads at some point, so it will automatically resize to fit the width of the container. Make sure your container has more than 250px width and height.

Top comments (0)

"I made 10x faster JSON.stringify() functions, even type safe"

☝️ Must read for JS devs