DEV Community

Steven Mercatante
Steven Mercatante

Posted on • Edited on • Originally published at stevenmercatante.com

Add Custom JavaScript to a Gatsby Site


This post was originally published at stevemerc.com


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
<script
  dangerouslySetInnerHTML={{
    __html: `
      var foo = 'bar';
      console.log(foo);
    `,
  }}
/>

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.

šŸ‘‹ Enjoyed this post?

Join my newsletter and follow me on Twitter @mercatante for more content like this.

Top comments (2)

Collapse
 
itmayziii profile image
Tommy May III

Please try and avoid ejecting html.js unless you have to. The out of the box APIs could accomplish adding a script to the head
gatsbyjs.org/docs/ssr-apis/#onRend...

Collapse
 
mercatante profile image
Steven Mercatante

Hi Tommy, thanks for mentioning onRenderBody. You're right that it can be used to render custom scripts in the head, but I still think there's value in knowing how to manually tweak html.js for fine-grained control. I'll update this article to include an example using onRenderBody, though.