How to Add Custom JavaScript to a Gatsby Site

February 05, 2018

I recently found myself needing to add some custom JavaScript to the head of a Gatsby project. In this article I’ll show you exactly to do this.

Gatsby doesn’t actually use an index.html or similar file. Instead, it uses an html.js file, which isn’t exposed by default.

Following their docs, we can expose html.js by doing the following:

cp .cache/default-html.js src/html.js

This copies html.js to our src folder so we can edit it.

Now let’s add our custom JavaScript. Below is a contrived example, but in a future article I’ll show a very practical use for this technique.

// example.js
    var foo = 'bar';

Since our HTML doc is a JavaScript file, we can’t just copy and paste the above example, otherwise React will complain about a syntax error.

The trick is to use React’s dangerouslySetInnerHTML attribute. As its awesome name suggests, you’re going to set the inner HTML of whatever tag you apply it to. Let’s see it in action!

// html.js
        __html: `
            var foo = 'bar';

Now if you refresh your app, you should see bar logged to the console.

I admit, this is more work than I care for to just add something to the head of a page, but as with all tech, there are tradeoffs we must make. Gatsby makes so many other things easy, I’m willing to give this annoyance a pass.

Hi, I'm Steven Mercatante.
I build awesome things for the web using Python, JavaScript and Elixir.
Contact me if you'd like to work together.