We’ve mentioned before that many web developers at Slicedbread like to utilize the Shopify Storefront API and GraphQL in order to access store data in fast and creative ways.
But today we’re going to touch on a particular nuance that a lot of developers may not be aware of: accessing metafields in your GraphQL queries.
As many probably know, metafields were given a facelift with Shopify’s Online Store 2.0 release and now they exist natively inside the Shopify admin area. It would seem logical, with this update, that you’d be able to access metafields in the same way that you access all other data points in the Storefront API, right? Wrong.
For reasons only known to Shopify, metafields are not accessible out of the box on the Storefront API. This is likely due to the additional server processing overheads that the process would require, but don’t worry. There’s a way to access them with a few additional steps:
By default. metafields are not “exposed” to the Storefront API. So in order to access your store’s metafields you first and foremost need to expose them.
There are a couple of ways to do this, but the easiest way is to use the GraphQL app provided by Shopify. You can find this at https://shopify-graphiql-app.shopifycloud.com/. (We use this tool because we need to execute a query on the Admin API.)
The query we need to run creates a MetafieldStorefrontVisibility record to tell Shopify to expose the specific metafield we want to work with. The query, or mutation, looks like this:
(In this example we are using a metafield to store a product’s color value. So the namespace used is product and the metafield key is color.)
Execute this query, ensuring that you select the Admin API (not Storefront) option in the GraphiQL app. If everything works correctly you will see a success response to confirm that the mutation has been applied.
Now we can access the metafield using GraphQL like this:
There we have it: metafields inside your Storefront API queries, in a nutshell. Completing this process can open up a lot of new possibilities, providing your clients with greater flexibility to configure their product data, and developers with the ability to read all client created metafields inside GraphQL queries.