Alk3my

Adding custom JavaScript to the head section in Gatsby

November 03, 2019

So I needed to add a small bit of JavaScript to the head section of this site. There seem to be different ways to tackle this, one was to make a copy of the html.js file that's normally in the .cache folder although I chose to make use of the gatsby-ssr.js file instead.

There are several APIs / hooks that allow you to perform certain actions. In this case I needed to add some tracking JavaScript (I went with clicky instead of google's analytics). So it's quite easy and makes use of the onRenderBody hook, the script looks like below.

const React = require(`react`);
exports.onRenderBody = (
    { setHeadComponents }
) => {
  setHeadComponents([
    <script
      dangerouslySetInnerHTML={{
        __html: `
            var clicky_site_ids = clicky_site_ids || [];
            clicky_site_ids.push(000000000);
          `,
      }}
    />,
    <script
      async
      type="text/javascript"
      src="//static.getclicky.com/js"
    />,
  ])
}

Reload the site and it should be there in the head section all going well.