Adding custom JavaScript to the head section in Gatsby

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 }) => {
        __html: `
            var clicky_site_ids = clicky_site_ids || [];
    <script async type="text/javascript" src="//" />,

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