Shopify

What does the Shopify connection provide?

Looking to connect Gadget and Shopify?

Follow our tutorials and learn how to connect Gadget and Shopify in just a few minutes!

  • All models in Shopify's REST API have their schemas mirrored as models in Gadget. These models can be extended in Gadget with additional fields to store extra information, though these fields will not sync back with Shopify.
  • Each Shopify model syncs data from Shopify using webhooks and a daily background sync, as per Shopify's recommended best practices. You can also manually sync your app to Shopify at any time or trigger syncs with the Sync API.
  • Gadget sets up an already-authenticated API client package for making calls to Shopify. See Accessing the Shopify API
  • Gadget has easy-to-use facilities for billing your merchants

Currently, Gadget uses Shopify's 2022-01 API version for new connections.

Setting up the Shopify Connection

If you are looking to connect Gadget with Shopify follow the Connecting to Shopify tutorial.

Where is Shopify data saved

All of the Shopify fields are mapped to a corresponding field in your Gadget model, and then these Gadget model records are updated when Shopify sends webhooks. You can identify these fields by looking at the schema for any of your app's Shopify models and finding any field with the Shopify icon.

A view of the schema editor for the Shopify product model

When a record in Shopify is changed, Shopify sends a webhook to your Gadget application, which triggers the appropriate model action. A model's create webhook will fire the create model action, update will fire update, and delete will fire delete. All of the incoming fields from the webhook are mapped and stored in their corresponding field in Gadget.

Syncs work much like webhooks, in that they will create or update records in Gadget. However, Gadget currently does not delete any models that exist in Gadget but no longer exist in Shopify.

Gadget does not automatically sync data changed within Gadget back to Shopify. If you want to make changes to Shopify, you should make API calls to Shopify from within your Gadget Actions. See Accessing the Shopify API for more details.

Delete handling

Any deletion webhooks will call the delete action on the model, along with running the delete action for all Shopify records associated with that model. For example, when a product is deleted, we delete all of its options, images, and variants. All other webhooks will call either the create or update action, based on whether or not the record currently exists in Gadget.

Modeling

Once set up, all of the models based on your selected scopes are now part of your app's GraphQL API, and you can query them like any other model in your app. You can change Shopify fields however you please, except for their type.

You can also add your own fields to these models. If you want to store extra data about each record from Shopify, Gadget will happily support adding a new field to the Shopify model with any of Gadget's supported field types, including relationships, File fields, and Computed fields.

Fields added to Shopify models can also be marked as metafields for syncing from Shopify.

Shopify model actions

You can change the change, add, and remove Actions on Shopify connected models. Extending the existing actions allows you to react to changes within Shopify, and adding your own actions allows you to define your own business logic which can manipulate your own data or Shopify's in the context of one Shopify record.

For example, you can react to a Shopify product being created by adding a new Run Code effect to the create action on the Shopify Product model:

shopifyProduct/upcase/upcase.js
JavaScript
module.exports = async ({ record, logger }) => {
logger.info({ record }, "shopify product was just created");
};

Gadget will run the create action for this model any time a product/create webhook arrives from Shopify, or if a new Product record is discovered during a sync.

You can also add an action to the Shopify Product model that runs your own business logic. For example, you could add an action to update the product's title to be all uppercase. You would add an action called upcase, and add one Run Code effect to it with the following code: This action would be available to run on any Shopify Product record in your app.

shopifyProduct/upcase/upcase.js
JavaScript
1module.exports = async ({ record, connections }) => {
2 if (record.changed("title")) {
3 const shopify = connections.shopify.current;
4 await shopify.product.update(record.id, { title: record.title.toUpperCase() });
5 }
6};

Removing the defaults

You can also remove the existing create, update, or delete actions from your models, but this will prevent the connection from being able to perform those actions in response to webhooks/syncs. For example, if you remove the delete action from the Shopify Product model, your Gadget database will no longer remove products when Shopify sends webhooks, preserving a long-term record of all products ever seen.

Gadget doesn't prevent you from deleting models, but doing so may prevent data from being updated. For example, if you have a product and product variant model, deleting the product model will mean that you no longer get updates to variant models. Deleting the product variant model is fine, and will not prevent products from being synced.

Key Shopify Models

In addition to the models available to you based on your selected scopes, the Shopify connection creates three additional models: Shopify Shop, Shopify Sync, and Shopify GDPR Request.

Shopify Shop

The Shopify Shop model is a representation of a Shopify shop connected to Gadget via the Shopify connection. It stores information about the connected shop, and a record is created when a shop is connected for the first time. You can create code effects on the creation of a Shopify Shop record that will then execute your logic on app installation.

