Display Adsense Ads Inside Posts On GatsbyJS Blog

To generate maximum revenue from your gatsby blog, start displaying ads inside blog posts.

I have been using Adsense to display Ads on my blogs for a really long time now. Over this time I have realized that ads which are displayed inside blog posts give higher revenue than any other ad placement. So, in this post we will looking into how you can display Adsense Ads inside posts on GatsbyJS blog.

The reason why Ads inside Posts give higher revenue is that they blend perfectly with your blog content. Imagine writing a blog article about iPhone 13 and showing an iPhone 13 ad just after a paragraph. People tend to click on such ads more and hence more revenue.

How to add Adsense ads inside blog posts on Gatsby

  1. Edit your post’s markdown files and add the below provided HTML comment to your blog posts at places where you want to show the Adsense Ads.
Blog paragraph 1


Blog paragraph 2
  1. Now, edit the blog-post template component and replace the section where we are dangerously setting inner html with the code below.
// Replace this code
  dangerouslySetInnerHTML={{ __html: post?.html || "" }}
// With this code
  getAllArticleSections(post?.html || "", post?.id || "")
// Also create this function in the component
const getAllArticleSections = (articleHTML: string, articleId: string) => {
  const sections = articleHTML.split("<!--ADSENSE_AD-->")
  return sections.map((articleSectionHTML: string, idx: number) => {
    return (
          dangerouslySetInnerHTML={{ __html: articleSectionHTML || "" }}
        // This is done so that last element is not followed by Ad
        {idx !== sections.length - 1 && <InPostAd />}

As you can see in the code above, we are splitting the HTML based on the comment and rendering each section with ad after that.

  1. Create InPostAd component. This component will hold the Adsense ad code. This this file replace XXXXXXXXXXXXXXX with your publisher id.
import React from "react"

const InPostAd = () => {
  const scriptString = `<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-XXXXXXXXXXXXXXX"
<!-- ladWhoCodes-In-Article -->
<ins class="adsbygoogle"
  (adsbygoogle = window.adsbygoogle || []).push({});

  return (
      dangerouslySetInnerHTML={{ __html: scriptString }}

export default InPostAd

Once everything is stitched together publish your code and wait for 5-10 minutes before ads start showing up. So, this is all you have to do to show Adsense ads inside blog posts on Gatsby. Do let us know if you face any issue.