Implementing Google Ads Code in NextJS for Automated Units

I'm currently working on a NextJS project and I need to integrate the Google AdSense code for automatic ads.

The Google ad code I have is:

<script
  async
  src={`https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=${process.env.NEXT_PUBLIC_GOOGLE_ADSENSE}`}
  crossOrigin="anonymous"
/>

There isn't a specific ad unit code provided. The ads will be automatically generated by Google based on this script.

My concern is how to implement this in my NextJS project so that the ads continue to function even when the route changes.

Currently, I've noticed that if I include this in the _document.js head, the ads only load on full reload. Most tutorials cover implementing Google AdSense in NextJS with specific ad units, not with automatic ads like in this case.

I would greatly appreciate any guidance on this matter.

Answer №1

For integrating Adsense for automatic ads on a Nextjs website, the recommended approach is to insert the script tag in either _app.tsx or _app.jsx.

When utilizing <script></script>, it's advisable to leverage Nextjs' built-in tag for better optimization. Below is a sample implementation of automatic ads:

// Import Script tag
import Script from 'next/script'; 

// Implementation 
<Script
  id="Absence-banner"
  async
  strategy="afterInteractive"
  onError={(e) => {
    console.error('Script failed to load', e);
  }}
  src={`https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=${process.env.NEXT_PUBLIC_GOOGLE_ADSENSE}`}
  crossOrigin="anonymous"
/>

UPDATE 12/8/23: With the recent changes in Nextjs, if you are using the appDir, some aspects of this method may not function as expected.

To integrate Adsense into your app, you will need to include it in the base layout.tsx or layout.jsx file.

You will still employ the script tag, but it should be added to the HTML within the standard <head></head> section of the document.

import React from 'react';
import Script from 'next/script'; 

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html lang="en">
        <head> 
            <Script
                id="Absence-banner"
                async
                strategy="afterInteractive"
                onError={(e) => {
                    console.error('Script failed to load', e);
                }}
                src={`https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=${process.env.NEXT_PUBLIC_GOOGLE_ADSENSE}`}
                crossOrigin="anonymous"
            />
        </head>
      <body>
        {children}
      </body>
    </html>
  );
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for implementing try-catch with multiple promises without utilizing Promise.all methodology

I am looking to implement something similar to the following: let promise1 = getPromise1(); let promise2 = getPromise2(); let promise3 = getPromise3(); // additional code ... result1 = await promise1; // handle result1 in a specific way result2 = await ...

Loading your NextJS page with a full-page loader

I am looking to create a full-page loader for my NextJS app, similar to this example: https://jsfiddle.net/yaz9x42g/8/. The idea is that once the content is loaded, it should be revealed in a visually appealing way. I want to build a reusable component tha ...

Persist user input even after reloading the page

In order to enhance the user experience, I would like to implement a feature where the data entered by the user is preserved even if they refresh, reload, or close the page. This includes retaining the selections made in the select elements. Additionally, ...

Tips for modifying JSON property names during the parsing process

As outlined in the JSON.parse documentation, a reviver function can be utilized to modify the value of each property within the JSON data. Here is an example: JSON.parse('{"FirstNum": 1, "SecondNum": 2, "ThirdNum": 3}', function(k, v) { return ...

Ways to populate dynamic choices for multiple Select boxes within an ng-repeat loop

When I click the "Add Row" button on an Html form, dynamic rows are added. Each row contains a 'Country' select and a 'State' select. The issue I am facing is that when I select a country in one row, all other row values change as well. ...

Get a subsection of the array starting from index N up to the final

Is there a way to accomplish this specific transformation? ["a","b","c","d","e"] // => ["c", "d", "e"] I initially thought that using the slice method could work, however.. ["a","b","c","d","e"].slice(2,-1) // [ 'c', 'd' ] ["a","b ...

Is it wise to question the validity of req.body in express.js?

https://expressjs.com/en/4x/api.html mentions It is crucial to validate all properties and values in the req.body object as they are derived from user input. Any operation performed on this object should be validated to prevent security risks. For instan ...

What methods can be used to accomplish this effect using CSS and/or Javascript?

Is there a way to achieve the desired effect using just a single line of text and CSS, instead of multiple heading tags and a CSS class like shown in the image below? Current Code : <h2 class="heading">Hi guys, How can i achieve this effect using j ...

Run a function upon clicking a button in JavaScript

Could someone please help me figure out what I am doing incorrectly in the code below? I am attempting to trigger a function when a button is clicked. The HTML: <button id="btn1">Press me!</button> <input type="button" id="btn2" value="Pr ...

Angular does not recognize the function element.sortable

I'm attempting to utilize ui.sortable in order to create a sortable list. Despite following the instructions provided at https://github.com/angular-ui/ui-sortable, I am still encountering an issue and receiving the following error message: TypeError: ...

The attribute interface overload in Typescript is an important concept to

Consider a scenario where there are multiple payload options available: interface IOne { type: 'One', payload: { name: string, age: number } } interface ITwo { type: 'Two', payload: string } declare type TBoth = IOne ...

Searching for a jQuery plugin that can dynamically rearrange tables while automatically updating their corresponding IDs

Is there a way in jQuery to dynamically move tables around on a webpage? Currently, I have implemented a button that clones a hidden table when needed and another button to delete unwanted tables. Now, I am looking to incorporate a feature that allows the ...

Looking to preserve the "ALL" selection in a JavaScript-CSS filter?

On the front page, there are approximately 16 posts displayed along with a filter featuring 4 drop-down menus showcasing post categories. I have assigned category names as classes to each post div and am currently using javascript to hide them. The code s ...

Could someone please assist me with an issue I am experiencing with an AJAX GET request?

My code is not fetching any data for me. Below is the code snippet: <script type="text/javascript"> function matriculaFn(mat) { $.ajax({ method: 'GET', url:'My url API, async: true, crossDomain: false, contentType: 'application/j ...

Is your script tag not functioning properly with Promises?

Below is the code snippet used to dynamically append scripts in the DOM using promises. This piece of code is executed within an iframe for A-frame technology and it is generated using Google Blockly (Block-based coding). export const appendScript = asy ...

Retrieving data from a script within a React component

How can I access a variable from a script inside a React component? I am performing device detection on Node and sending the resulting object to the client (React) within index.ejs. <script type="text/javascript">window.deviceType = <%- deviceT ...

Using JavaScript's setInterval function in conjunction with Math.random to obtain a random value

Just generated some random numbers. Wondering how to dynamically update the values of these numbers every 5 seconds with fluctuations less than +/- 5% compared to the current value. Need help using the setInterval function. Here is my code for Random Pric ...

The crossIcon on the MUI alert form won't let me close it

I am facing an issue with my snackBar and alert components from MUI. I am trying to close the alert using a function or by clicking on the crossIcon, but it's not working as expected. I have used code examples from MUI, but still can't figure out ...

Various colored backgrounds in a random arrangement on a grid post layout

I'm looking to implement this plugin for displaying blog posts, but instead of using an image as the background, my client wants different colored images. I have managed to figure out the code to achieve this based on a post I found here, but unfortun ...

Implementing Object.somefunction() in ngFor with Angular

In my Angular project, I am using an ngFor loop to iterate over keys generated by Object.keys() in the following code snippet: <ul id='nav-tablist' class='tabrows'> <li *ngFor="let tab of obj.keys(tabList)"> ...