Shopify Sync

The Shopify Sync model represents the data sync between Shopify and Gadget for any given connected Shopify shop. Like the Shopify Shop model, you can create code effects on the creation of a sync record, which will execute whenever a sync is initiated between Shopify and Gadget.

Shopify GDPR Request

The Shopify GDPR Request model represents requests from Shopify's mandatory webhooks in compliance with General Data Protection Regulation (GDPR). You can add custom code effects to the Shopify GDPR Request model's create action to handle the request as needed, ensuring your app is GDPR compliant. To enable GDPR webhook requests from Shopify, go to the Apps page on the Shopify Partner Dashboard, select your application, click App setup, and paste https://app.gadget.dev/connections/webhooks/shopify/<your-app-id> in the GDPR mandatory webhooks section.

Adding Code Effects

Shopify models can be given business logic just like any other model in Gadget using Model Actions. Most often, developers add Run Code effects to the Success Effect list for the create, update, or delete Actions on a Shopify model. These effects can make calls to other APIs, create or change data in the Gadget app, or make calls back to Shopify. Within effects, you have access to the current record that is being manipulated, the incoming params from the webhook, the api object for fetching or changing other data in your app, and the connections object for making API calls back to Shopify.

Note: Gadget's automatic data sync replicates changes made in Shopify to your Gadget app, but not the other way around. If you want to update Shopify data, you must make explicit API calls to the Shopify API to do so.

Let's say we wanted to build an automatic product tagger for Shopify products. When a product is changed in Shopify, our Gadget app should parse the product body, extract some new tags, and send them back to Shopify so customers can search for the product on the storefront easily. To do this, we can add a new Run Code effect to the Shopify Product model's update action that does this in code:

shopifyProduct/update/apply-tags.js
JavaScript
1const { extractKeywords } = require("easy-keywords");
2
3module.exports = async ({ api, record, params, logger, connections }) => {
4 if (record.changed("body")) {
5 const newTags = (await extractKeywords(record.body)).slice(20);
6 const allowedTags = (await api.allowedTag.findMany()).map(
7 (record) => record.tag
8 );
9 logger.info({ newTags }, "saving new tags");
10 const shopify = await connections.shopify.forShopDomain(
11 "some-great-shop.myshopify.com"
12 );
13 await shopify.product.update(record.id, { tags: newTags.join(", ") });
14 }
15};

The above code extracts tags from the product's body field using a module from npm, gets an authenticated API client for working with a specific Shopify shop's API, and then updates the product by making an API call back to Shopify using that client.

Accessing the Shopify API

Looking to connect Gadget and Shopify?

Follow our tutorials and learn how to connect Gadget and Shopify in just a few minutes!

Gadget provides a helper for quickly accessing a client API object for communicating with Shopify. Gadget uses the shopify-api-node library as it is battle-tested, has good coverage of the Shopify API, and has support for automatic retries to avoid the Shopify API rate limits.

To access a Shopify API client, use the connections.shopify object in your code effect. connections.shopify is a helper object with some handy functions for accessing already-created API Client objects:

  • connections.shopify.current returns a Shopify API client for the current shop if there is one in context. For Public Shopify apps making requests from an embedded app, Gadget is able to track the shop making the request and populate this value.
  • connections.shopify.forShopId allows creating a Shopify client instance for a specific shop ID
  • connections.shopify.forShopDomain allows creating a Shopify client instance for a specific myshopify domain.

More info on the connections.shopify helper object can be found in the Code Reference for your application.

For example, we can use connections.shopify to access a Shopify client for a given store, and then make a call to the Products REST API in Shopify to create a new product record:

JavaScript
1module.exports = async ({ connections }) => {
2 const shopifyClient = await connections.shopify.forShopDomain(
3 "the-store.myshopify.com"
4 );
5 await shopifyClient.product.create({
6 title: "New Product",
7 body_html: "This is the latest product on The Store",
8 tags: ["product", "new"],
9 });
10};

If you'd prefer to use another client, the options attribute of the provided client has all the necessary details to construct one:

JavaScript
1import MyShopifyClient from "my-shopify-client";
2
3module.exports = async ({ connections }) => {
4 const shopifyClient = await connections.shopify.forShopDomain(
5 "the-store.myshopify.com"
6 );
7 const myClient = new MyShopifyClient({
8 myshopifyDomain: shopifyClient.options.shopName,
9 accessToken: shopifyClient.options.accessToken,
10 });
11 // ...
12};

