Test Google AdSense on Localhost

November 09, 2021

programming
article cover

Problem

Add Google AdSense to Gatsby site

In the previous article, I wrote how to add Google AdSense to Gatsby site. But it’s a bit inconvenient that you can’t see and check Google Ads on localhost. I assume that is because it’s designed to show up only on a specific domain.

Solution

First, add property data-adtest="on" to ad component.

<ins 
  className="adsbygoogle"
  style={{ "display": "block" , textAlign: "center"  }}
  data-ad-client="<YOUR_GOOGLE_AD_CLIENT_ID>"
  data-ad-slot="<YOUR_GOOGLE_AD_SLOT>"
  data-ad-format="auto"
  data-adtest="on" // <- this one
  data-full-width-responsive="true"
/>

Next is making an alias by editing /etc/hosts. But before doing that let’s take a moment to look into /etc/hosts.

cat /etc/hosts

Probably you see there already is an alias for localhost.

127.0.0.1	localhost
255.255.255.255	broadcasthost
::1             localhost

This is why you can see the page when you usually access ‘localhost’.

So let’s add new alias here.

sudo nano /etc/hosts
or 
sudo vim /etc/hosts
127.0.0.1 dev.<YOUR DOMAIN>.com

At <YOUR DOMAIN>, you should put the same domain as the one you registered on Google AdSense.

Then now you can see ads on localhost!


Profile picture

Photographer / Web engineer working in Berlin.
A Japanese living with a Slovak wife and two German cats.