It's been a little while now that I've had this avagasafari.com website which I built using GatsbyJS. I'm a pretty big fan of GatsbyJS because of its supportive community, and resources. I have worked with NextJS, Wordpress, MEAN/MERN stacks, and other stuff in the past, but Gatsby just has that good vibes feel for me.

For no particular reason today, I felt like adding some ads to the website. Given the current state of the internet and the saturated market for bloggers, I don't feel like the ads will actually generate much revenue, if any, even with a decent amount of traffic. When I started building websites a long time ago, I still remember when it was extremely easy to get on to Google AdSense. Nowadays, there are so many different milestones that need to be passed in order to be approved so instead of going with AdSense, I decided to give Media.net a try.

While this post will specifically focus on implementing Media.net adds on to a GatsbyJS website, the same approach can be taken for other third-party scripts (e.g. Sovrn, AdSense, and more).

My little preface

Before I continue any further, I would like to emphasize that I've been doing everything for fun. I am by no means an expert and I would like to take no part of responsibility in anyone's frustrations. With that being said, I'll get straight to the nitty gritty and try to keep things short and simple. I've created this guide mostly as a result of my own search for a simplified approach to adding third-party scripts to my own Gatsby website while also keeping a record of what I did that may or may not be useful to others.

One other thing to note is that if you're using something like Netlify, I believe that the snippet can just be injected there with the post processes to decrease bloating on the Gatsby build - just something to consider for Netlify users. Another thing to keep in mind is that things can also be implemented via Gatsby's html.js, but I won't go into details on that as it has been documented elsewhere.

Register for Media.net

This little part only applies to anyone who would actually like to use Media.net as their choice of ad network. I definitely wouldn't classify them as a get-rich-quick platform, but they are a pretty good alternative to Google AdSense. To get started, simply visit Media.net and click "Sign Up" to open an account. After a few simple steps, the website will ask you to implement two snippets of code that will get reviewed to see if one's website qualifies for ads within a few days. One snippet is supposed to get injected in the head of your website while the other is supposed to be added to the body. With standard HTML, this would be relatively easy, but using Gatsby requires a few additional steps.

First step - edit the Gatsby SSR file

At the root of your Gatsby folder, there should be a Gatsby SSR file. If this file does not exist, simply create a new file and name it gatsby-ssr.js. In the file, insert the following code:

const React = require("react")

exports.onRenderBody = function ({ setHeadComponents, setPreBodyComponents }) {
  setHeadComponents([
    <script
      dangerouslySetInnerHTML={{
        __html: `
            window._mNHandle = window._mNHandle || {};
            window._mNHandle.queue = window._mNHandle.queue || [];
            medianet_versionId = "XXXXXXX";
            `,
      }}
    />,
    <script
      src="https://contextual.media.net/dmedianet.js?cid=XXXXXXXXX"
      async="async"
    />,
  ])

  setPreBodyComponents([
    // <div
    //   style={{
    //     maxWidth: '1400px',
    //     margin: '0 auto'
    //   }}
    //   id="XXXXXXXXX"
    // >
    <script
      dangerouslySetInnerHTML={{
        __html: `
                  try {
                      window._mNHandle.queue.push(function (){
                          window._mNDetails.loadTag("XXXXXXXXX", "300x250", "XXXXXXXXX");
                      });
                  }
                  catch (error) {}
                  `,
      }}
    />,
    // </div>
  ])
}

The XXXXXXXXX will need to get replaced with your own account details, and the 300x250 will need to match the size of the ad unit you have chosen after opening your Media.net account. Note that there is a div within the setPreBodyComponents. I intentionally left that there as an optional feature as it can be used to edit the style of the ad unit if one so desires. I find the margin setting useful for billboard ads that need to be centered.

Step two - edit the blog post page

In my case, my blog post page is found within a template folder that is within a source folder, and my blog post file is named blog-post.js. The name and location of your blog post file may differ from mine based on how your Gatsby site folder is organized. Once this file is found, some code will need to be added if it hasn't been added already.

At the top of the file, make sure useEffect is available.

import { useEffect } from "react"

Next, use useEffect to activate the ad in the section just before returning the actual blog post content while replacing the XXXXXXXX with your own account details.

// My post starts like this, but yours may differ
const Post = ({ data, pageContext }) => {
// ...

  // ACTIVATES AD
  useEffect(() => {
    const loadAd = () => {
      window._mNDetails.loadTag("XXXXXXXX", "300x250", "XXXXXXXX")
    }
    if (window._mNDetails && window._mNDetails.loadTag) {
      loadAd()
    } else {
      window._mNHandle.queue.push(loadAd)
    }
  }, [])

// ...

// the useEffect is inserted just before the return of my blog post content
return (
// ...

Step three - add the ad unit where it should show up

The final step is the easiest. Within the return statement as shown from the previous step, simply insert the ad unit wherever it's expected to appear. In my case, I wanted the ad to show up just before Disqus.

        // this is where the ad unit will show up on the site
        <div id="XXXXXXXXX"></div>

        // I wanted the ad unit to show up just before my Disqus component
        <Disqus config={disqusConfig} />

Again, the XXXXXXXXX will need to be replaced with your own ad unit details, and then that's everything! Now, you can check your network calls to make sure everything is running successfully, and push the changes.

If you enjoyed my guide, you can show support by simply listening to my latest track below. It's back to music now for me!