When to make API calls to Shopify in Code Effects

For reading data within your effects, API calls can be placed anywhere without issue. That said, reaching out to Shopify can be expensive and can exhaust your Shopify API rate limit, so it is generally preferable to read data from your Gadget database instead of right from Shopify. Your Gadget database is a performant, nearby copy of the Shopify data expressly designed to power your business logic and works well for this, but if you need the most up-to-date data possible, making an API call to Shopify works too.

For writing data within your effects, API calls should generally be placed within Success Effects. Success effects run after the run effects have all been completed without errors, which gives more confidence that your business logic has worked and saved changes to the database. This makes it quite a bit less likely that your system and the external system will get out of sync. Gadget, by default, will execute the run effects of your app's actions inside a database transaction. When the run effects fail for these actions, Gadget undoes (rolls back) any changes made to your app's database during the action. Gadget cannot roll back changes made to external systems, so if you have made API calls within a failing run effect list, the side effects of those API calls will remain. Care should be taken to make API calls to external systems in the right place.

Managing Shopify API rate limits

Shopify has restrictive rate limits, limiting apps to making 2 requests per second to any given shop. To avoid errors from hitting this rate limit, Gadget recommends two strategies:

  1. Use the shopify-api-node object returned by Gadget's connections.shopify helper, which is preconfigured to retry when encountering rate limit errors. shopify-api-node will retry a request up to 12 times, respecting Shopify's Retry-After header. If you need to make a write request to Shopify or a read of the most up-to-date data possible, this is the best option.
  2. Read data from your Gadget database where possible. Gadget's Shopify Connection syncs data from Shopify to your Gadget database so you can read quickly and without rate limits.

Read more about Shopify's rate limits here: https://shopify.dev/api/usage/rate-limits

Current shop tenancy in Code Effects

As the front-end is making queries and performing mutations on the data in your Gadget application, it is important to make sure that cross-talk between different shops is not allowed. This is especially relevant for public Shopify apps.

The context of the current shop is determined by the user and session making the request, or, if the Effect is triggered by a webhook or sync, the current record that is being processed.

You can use connections.shopify.current to gain access to the current shop's information. It is preferred to use connections.shopify.current in Code Effects to prevent any cross-talk between shops. You can then use the shopify-api-node API off of the current shop to interact with the current Shopify store.

shopifyProduct/update/update-product.js
JavaScript
1module.exports = async ({ api, record, params, logger, connections }) => {
2 if (connections.shopify.current) {
3 await connections.shopify.current.product.update(record.id, {
4 tags: "foo, bar, baz",
5 });
6 }
7};

It can also be useful to understand how filtered model permissions work in Gadget as they determine what default filters, such as shopId in the case of a public app, are applied to GraphQL queries and mutations made through your application's API.

Webhook infinite loop handling

It is common for Gadget code effects running in response to a webhook to make calls to Shopify which then trigger the same webhook a second time. In the example above, we're processing an update action on a product record, and within it, we update the same product record again using the Shopify API. This triggers a second product/update webhook, which will dispatch the same Gadget action and run the effects again. Without care, this can cause infinite webhook loops, which chews through your Shopify API rate limit and Gadget resources.

To avoid webhook infinite loops, you must ensure that your code doesn't re-process the changes it makes and re-trigger webhooks forever. The best strategy for detecting this is to only trigger your business logic if the fields you care about have changed on the record, instead of always doing it when any field changes. The record object in the effect parameters is a GadgetRecord object which reports which fields have been changed by the incoming webhook payload, and which have not.

In the example above, we only need to extract new tags for the product when the product's body field has changed. If anything else changes, we don't need to change the tags, as they purely come from the body, so we wrap our business logic in a check for if (record.changed("body")). This way, when we make the API call to update the product's tags in Shopify, Gadget will receive this webhook and dispatch the update action, but our code won't run twice, as record.changed('body') will be false, as we only updated the record's tags.

More details on the GadgetRecord changes API can be found here.

Shop installs

You can click Shop Installs to view the shops that have installed your application. This page also allows you to manually Sync data per store or view Sync History.

A view of the Installs page with two successfully installed stores

You can click the Sync button to sync a single store. Expanding the options for a single store allows you to view the Sync History or to Register Webhooks.

'View Sync History' and 'Register Webhooks' drop down options for a single store on the Installs page

You can also perform operations on multiple stores at once by selecting multiple stores and then clicking Sync or Register Webhooks buttons.

