GatsbyJS - Add Google AdSense

Make use of GatsbyJS SSR APIs to integrate Google Adsense

commit 3374e70 · authored · 2 min read

GatsbyJS - Add Google AdSense

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).

import React from "react";
export const onRenderBody = ({ setHeadComponents, setPostBodyComponents }) => {
const pluginOptions = {
googleAdClientId: `ca-pub-XXXXXXXXXXXXXX`, //TODO: Replace with your client-Id
head: true, // Set to false if you prefer to have your adsense script loaded at the end of body instead of head.
};
if (process.env.NODE_ENV !== `production`) {
return null;
}
if (pluginOptions.googleAdClientId === undefined) {
return null;
}
const setComponents = pluginOptions.head
? setHeadComponents
: setPostBodyComponents;
return setComponents([
<script
async
type="text/javascript"
src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"
/>,
<script
key={`gatsby-plugin-google-adsense`}
dangerouslySetInnerHTML={{
__html: `
(adsbygoogle = window.adsbygoogle || []).push({
google_ad_client: "${pluginOptions.googleAdClientId}",
enable_page_level_ads: true
});
`,
}}
/>,
]);
};

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.

👉 abhith/abhith.net: Personal website running on Gatsby

local graph · open full graph

"GatsbyJS - Add Google AdSense" is connected to the topics Gatsby and related to 5 other entries. Best FREE Form Provider for Static Websites Best FREE Form Provider for… Azure DevOps - GatsbyJs Build Pipeline Azure DevOps - GatsbyJs Bui… Gatsby - See All Generated Pages Gatsby - See All Generated … Gatsby - Cookbook Gatsby - Cookbook Markdown - Link within document Markdown - Link within docu… Gatsby #gatsby GatsbyJS - Add Google AdSense

comments

loading discussion…