Steven Mercatante

Steven Mercatante

Add Custom JavaScript to a Gatsby Site

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

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

Following their docs, we can expose html.js by invoking the following command in terminal:

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 for demonstration purposes.

// html.js
<script>var foo = 'bar'; console.log(foo);</script>

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 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 site, but as with all tech, there are tradeoffs we must make. Since Gatsby makes so many other things easy, we can overlook this minor invonvenience.