Displays available bulk operations on the on the Installs page, 'Sync' and 'Register Webhooks'

The Installs page also lets you know if you are missing access scopes on your store or if you are missing topics/namespaces for your registered webhooks.

To fix missing access scopes, the merchant who installed the application needs to grant access to the scope in the Shopify dashboard.

Warning message on a store missing 2 scopes and a pop over detailing the missing scopes

Selecting Register Webhooks from the store options button or clicking Register Webhooks with multiple stores selected should fix missing webhook topics in most cases. If you are editing a connection that includes new models you need to grant additional scopes before the new webhooks can be registered. The Register Webhooks button will also not handle missing checkouts_create and checkouts_update webhooks at this time.

Warning message on a store missing multiple webhook topics and a pop over listing the topics

There are two ways to associate a Shopify store with a custom app: 1. Through a merchant install link , or 2. via the "Test on development store" link in the application view on your Partners Dashboard. Both of these will start Shopify's installation flow , where the user has to authorize your app to be able to access its data. Once authorized, your connection is now associated with that store. You should see the shop's name and domain on the connections index page, and the sync button should now be available so that you can get the shop's data into Gadget. You can repeat the above process if you need to connect to another store, which you would typically do to allow installation on both a development store and the associated merchant store.

Editing Shopify connections

You can also edit your connections using the Edit button on the Connections page. This allows for changes to be made to the Shopify scopes and models that your application can access and import.

The section where a user updates Shopify scopes and models

Adding new scopes

If you have a custom application built through the Partners dashboard or Shopify CLI and edit your connection to require additional scopes, you will need to re-authenticate your app for all stores on which it is installed. To do this, you can go through the app installation process again. This involves re-installing your app on development stores in the Partners dashboard.

If you are building an embedded application using React, and use the Gadget Provider from our @gadgetinc/react-shopify-app-bridge package, reauthentication will be handled for you.

If you have an application built through a store admin, you must ensure that the scopes selected in the admin match the scopes required by your Gadget connection. If they are out of sync, navigate to the Shop Installs page. From there you can click the Sync button to the right of the store you are trying to sync. You may also need to reregister your webhooks.

The refresh scopes menu option of a Shopify admin connection

Adding new models without new scopes

You might edit your connection to only add new models, not new scopes. In this case, you do not need to reauthenticate or reinstall, but you may need to register new webhooks for your newly selected models. You can check to see if you need to register webhooks on the Installs page for your connection.

For example, you might have a connection set up that has the read_products scope selected along with the Product model. If you edit your connection to include the Collection model, you do not need new scopes, but you need to register the collections/create, collections/update, and collections/delete webhooks manually.

Screenshot of the Installs page with a store that has a missing webhooks warningScreenshot of the Installs page with a store that has a missing webhooks warning expanded to show missing Collections webhooks

To register webhooks, you need to go to the Installs page for your Connection in Gadget, click the More button (

) for any stores you have re-authenticated on and select the Register Webhooks option.

Screenshot of the Register Webhooks option for a store on the Installs page

Once the webhooks are registered, you are ready to continue building your app using the newly selected scopes and models.

Syncing

The syncing system for the Shopify connection works by leveraging Actions and Effects. Each time Gadget goes to sync the connected shop, Gadget creates a new Shopify Sync record and dispatches the Run and either the Complete or Error actions based on the outcome of the sync. There are three types of syncs for the Shopify connection: API-triggered, Manual, and Daily.

Daily syncs

The Shopify connection will automatically fetch all recent data in the background daily. This ensures we have all of the shop's data, in the case of a missing webhook, or for resources that don't have webhooks (such as the Online Store content). This sync only fetches data from the past day, so if the sync fails or has scheduling issues, there's a possibility you may not have the most up-to-date data in Gadget. If this does occur, check the Shopify Sync data viewer or logs via the Sync History to identify any errors.

API-triggered Syncs

An API-triggered sync can be initiated via the GraphQL API or api in code effects. For example, it may be necessary to run an initial sync upon installation. A success effect can be added to the Shopify Shop model's create action with the following code effect:

shopifyShop/create/initial-sync.js
JavaScript
1module.exports = async ({ api, record, params, logger, connections }) => {
2 await api.shopifySync.run({
3 shopifySync: {
4 domain: record.domain,
5 shop: {
6 _link: record.id,
7 },
8 },
9 });
10};

Sync by date-time

You can optionally pass a syncSince to indicate the earliest date-time you wish to sync from; without this parameter, the API-triggered sync will be a full data sync.

