GatsbyJS v4 no longer allows directly modifying or mutating nodes in onCreateNode

Posted by Orville Bennett on 5 December 2021
Read time: about 2 minutes

Wooooo buddy! Did I have some debugging fun this weekend guys. Let's talk about Gatsby—the React framework for building single page web applications, not the literary novel.

I had occasion recently to start upgrading a project from Gatsby version 3 to version 4. The upgrade was going fine until I started querying Gatsby's GraphQl API for image nodes that it should have been creating 1. The way the project is set up, custom image nodes should have been getting created by a plugin based on the featured_images set for a post.

What was happening instead was that after an initial run of gatsby clean and gatsby develop commands the images would be present. On subsequent gatsby develop runs the images would not be there. Crap.

I had read the upgrade guide before starting and it sounded similar to something I saw in there, so I went back to check. There was a section mentioning that while directly modifying nodes would work, it was never an intended way to make these changes. Unfortunately, it did work and became a popular way to do these kind of changes. In version 4 this was no longer allowed though. Oops.

I decided it was time to go looking directly at the plugin I was using for how it was changing nodes. Sure enough it was directly modifying nodes in the onCreateNode() API method. This seemed like a great place to make some changes, so I did but ... that didn't fix things!

Fortunately I wasn't very far off. A bit more spelunking in Gatsby's discord channel (where they have a room specifically for v4 upgrades) and I found an issue that led me down the correct path. What I had missed was modifications to the the custom type that was created along with the node in the createSchemaCustomization() API method.

1

Sigh. This is an entire rabbit hole in and of itself. You see, Gatsby provides data on the backend via a GraphQL API.