How to add Google Adsense to Next.js applications

How to add Google Adsense to Next.js applications

In this article I am going to explain, how you can implement Google Adsense in Next.js applications (or any other react applications). There are several approaches for implementing Adsense on a react site and I want to show you how you can add Adsense with privacy in mind.

As soon as you signed up for your site on Adsense and it has been approved, you have to place the Adsense code (or ad unit code) in your pages. This code in general looks like this and exists of three parts.

adsense-code.png

Add Google Adsense script

The first part will load the actual Adsense script. This script is typically placed between the <head></head> or <body></body>section.

We will not just place it there because we just want the script to be inserted after a user has given consent to allow third-party cookies and services. So I for example outsourced it in a separate function which will be triggered by accepting cookies.

export function enableGoogleAdsense () {
    const head = document.getElementsByTagName('head')[0]
    const scriptElement = document.createElement(`script`)
    scriptElement.type = `text/javascript`
    scriptElement.async
    scriptElement.src = `https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=${process.env.NEXT_PUBLIC_ADSENSE_ID}`
    scriptElement.crossOrigin = "anonymous"
    head.appendChild(scriptElement);
}

By clicking the 'Accept required and optional cookies' button on this site, this function will be triggered which will then place the adsense script into the <head></head> section.

If you want to use Auto ads you are actually already done as long as Auto Ads are enabled in your Adsense Account for your site.

Otherwise, if you want to place ad units individually you can do this now like the following.

Add ad units

I would recommend to create a separate component for ad units. This could look like the following:

import styled from 'styled-components';
import { useEffect } from 'react';

export function GoogleAdsenseContainer ( { client, slot }) {

  useEffect(() => {
    (window.adsbygoogle = window.adsbygoogle || []).push({});
  }, []);

  const AdLabel = styled.span`
    font-size: 12px;
  `

  return (
    <div 
      style={{textAlign: 'left',overflow: 'hidden'}}
    >
    <AdLabel>Advertisment</AdLabel>
      <ins
        className="adsbygoogle"
        style={{ display: "block" }}
        data-ad-client={client}
        data-ad-slot={slot}
        data-ad-format="auto"
        data-full-width-responsive="true"
      ></ins>

    </div>
  );     
}

In this component you will find the other to parts of the original Adsense script. So here the actual ad unit element is placed with a small ad-label. You can load this component in every page and position you like and place your individual client and slot ID. After the ad unit is placed window.adsbygoogle in the useEffect hook will fill this ad unit with the actual advertisement graphics.

With the useEffect hook ads will also be requested/refreshed when a user navigates to any other page without refreshing the page.

About The Author

Max Dietrich
Max Dietrich

Geospatial Developer

Currently i work as IT-Architect at Bayernwerk. Beside that I ride my mountain bike in the alps, code and design my website and publish new content on my website whenever i can.

0 Webmentions

Have you published a response to this? Send me a webmention by letting me know the URL.

Found no Webmentions yet. Be the first!

Newsletter

Continue Reading

  • How to create a custom cookie banner for your React application

    How I created and designed my cookie banner which hopefully will help you in creating your own for your Next.js or React application. Continue reading...
  • Fetching and storing activities from Garmin Connect with Strapi and visualizing them with NextJS

    Step-by-step guide explaining how to fetch data from Garmin Connect, store it in Strapi and visualize it with NextJS and React-Leaflet. Continue reading...
  • Syntax Highlighting with Prism.js and Next.js

    Prism.js is a compact, expandable syntax highlighter that was developed with modern web standards in mind. Continue reading...