shopifyProduct/update/run-sync.js
JavaScript
1module.exports = async ({ api, record, params, logger, connections }) => {
2 if (record.shopId) {
3 const shop = await api.shopifyShops.findOne(record.shopId);
4 const syncSince = new Date();
5 const millisecondsPerDay = 1000 * 60 * 60 * 24;
6 // sync from 5 days ago
7 syncSince.setTime(syncSince.getTime() - 5 * millisecondsPerDay);
8 await api.shopifySync.run({
9 shopifySync: {
10 domain: shop.domain,
11 // optional parameter
12 syncSince,
13 shop: {
14 _link: record.shopId,
15 },
16 },
17 });
18 }
19};

Sync by model

You may also optionally pass a models parameter to the runSync call to specify which particular Shopify models to sync; this should be an array of model API identifiers. If the models parameter is either omitted or is an empty array, all Shopify models will be synced.

shopifyProduct/update/run-sync.js
JavaScript
1module.exports = async ({ api, record, params, logger, connections }) => {
2 if (record.shopId) {
3 const shop = await api.shopifyShops.findOne(record.shopId);
4 await api.shopifySync.run({
5 shopifySync: {
6 domain: shop.domain,
7 shop: {
8 _link: record.shopId,
9 },
10 // optional parameter
11 models: ["shopifyProduct"],
12 },
13 });
14 }
15};

Manual syncs

A sync will be queued (without a syncSince set) when clicking the "Sync" button next to your Shopify connection. This will make a call to the Shopify Sync model's Run action.

The connections index page having performed a single sync successfully

This sync may take some time to complete, depending on how much data the shop has.

Sync error handling

If an error occurs during a sync, the Shopify Sync model's Error action will be called. For example, here's how you teach Gadget to alert you via SMS when a sync fails.

JavaScript
1const Twilio = require("twilio");
2// Environment variables set in Gadget
3const twilio = new Twilio(
4 process.env["TWILIO_ACCOUNT_SID"],
5 process.env["TWILIO_ACCOUNT_AUTH_TOKEN"]
6);
7
8module.exports = async ({ api, record, params, logger, connections }) => {
9 /*
10 params: {
11 id: string;
12 shopifySync: {
13 errorMessage: string;
14 errorDetails: string;
15 }
16 }
17 */
18
19 const errors = params.shopifySync.errorDetails.split("\n");
20
21 // send the errors individually to the logger
22 for (const error of errors) {
23 logger.error({ error }, "an error occurred syncing");
24 }
25
26 // send an SMS notification
27 await twilio.sendSMS({
28 to: "+11112223333",
29 from: "+11112223333",
30 body: `Shopify sync failed with message: ${params.shopifySync.errorMessage}`,
31 });
32};

id is the Shopify Sync id that was created
errorMessage contains a generate description of the error or errors
errorDetails contains a all error messages (if more than 1 occurred) joined by a \n

The best way to debug why a sync may have failed is to search for errors through your logs. Use the following log query to filter by sync ID (replace {syncId} with ID of the sync that has failed):

{app_logs_service=~".+", environment_id="{environmentID}"} | json | connectionSyncId = "{syncID}"

Metafields

Shopify metafields allow you to extend Shopify's data model to store additional information on resources including orders, products, customers, and shop. Frequently used in custom and public app development, metafields are an important tool for building rich Shopify app experiences.

Despite their importance and popularity, working with metafields can be challenging for developers. The data is stored in a separate resource on Shopify's end (the “metafield object”), whereas you almost certainly want the data right on the resource you are extending with that metafield. Additionally, Shopify's API rate limits make this additional resource hopping even more cumbersome to navigate.

To simplify this experience, Gadget offers developers a fast way to sync, query and mutate Shopify metafields in their app's backend.

Storing metafield data in Gadget

Gadget allows you to store metafield data directly on any of the following Shopify resources: articles, blogs, collections, customers, orders, pages, products, and shop.

To do this, you must first copy the desired resource to your Gadget backend. Go to the Connections screen and pick the desired scopes and models, e.g. the read_products scope and the Product model, and connect to a store.

Once you have the desired model in your Gadget backend, click on “Add Field” to decorate the model with the additional metafield values. Name your field and select an appropriate type for the incoming data. To start the metafield import, you also need to click the Store data from Shopify Metafield box.

The required fields to set up a metafield on a Shopify Model

You now need to register your metafield's namespace. Enter the namespace that is used for your metafield in the Shopify Store, then click Register Namespace. Gadget will then register for webhooks on the entered namespace.

The namespace for a metafield is registered

