Logo
Published on
ยท6 min read

Connecting Google Adsense to Next.js Blog

I apologize in advance for any awkward expressions in English. ๐Ÿ™

English is not my native language, and I have relied on ChatGPT's assistance to proceed with the translation.

Overview

In this guide, we will walk you through the process of connecting Google Adsense to your blog.

Please note that this blog is created using the Tailwind CSS Blog Starter template.

Google Adsense

  1. Go to Google Adsense > Ads > Click Edit > Choose "Auto ads," then click the [Apply to site] button.
    (I prefer to use auto ads because manual ads may not apply to certain ad formats like overlays.)

  2. Go to Google Adsense > Ads > Click Get code.

Copy the <script> provided in the popup and paste it between the <head></head> tags on your website.

Adding to Blog Code

1. Add googleAdsenseId to the data/siteMetadata.js file

You can also place the code directly in the _document.js file without setting it here. I separated it to make it usable for other code as well.

const siteMetadata = {
  // ... omitted
  analytics: {
    // ... omitted
  },
  ads: {
    googleAdsenseId: 'ca-pub-xxxxxxxxxx',
  },
}

module.exports = siteMetadata

2. Modify the pages/_document.js file

Open the pages/_document.js file and add the following code between the <Head> tags.

I've added the isProduction variable to load the script only in the production environment.

Here's the code:

import siteMetadata from '@/data/siteMetadata' // add
class MyDocument extends Document {
  render() {
    const isProduction = process.env.NODE_ENV === 'production' // add

    return (
      <Html lang="en" className="scroll-smooth">
        <Head>
          {/* ... */}
          <link rel="alternate" type="application/rss+xml" href="/feed.xml" />
          {/* add [[ */}
          {isProduction && (
            <script
              async
              src={`https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=${siteMetadata.ads.googleAdsenseId}`}
              crossOrigin="anonymous"
            ></script>
          )}
          {/* add ]] */}
        </Head>
        <body className="bg-white text-black antialiased dark:bg-gray-900 dark:text-white">
          <Main />
          <NextScript />
        </body>
      </Html>
    )
  }
}

export default MyDocument

This concludes the setup.

If you want to verify the functionality locally, please refer to the instructions below.

3. Local Testing

Since the script is loaded only in the production environment, ads won't be visible locally.

First, temporarily set the isProduction variable to true and proceed.

Also, if the domain doesn't match, ads won't be visible, so modify your hosts file to make ads visible locally.

Open the C:\Windows\System32\drivers\etc\hosts file, add the following line, and save it.
(If you encounter permission issues while saving, run Notepad as an administrator, open the file, add the line below, and then save.)

127.0.0.1       local.youradsensedomain
# Example: 127.0.0.1       local.hlog.kr

Access http://local.youradsensedomain:3000 to check if the ads are displayed.

[Note 1] If you haven't configured auto ads or manually added ad unit codes, ads won't be visible.

[Note 2] If you encounter a Content Security Policy (CSP) error, check your next.config.js file and add AdSense-related domains as follows: (I've included the error domains seen in the developer tools in each respective location.)

const ContentSecurityPolicy = `
  default-src 'self';
  script-src 'self' 'unsafe-eval' 'unsafe-inline' giscus.app *.googletagmanager.com *.googlesyndication.com *.googleadservices.com *.google.com;
  style-src 'self' 'unsafe-inline' giscus.app;
  img-src * blob: data:;
  media-src 'none';
  connect-src *;
  font-src 'self';
  frame-src giscus.app googleads.g.doubleclick.net *.google.com *.googlesyndication.com
`
  • Alternatively, you can configure it not to use CSP as follows.
const securityHeaders = [
  // https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP
  {
    key: 'Content-Security-Policy',
    value: '', //ContentSecurityPolicy.replace(/\n/g, ''),
  },
]
  • Modifying the next.config.js file requires a server restart.

  • Once you have finished checking the ads, restore the isProduction variable to its original code.

  • The URLs to be added to the Content Security Policy may vary depending on changes in services such as Google AdSense and Google Analytics.

4. Adding Manual Ad Units

If you want to add manual ad units separately from automatic ads, follow these steps:

  1. In Google AdSense, go to Ads > "Ad units."

  2. Create the ad unit you want to use manually.

  3. Create a new component for applying this ad unit. For example, you can create a file named components/GAdsBanner.js and paste the following code into it:

import { useEffect } from 'react'
import siteMetadata from '@/data/siteMetadata'

const GAdsBanner = ({ slot }) => {
  const isProduction = process.env.NODE_ENV === 'production'

  useEffect(() => {
    if (!isProduction) return
    try {
      ;(window.adsbygoogle = window.adsbygoogle || []).push({})
    } catch (err) {
      console.log(err)
    }
  }, [])

  return (
    isProduction && (
      <ins
        className="adsbygoogle"
        style={{ display: 'block' }}
        data-ad-client={siteMetadata.ads.googleAdsenseId}
        data-ad-slot={slot}
        data-ad-format="auto"
        data-full-width-responsive="true"
      />
    )
  )
}

export default GAdsBanner
  1. Place the <GAdsBanner /> component in the desired location within your content to display the manual ad unit.

Code

The updated code can be found in the commit history.