gatsby ssr - add script to header before other plugins

Viewed 3312

I am using Gatsby and need to head a script in the header BEFORE other plugin.

If I add it via gatsby-ssr.js

exports.onRenderBody = ({ setHeadComponents }) => setHeadComponents([#MY-SCRIPT#]);

it's being added last.

How can I add it BEFORE other plugins?

2 Answers

In addition to onRenderBody, use onPreRenderHTML to reorder your scripts.

exports.onRenderBody = ({ setHeadComponents }) =>
  setHeadComponents([
    <script key='myscript' src='...' />
  ]);

exports.onPreRenderHTML = ({ getHeadComponents, replaceHeadComponents }) => {
  const headComponents = getHeadComponents()

  // reorder your array with the sort method, by putting your item at top
  const orderedComponents = headComponents.sort((item) => (item.key === 'your-key' ? -1 : 1));  const orderedComponents = reorder(headComponents)
  replaceHeadComponents(orderedComponents)
}

For more info, see the Gatsby docs on SSR API.

2022 update

Since the release of the Script Gatsby component (powered by Partytown) it's much easier adding third-party scripts. Just:

import React from "react"
import { Script } from "gatsby"

function YourPage() {
  return <Script src="https://my-example-script" />
}

export default YourPage

Why you use gatsby-ssr.js file if you can use <Helmet> tag, maybe it fits you. You just need to use it like this in any component:

import React from "react"
import Helmet from "react-helmet"

import Layout from "../components/layout"
import SEO from "../components/seo"

const IndexPage= () => (
    <Layout>
      <SEO title="Index page" />
      <Helmet>
        <script src="https://whatever.com" type="text/javascript"/>
        <script src="https://whatever2.com" type="text/javascript"/>
      </Helmet>
    </Layout>
)

export default IndexPage

The snippet above will load your scripts inside <head> tag on the same order you've placed it.

If you need some kind of ordering and async approach, you can use gatsby-ssr, across onRenderBody and onPreRenderHTML.

Related