Once you get a message stating that the namespace registrations are complete, you can enter the key for your metafield and select the correct metafield type.

Here's an example of what the form looks like when we try to teach Gadget to store a metafield capturing each product variant's weight, under the namespace "gadget_app" and key "spiciness":

A completed Shopify metafield setup in Gadget

Your Gadget app is now set up to store the data directly on this model. You can go back to your Connections page and sync to pull in metafield data. Once the metafield data is synced to your Gadget app, you can query or mutate metafield values using Gadget Actions.

Querying metafields

One of the main advantages of Gadget's approach to metafields is that once you specify where the metafield values should be stored, you can query the data using Gadget's instant CRUD APIs.

You can fetch metafield values alongside the records they correspond to, in a single query. You can also run range queries directly on the metafields.

Metafield query examples

Here's an example of a range query being run on “spiciness”, a metafield stored on the Shopify Product, in order to fetch products that have a spiciness rating of greater than 5:

GraphQL
1query {
2 shopifyProducts(
3 filter: { spiciness: { greaterThan: 5 } }
4 sort: { spiciness: Ascending }
5 ) {
6 edges {
7 node {
8 title
9 id
10 spiciness
11 handle
12 }
13 }
14 }
15}

Writing to metafields

If you're looking to mutate metafield values in Gadget and sync them back to Shopify, you will need to teach Gadget about the mutation in code. You can do this in Gadget by writing code Effects and having Gadget run them when the API is triggered.

Metafield writing examples

Here's an example of a code effect added to the Update action of a Shopify Customer model that overrides the metafield data in Gadget first, then sends the information to Shopify so that the data stays in sync:

JavaScript
1/**
2 * Fetch the ids for metafields on a resource
3 */
4const fetchMetafieldIds = async ({ resource, shopifyApi, metafieldSchema, id }) => {
5 const gidResource = resource.charAt(0).toUpperCase() + resource.slice(1);
6 const gid = `gid://shopify/${gidResource}/${id}`;
7 return (
8 await shopifyApi.graphql(
9 `
10 query MetafieldIds($id: ID!) {
11 metafields: ${resource}(id: $id) {
12 ${metafieldSchema.metafields.map(
13 ({ namespace, key }) =>
14 `${namespace}_${key}: metafield(namespace: ${JSON.stringify(
15 namespace
16 )}, key: ${JSON.stringify(key)}) { id }`
17 )}
18 }
19 }
20 `,
21 {
22 id: gid,
23 }
24 )
25 ).metafields;
26};
27
28/**
29 * Get the shopify metafield configuration for all metadata fields in `model`
30 */
31const getModelMetafieldSchema = (model) => {
32 const metafields = [];
33 const privateMetafields = [];
34 for (const field of Object.values(model.fields)) {
35 const contributorConfig =
36 field.contributorConfiguration["shopify/contributor/field/metafield"];
37 if (!contributorConfig) continue;
38
39 const metafield = contributorConfig.metafield;
40 if (!metafield.namespace || !metafield.key) continue;
41
42 if (!metafield.isPrivate) {
43 metafields.push({ ...metafield, apiIdentifier: field.apiIdentifier });
44 } else {
45 privateMetafields.push({ ...metafield, apiIdentifier: field.apiIdentifier });
46 }
47 }
48
49 return { metafields, privateMetafields };
50};
51
52const buildRESTMetafieldsPayload = async ({
53 resource,
54 shopifyApi,
55 model,
56 record,
57}) => {
58 const metafieldSchema = getModelMetafieldSchema(model);
59 const metafieldIds = await fetchMetafieldIds({
60 resource,
61 shopifyApi,
62 metafieldSchema,
63 id: record.id,
64 });
65
66 // Make sure the field we're updating has a metafield and that if it has a Shopify id then include id
67 return metafieldSchema.metafields.map(
68 ({ namespace, key, type, apiIdentifier }) => {
69 const gid = metafieldIds[`${namespace}_${key}`]?.id;
70 const id = gid ? gid.match(/^gid:\/\/shopify\/[A-Za-z]+\/(\d+)$/)[1] : null;
71 return {
72 id,
73 namespace,
74 key,
75 type,
76 value: record[apiIdentifier],
77 };
78 }
79 );
80};
81
82// Once a record has been updated in Gadget, fire off an update to the Shopify API
83// to keep our meta fields in sync
84module.exports = async ({ model, record, connections }) => {
85 const shopifyApi = await connections.shopify.forShopDomain(
86 "mycoolshop.myshopify.com"
87 );
88
89 // If customer's order count is greater than 10, mark them with a VIP metafield flag
90 if (record.ordersCount > 10) {
91 // Set VIP flag to true
92 // This field will have been set up as a metafield in the Shopify Customer model
93 record.isVip = true;
94
95 // Update metafield on a resource through the REST API
96 await shopifyApi.customer.update(Number(record.id), {
97 metafields: await buildRESTMetafieldsPayload({
98 resource: "customer",
99 shopifyApi,
100 model,
101 record,
102 }),
103 });
104 }
105};

