How to inject certain context into all pages in Gatsby?

Viewed 2395

Using gatsby-node.js and createPages I can query something using graphql and create pages using that something as page context. So those pages can use that something as parameter in their queries.

The problem I'm facing is that I don't want to use createPages. I'm completely fine with pages that are created by default (from gatsby-plugin-page-creator), I just want all of them to have something from graphql as a context.

Basically I want a global context (which I get from gatsby graphql) to be available for all pages.

There is onCreatePage hook but unfortunately graphql is not available there according to https://github.com/gatsbyjs/gatsby/issues/3121#issuecomment-348781341.

1 Answers

What about this... you can try using the onCreateNode() hook instead inside your gatsby-nodejs file. E.g.:

const allMyPageNodes = [];

exports.onCreateNode = ({ node, actions, getNode }) => {
  const { createNodeField } = actions;
  if(...) { //whatever filtering you need to select JUST pages in your site
    const mySpecialContext = "blah"; //whatever your global context settings are
    createNodeField({ node, name: "myglobal", value: mySpecialContext });
    allMyPageNodes.push(node);
  }
}

```

Then in all graphql queries thereafter, for pages, the graphql payload should have edge.node.fields.myglobal populated and you should be able to do whatever you like with it. Also have a look at https://www.gatsbyjs.org/docs/static-query/ for querying directly from inside a component.

HTH.

Related