HomeContact
Gatsby
Gatsby Learning Tips
August 17, 2021
2 min

##Gatsby implementation and learning tips

  1. Adding Customize Adsense Ad to Gatsby site.
  2. Adding ads.txt from Adsense to my site.
  3. Turning my website into a progressive web app.
  4. Updating Gatsby Site content without refresh or hard refresh in Browser

Adding Customize Adsense Ad to Gatsby site.

I have tried multiple times, trying to add custom adsense AD into my site and markdown Blog post, it works in develop but when I deploy to Netlify, I had this error.

 WebpackError: Invariant Violation: Minified React error #62; visit https://reactjs.org/docs/error-decoder.html?invariant=62&args[]= for the full message or use the non-minified dev environment for full errors and additional helpful warnings.

Previous Method…

The process of adding AD Sense Javascript file is very straight forward in Netlify, I can just go to Netlify and then go

settings -> build & deploy -> post processing -> snippet injection -> add snippet

to add the Adsense JS snippet.

However the problem is to add customize AD in the blogpost or desired location in the website.

The previous method I used is to use inline element along with gatsby adsense plugin

npm install --save gatsby-plugin-google-adsense
  <div>
  <ins className="adsense"
  data-ad-client=""
  data-ad-slot=""
  data-ad-format=""></ins>
  </div>

and adding this into component

if(type of window != "undefined){
    (window.adsbygoogle = window.adsbygoogle || []).push({});
}

But When the site deploy to Netlify, it will error out!!!

I have spent days and try to debug this problem and cannot fix it!!!

The current method I used now…

install these 2 packages
npm install --save react-adsense rehype-react

Create an ADSense component.

import React from 'react';
import AdSense from 'react-adsense';

const AdSenseComponent = () => (
  <AdSense.Google
    client='ca-pub-xxxx
    slot='xxxx'
  />
);

export default AdSenseComponent;

You can get your client and slot id from your AdSense account

"Account > Settings > Account Information" (ad ID = slot).

For Anywhere in the website, you can just Import AdSenseComponent in include it in the code.

However for Markdown Post, more steps will be needed.

In the markdown blog template, we will need to import rehype-react and the new AdSense component created above. create a const variable for rehype-react

import rehypeReact from 'rehype-react'
import AdSenseComponent from '../components/AdSenseComponent';

const renderAst = new rehypeReact({
  createElement: React.createElement,
  components: {
    'adsenseblog': AdSenseComponent,
  },
}).Compiler;

And we need to add “htmlAst” in GraphQL Query in the blog template

query($pathSlug: String!) {
    markdownRemark(frontmatter: { path: { eq: $pathSlug } }) {
      html
      frontmatter {
        title
        date(formatString: "MMMM DD, YYYY")
        path
        tags
        description
      }
      htmlAst
    }
  }

In the template Instead of using

<div dangerouslySetInnerHTML={{ __html: html }} />

I replace it with

<div>{renderAst(htmlAst)}</div>

Then in any of the blog post I can just add

Gatsby is very cool
<adsenseblog></adsenseblog>

to make the AD appear in the post.

If you find my tips are useful, please support my work :)


Adding ads.txt from Adsense to my site.

One day I got this warning from Google Adsense.

To prevent severe impact on revenue, download an ads.txt file then upload the file to the root level domain of each site:

It may take a few days for changes to update. If you’re using another ad network, remember to add the network to the ads.txt file. See the ads.txt guide for more details.

There is no plugin for adding file to the root folder. Simplily just download the file and copy it to the project ‘static’ folder. Once its push to netlify, the file can be access in root.


Turning my website into a progressive web app

Turning my website into a progressive web app is very straight forward since I built my website with Gatsby, I only have to install two Gatsby plugin with minor modification.

  1. Install Gatsby offline plugin
npm install --save gatsby-plugin-offline

gatsby-config.js

{
  plugins: [
    {
      resolve: `gatsby-plugin-manifest`,
      options: {
        ...
      }
    },
    'gatsby-plugin-offline'
  ]
}
  1. Create a web manifest file using gatsby-plugin-manifest

to install plugin

npm i gatsby-plugin-manifest

configure gatsby-config.js

    {
      resolve: `gatsby-plugin-manifest`,
      options: {
        name: `GatsbyJS`,
        short_name: `GatsbyJS`,
        start_url: `/`,
        background_color: `#f7f0eb`,
        theme_color: `#a2466c`,
        display: `standalone`,
        icon: `src/images/logo.png`, // This path is relative to the root of the site.
      },
    },

using Google lighthouse audit, the score has jump from 31 to 69 by installing and configuring 2 Gatsby plugin.

Note: In order to measure the PWA score properly and PWA to work properly in Chrome, make sure you head to Chomre -> Inspect -> Application -> Clear Storage where you can clear out the cached values and “unregister” service workers.

If you find my tips are useful, please support my work :)

Updating Gatsby Site content without refresh or hard refresh in Browser.

My Site is built with Gatsby and Netlify and everytime when I try to update my blog content and rebuild the site, new changes would not show unless I did a refresh or hard refresh in the browser.

To solve this I have to make the site HTML files never be cached by the browser by adding this to the Document Head

<meta http-equiv="Cache-Control" content="public, max-age=0, must-revalidate" />

This should solve the problem.

If you find my tips are useful, please support my work :)


Tags

#Gatsby

Related Posts

Common Gatsby Shopify Error Encounter During Development
August 25, 2021
1 min
© 2023, All Rights Reserved.

Quick Links

Advertise with usAbout UsContact Us