Metafield utility methods

In the above example, we implement three utility methods to support querying and writing to metafields in code effects. While these methods are not built into the client, you are free to use them in your own code effects.

getModelMetafieldSchema is used to find all fields on a Gadget model that is set up as a metafield. This method returns an object that has keys for public and private metafield definitions.

fetchMetafields is used to fetch existing metafield definitions on a Shopify shop. This is necessary to ensure that when writing to a metafield, an existing metafield namespace and key combination includes its ID, as an ID is required by Shopify to write to an existing namespace and key combination.

buildRESTMetafieldsPayload matches the record's fields with a model metafield and adds an appropriate Shopify metafield definition ID to the REST payload.

Available Models

Gadget receives webhooks and syncs data from Shopify for the following models:

Model NameRequired ScopesWebhook Topics
AppAlways availablesynced only
App CreditAlways availablesynced only
Shopify App Credits (and other billing resources) are only available to OAuth apps created via the Shopify CLI or in the Shopify Partners dashboard that are marked for Public distribution. To successfully receive webhooks or sync this model, you must mark your app for Public distribution. Find more instructions in the Shopify docs.
App InstallationAlways availablesynced only
App Purchase One TimeAlways availableapp_purchases_one_time/update
Shopify App Purchase One Time (and other billing resources) are only available to OAuth apps created via the Shopify CLI or in the Shopify Partners dashboard that are marked for Public distribution. To successfully receive webhooks or sync this model, you must mark your app for Public distribution. Find more instructions in the Shopify docs.
App SubscriptionAlways availableapp_subscriptions/update
Shopify App Subscription (and other billing resources) are only available to OAuth apps created via the Shopify CLI or in the Shopify Partners dashboard that are marked for Public distribution. To successfully receive webhooks or sync this model, you must mark your app for Public distribution. Find more instructions in the Shopify docs.
App Usage RecordAlways availablesynced only
Blogread_contentsynced only
Articleread_contentsynced only
Commentread_contentsynced only
Themeread_themesthemes/create, themes/update, themes/delete
Assetread_themessynced only
Balance Transactionread_shopify_payments_payoutssynced only
Checkoutread_checkouts, read_orderscheckouts/create, checkouts/update
The read_checkouts scope will allow Gadget to process checkout related webhooks, but does not provide a mechanism to sync all existing checkouts.

