Source remote images the right way with Gatsby v4  🖼 📥

Gatsby v4 has been out for a while, and with v4 came a much stricter approach to creating and modifying nodes.

However there seems to be quite a bit of outdated documentation, as I experienced when looking into createResolvers.

An examples shows creating remote file nodes as part of a custom resolver. It worked for me locally but failed on Gatsby Cloud, and I found out it is no longer supported.

There are also examples using the ___NODE Convention for linking nodes that will be deprecated in v5.

In Gatsby Version 4:

Combined, we get the following recommended way of sourcing remote images:

exports.onCreateNode = async (gatsbyUtils) => {
  const { node, actions, reporter, createNodeId, getCache } = gatsbyUtils;
  const { createNodeField, createNode } = actions;

  if (node.internal.type === `YouTube`) {
    const imageFile = await createRemoteFileNode({
      // The url of the remote file
      url: node.oEmbed.thumbnail_url,
      parentNodeId: node.id,
      getCache,
      createNode,
      createNodeId,
    });

    createNodeField({
      node,
      name: `thumbnailFileId`,
      value: imageFile.id,
    });

    reporter.info(`Created YouTube File Node for ${node.youTubeId} thumbnail`);
  }
};

exports.createSchemaCustomization = ({ actions }) => {
  actions.createTypes(`
    type YouTube implements Node {
      thumbnail: File @link(from: "fields.thumbnailFileId")
    }
  `);
};

Example lifted from @raae/gatsby-source-youtube-oembed.

 
All the best,
Queen Raae

Stuck on a reef in the sharky waters around the Gatsby islands?

Book a 1-on-1 Gatsby Call with Queen Raae. Friendly advice you can put into action immediately, guaranteed!

Serious about Gatsby? Sign up for emails sent every weekday to help you get the most out of Gatsby!