Adding a <script> tag using Gatsby JS

I recently needed to add a script tag to my Gatsby install for https://actionsbook.com and couldn’t work out the correct way to do it.

There are various options available online, from using React Helmet (which I didn’t get working. I also didn’t want the script in the <head>), to a useScript hook (which worked sometimes).

The solution that worked for me was to use setPostBodyComponents in gatsby-ssr.js like so:

export const onRenderBody = ({ setPostBodyComponents }) => {
  setPostBodyComponents([
    <script
      key="https://example.com/my-file.js"
      src="https://example.com/my-file.js"
      defer
    />,
  ])
}

This works when running both gatsby develop and gatsby build


Published:
May 21, 2020

Category
Development
Topics
#gatsby