Adding the read_orders scope, while also including the Checkout model in your application, will result in all Abandoned Checkouts that aren't handled via webhooks (failed delivery, checkouts that already exist) being imported during nightly or manual syncs.
Billing Addressread_checkouts, read_ordersSent within Checkout model
Checkout Applied Gift Cardread_checkouts, read_orderssynced only
Checkout Line Itemread_checkouts, read_ordersSent within Checkout model
Checkout Shipping Rateread_checkouts, read_orderssynced only
Shipping Addressread_checkouts, read_ordersSent within Checkout model
Bulk OperationAlways availablebulk_operations/finish
Carrier Serviceread_shippingsynced only
Cartread_orderscarts/create, carts/update
Cart Line Itemread_ordersSent within Cart model
Collectionread_productscollections/create, collections/update, collections/delete
Gadget uses the Collection model to represent both Custom Collections and Smart Collections from Shopify.
Productread_productsproducts/create, products/update, products/delete
Collectread_productssynced only
Product Imageread_productsSent within Product model
Product Optionread_productsSent within Product model
Product Variantread_productsSent within Product model
Countryread_shippingsynced only
Provinceread_shippingsynced only
Customerread_customerscustomers/create, customers/update, customers/delete
Customer Addressread_customersSent within Customer model
Customer Payment Methodread_customer_payment_methodscustomer_payment_methods/create, customer_payment_methods/update, customer_payment_methods/revoke
Discount Coderead_discountssynced only
Disputeread_shopify_payments_disputesdisputes/create, disputes/update
Dispute data is only available for Shopify merchants using Shopify Payments.
DomainAlways availabledomains/create, domains/update, domains/destroy
Shopify Domain delete and update webhooks are missing key data, so Gadget does an inline sync of the Domain REST API resource when these webhooks arrive to properly discover updates and deletes.
Draft Orderread_draft_ordersdraft_orders/create, draft_orders/update, draft_orders/delete
Draft Order Line Itemread_draft_ordersSent within Draft Order model
Orderread_ordersorders/create, orders/updated, orders/delete
Dutyread_ordersSent within Order Line Item model
Fulfillment Eventread_ordersfulfillment_events/create, fulfillment_events/delete
Fulfillmentread_ordersfulfillments/create, fulfillments/update
Fulfillment Line Itemread_ordersSent within Fulfillment model
Order Adjustmentread_ordersSent within Refund model
Order Line Itemread_ordersSent within Order model
Order Riskread_orderssynced only
Order Transactionread_ordersorder_transactions/create
Refund Dutyread_ordersSent within Refund model
Refundread_ordersrefunds/create
Refund Line Itemread_ordersSent within Refund model
Shipping Lineread_ordersSent within Order model
Tender Transactionread_orderstender_transactions/create
Eventread_content, read_products, read_price_rules, read_orderssynced only
Fulfillment Orderread_assigned_fulfillment_orders, read_merchant_managed_fulfillment_orders, read_third_party_fulfillment_orderssynced only
Fulfillment Order Line Itemread_assigned_fulfillment_orders, read_merchant_managed_fulfillment_orders, read_third_party_fulfillment_orderssynced only
Fulfillment Serviceread_fulfillmentssynced only
GDPR RequestAlways availablesynced only
This model tracks incoming GDPR webhook requests from Shopify to delete merchant or customer data. These GDPR webhooks are required to be supported by Public applications for the Shopify app store, which you can read more about in the Shopify Docs. This model doesn't correspond to an API endpoint within Shopify.
Inventory Itemread_inventoryinventory_items/create, inventory_items/update, inventory_items/delete
Inventory Items are synced using the REST API endpont for Inventory Levels for each Location to get a list of inventory levels, and then using the REST API endpoint to get a list of inventory items for each level.
Inventory Levelread_inventoryinventory_levels/connect, inventory_levels/update, inventory_levels/disconnect
Inventory Levels are synced using the REST API endpoint for Inventory Levels at a Location.
Locationread_locationslocations/create, locations/update, locations/delete
Pageread_contentsynced only
Payoutread_shopify_payments_payoutssynced only
Price Ruleread_price_rulessynced only
Redirectread_contentsynced only
Script Tagread_script_tagssynced only
ShopAlways availableshop/update, app/uninstalled
Selling Plan Groupread_productsselling_plan_groups/create, selling_plan_groups/update, selling_plan_groups/delete
Selling Plan Group Productread_productsSent within Selling Plan Group model
Selling Plan Group Product Variantread_productsSent within Selling Plan Group model
Selling Planread_productsSent within Selling Plan Group model
Subscription Contractread_own_subscription_contractssubscription_contracts/create, subscription_contracts/update
Subscription Billing Attemptread_own_subscription_contractssubscription_billing_attempts/success, subscription_billing_attempts/failure, subscription_billing_attempts/challenged
Subscription Lineread_own_subscription_contractssynced only
Subscription Manual Discountread_own_subscription_contractssynced only

Troubleshooting

The sync between Shopify and my Gadget app failed.

Do you have any custom code effects running on the create action on the Shopify Sync model? A custom code effect with errors will prevent the sync from completing successfully. Try removing or editing the code effect(s) and running a manual sync.

Code effects aren't updating my records in Shopify.

You need to explicitly call out to the Shopify client in your code effect to manipulate data in Shopify. See Accessing the Shopify API.

Frequently Asked Questions

How do I make calls back to Gadget from a Shopify storefront?

You can call your Gadget app's API client in the storefront's Shopify theme. To do so, you can use the Direct Script Tag option in the Installation section of your app's API Reference.

How do I make an embedded Shopify app using Gadget?

Gadget supports being used as a backend for an app embedded in the Shopify Admin. You can read the docs for setting up the Gadget app client and Provider and go through the tutorial that walks you through setting up an embedded app with the Shopify CLI and Gadget.

When does Gadget automatically sync my Shopify connection?

Gadget will fully sync your Shopify connection on demand when you request a sync from the Connections view. Gadget will also automatically fetch all recent data from Shopify in the background in a scheduled daily sync. To see when your app was last synced with Shopify, you can visit the Connections view or view the Shopify Sync dataviewer.