GatsbyJS - Add Google AdSense

Make use of GatsbyJS SSR APIs to integrate Google Adsense

Edson Frainlar
Edson FrainlarJanuary 05, 2020 · 2 min read · Last Updated:

One of the major strengths of Gatsby is its evolving plugins catalog. And there are a couple of plugins found for Google AdSense integration but don’t seem to be maintained for so long. But peeking into the source code of the one pave the path to do the same without any plugins.

All you have to do is, update your gatsby-ssr.js with the below code (if there is no gatsby-ssr.js file on your project directory then create one at the root).

1import React from "react";
3export const onRenderBody = ({ setHeadComponents, setPostBodyComponents }) => {
4 const pluginOptions = {
5 googleAdClientId: `ca-pub-XXXXXXXXXXXXXX`, //TODO: Replace with your client-Id
6 head: true, // Set to false if you prefer to have your adsense script loaded at the end of body instead of head.
7 };
9 if (process.env.NODE_ENV !== `production`) {
10 return null;
11 }
12 if (pluginOptions.googleAdClientId === undefined) {
13 return null;
14 }
15 const setComponents = pluginOptions.head
16 ? setHeadComponents
17 : setPostBodyComponents;
18 return setComponents([
19 <script
20 async
21 type="text/javascript"
22 src=""
23 />,
24 <script
25 key={`gatsby-plugin-google-adsense`}
26 dangerouslySetInnerHTML={{
27 __html: `
28 (adsbygoogle = window.adsbygoogle || []).push({
29 google_ad_client: "${pluginOptions.googleAdClientId}",
30 enable_page_level_ads: true
31 });
32 `,
33 }}
34 />,
35 ]);

onRenderBody is a Gatsby SSR API, called after every page Gatsby server renders while building HTML so you can set head and body components to be rendered in your html.js.

👉 SSR APIs | GatsbyJS

Build the project (gatsby build) and see whether the AdSense snippet is present in the build output HTML.

You can also refer the same used in my repo itself.

This page is open source. Noticed a typo? Or something unclear?
Improve this page on GitHub

Edson Frainlar

Written byEdson Frainlar
Mission-driven Full-stack Developer with a passion for developing KTern, Dev Collaboration, and teaching. Curious to explore Quantum Information and Computing.

Is this page helpful?

Related ArticlesView All

Related VideosView All

GatsbyJS & Analytics: How to Add Google Analytics 4.0 To a Gatsby Site Using Gtag