Adding a script tag using Gatsby JS
21 May 2020 in TIL
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:
js
export const onRenderBody = ({ setPostBodyComponents }) => {setPostBodyComponents([<scriptkey="https://example.com/my-file.js"src="https://example.com/my-file.js"defer/>,]);};
This works when running both gatsby develop
and gatsby build