Building Shopify app extensions 

Prerequisites 

Before building Shopify extensions, you need to:

Working with extensions 

You can build your Shopify app extensions inside your Gadget app using the Shopify CLI and ggt, Gadget's CLI.

  1. In your local terminal, run the ggt dev command replacing <YOUR APP DOMAIN> to pull down your app to your local machine:
terminal
ggt dev ./<YOUR APP DOMAIN> --app=<YOUR APP DOMAIN> --env=development

You can also click the cloud icon next to your environment selector in the Gadget editor to get your app's ggt dev command. See the ggt guide for more info on working locally.

  1. cd into your project, and open it in an editor.
  2. Add the following workspaces and trustedDependencies to your package.json:
package.json
json
{ "workspaces": ["extensions/*"], "trustedDependencies": ["@shopify/plugin-cloudflare"] }
Installing dependencies

Once you add the workspaces definition to your package.json, you will need to use the -W flag to add new packages to your core Gadget app:

terminal
yarn add -W <package>

This is required by Yarn workspaces to ensure that all packages are installed in the correct location.

  1. Add a .ignore file to the root of your project.
  2. Add the following to both .ignore (and .gitignore if you are using source control):
add to .ignore and .gitignore
extensions/*/dist extensions/*/node_modules

If your Gadget app does not have a shopify.app.toml file, you need to manually add one to the root of your project. New Gadget apps will come with a TOML file. Learn more about working with Shopify TOML files in Gadget.

  1. Use the Shopify CLI to generate your checkout UI extension:
terminal
yarn shopify app generate extension

The following steps are for admin, checkout, or customer account extensions. For theme app extensions, see the theme app extensions section.

  1. Select the same Partner app and development store you used to connect to Shopify when prompted by Shopify's CLI.
  2. Select an extension type and a language for your extension.

This command will create an extensions folder at your project root, and your extension will be generated by the Shopify CLI.

  1. Start your extension development server by running:
terminal
yarn shopify:dev
Shopify scripts added to package.json

The Shopify connection, adds the following scripts to your package.json:

// Default Shopify CLI command "shopify": "shopify" // Use the current development environment's Shopify app config "shopify:config:use:development": "shopify app config use shopify.app.development.toml" // Use the production environment's Shopify app config "shopify:config:use:production": "shopify app config use shopify.app.toml" // Start the Shopify CLI dev server using the current development environment's Shopify app config "shopify:dev": "yarn shopify:config:use:development && shopify app dev --no-update" // Deploy the development environment; this should be used when developing app extensions to sync the extension to Shopify "shopify:deploy:development": "yarn shopify:config:use:development && shopify app deploy" // Deploy the production environment; this can be used for CI setups to deploy the app to Shopify after the Gadget app is deployed to production using ggt deploy "shopify:deploy:production": "yarn shopify:config:use:production && shopify app deploy" // An alias for shopify:deploy:production "shopify:deploy": "yarn shopify:deploy:production" // Get info about the Shopify app "shopify:info": "shopify app info"
Bringing an existing extension into Gadget?

If you are porting over an existing extension-only app and you are copying over your root-level app configuration shopify.app.toml, you need to make sure use_legacy_install_flow = true is set in the [access_scopes] section so Gadget can manage scope registration.

Using Shopify metafields as input 

You can use Shopify metafields to store and retrieve custom data. This has the added benefit of being stored on Shopify's infrastructure, so you don't need to manage stored values in your Gadget database.

You do have the option to store metafield data in your Gadget database if it is required for your app. If you need access to metafield data in Gadget, you can add metadata fields to your Shopify data models.

Metafields are the only way to use custom data as input in some extensions, for example, most Shopify Functions.

Make a network request to your Gadget API 

In some extensions, you can also send a request to your app's API to run custom backend code and return the data you need. This is useful if you need to run custom logic to generate the data you need.

Before you write any network requests, you'll need to set network_access = true in your extension's shopify.extension.toml file. Some extensions, such as Admin extensions, already allow you to make requests to your app backend, and don't require this setting.

Some extension types may not allow external network requests. Check Shopify's documentation for the extension type you're working with to see if network access is allowed.

Initialize your API client 

To use your Gadget API client in an extension you can import your Client and initialize it with your current Gadget app environment:

extensions/your-extension-name/src/Extension.jsx
JavaScript
import { Client } from "@gadget-client/<YOUR-GADGET-APP-DOMAIN>"; export const api = new Client({ environment: process.env["NODE_ENV"] });

If you are managing your extensions outside of your Gadget project, for example, in a Shopify CLI app, you need to install your API client .

Environment selection in extension clients 

Shopify extensions are sandboxed, so there is not a simple way to get the current Gadget environment when starting an extension. If you only have a single development environment, using the extension's environment variable process.env.NODE_ENV could work for you.

If you have multiple development environments you will need a way to manually update the environment used to initialize the Client in extensions.

One option: add a small script file to your project that accepts an environment name and does string replacement for the environment used to init Client. Run this with a package.json script command that also starts the Shopify extension dev server. This approach can also work when deploying to production with a CI/CD pipeline.

Using @gadgetinc React hooks 

The @gadgetinc/react hooks, such as useFindMany, useAction, and useFetch, can be used to interact with your app's API.

  1. Install the @gadgetinc/react package:
terminal
yarn add @gadgetinc/react
  1. Set up the Provider in your extension by wrapping the exported extension component or app with the Provider component and passing in your API client instance:
extensions/your-extension-name/src/Extension.jsx
React
import { Provider } from "@gadgetinc/react"; import { api } from "./api"; export default reactExtension(TARGET, () => ( <Provider api={api}> <App /> </Provider> ));
import { Provider } from "@gadgetinc/react"; import { api } from "./api"; export default reactExtension(TARGET, () => ( <Provider api={api}> <App /> </Provider> ));

Now you can use the @gadgetinc/react hooks to interact with your app's API.

Admin extensions 

By default, Shopify's Admin extensions will add an Authentication header to requests made by the extension.

Your Gadget app will automatically handle these incoming requests, and grant them the shopify-app-users role. This means you can use your api client like you would in an embedded admin frontend, with or without the @gadgetinc/react hooks.

Here's an example of a simple Admin extension making an authenticated request to a custom updateDescription action on the shopifyProduct model:

extensions/your-extension-name/src/ActionExtension.jsx
React
import { useCallback, useState } from "react"; import { reactExtension, useApi, AdminAction, BlockStack, Button, Text, NumberField } from "@shopify/ui-extensions-react/admin"; // import app API client import { api } from "./api"; import { Provider, useAction } from "@gadgetinc/react"; // The target used here must match the target used in the extension's toml file (./shopify.extension.toml) const TARGET = "admin.product-details.action.render"; // set up the Provider component so React hooks can be used export default reactExtension(TARGET, () => ( <Provider api={api}> <App /> </Provider> )); function App() { // The useApi hook provides access to several useful APIs like i18n, close, and data. const { extension: { target }, i18n, close, data, } = useApi(TARGET); const [wordCount, setWordCount] = useState("100"); // custom action in Gadget that updates the product description // using OpenAI to generate a description based on the word count and product images const [_, updateDescription] = useAction(api.shopifyProduct.updateDescription); const update = useCallback(async () => { // get current product id from data // remove the shopifyProduct gid prefix from the id const productId = data.selected[0].id.split("/").pop(); // fire request to update the product description in Gadget await updateDescription({ id: productId, wordCount, }); }); // The AdminAction component provides an API for setting the title and actions of the Action extension wrapper. return ( <AdminAction primaryAction={ <Button onPress={() => { update(); close(); }} > {i18n.translate("updateDescription")} </Button> } secondaryAction={ <Button onPress={() => { close(); }} > {i18n.translate("close")} </Button> } loading={fetching} > <BlockStack gap="large"> <Text fontWeight="bold">{i18n.translate("welcome", { target })}</Text> <NumberField label="Select a word count" value={wordCount} onChange={setWordCount} /> </BlockStack> </AdminAction> ); }
import { useCallback, useState } from "react"; import { reactExtension, useApi, AdminAction, BlockStack, Button, Text, NumberField } from "@shopify/ui-extensions-react/admin"; // import app API client import { api } from "./api"; import { Provider, useAction } from "@gadgetinc/react"; // The target used here must match the target used in the extension's toml file (./shopify.extension.toml) const TARGET = "admin.product-details.action.render"; // set up the Provider component so React hooks can be used export default reactExtension(TARGET, () => ( <Provider api={api}> <App /> </Provider> )); function App() { // The useApi hook provides access to several useful APIs like i18n, close, and data. const { extension: { target }, i18n, close, data, } = useApi(TARGET); const [wordCount, setWordCount] = useState("100"); // custom action in Gadget that updates the product description // using OpenAI to generate a description based on the word count and product images const [_, updateDescription] = useAction(api.shopifyProduct.updateDescription); const update = useCallback(async () => { // get current product id from data // remove the shopifyProduct gid prefix from the id const productId = data.selected[0].id.split("/").pop(); // fire request to update the product description in Gadget await updateDescription({ id: productId, wordCount, }); }); // The AdminAction component provides an API for setting the title and actions of the Action extension wrapper. return ( <AdminAction primaryAction={ <Button onPress={() => { update(); close(); }} > {i18n.translate("updateDescription")} </Button> } secondaryAction={ <Button onPress={() => { close(); }} > {i18n.translate("close")} </Button> } loading={fetching} > <BlockStack gap="large"> <Text fontWeight="bold">{i18n.translate("welcome", { target })}</Text> <NumberField label="Select a word count" value={wordCount} onChange={setWordCount} /> </BlockStack> </AdminAction> ); }

Checkout extensions 

Checkout extensions are making network requests from an unauthenticated context, the Shopify checkout. This means that requests made to your app's API will be granted the unauthenticated role. Make sure any data passed into the checkout extensions is safe to be seen by any buyer!

Custom apps 

For custom apps where you do not need multi-tenancy per shop, you can make requests using the API client:

extensions/your-extension-name/src/Checkout.jsx
React
import { Banner, reactExtension } from "@shopify/ui-extensions-react/checkout"; import { Provider, useGlobalAction } from "@gadgetinc/react"; // import your app API client import { api } from "../api"; // set up the Provider component so React hooks can be used export default reactExtension("purchase.checkout.block.render", () => ( <Provider api={api}> <Extension /> </Provider> )); function Extension() { // use hooks to call your API // in this case, a global action const [{ data, error, fetching }, refresh] = useGlobalAction(api.myCustomGlobalAction); if (fetching) { return <Banner>Loading...</Banner>; } if (error) { return <Banner>Error loading. Please try again.</Banner>; } return <Banner>{data.value}</Banner>; }
import { Banner, reactExtension } from "@shopify/ui-extensions-react/checkout"; import { Provider, useGlobalAction } from "@gadgetinc/react"; // import your app API client import { api } from "../api"; // set up the Provider component so React hooks can be used export default reactExtension("purchase.checkout.block.render", () => ( <Provider api={api}> <Extension /> </Provider> )); function Extension() { // use hooks to call your API // in this case, a global action const [{ data, error, fetching }, refresh] = useGlobalAction(api.myCustomGlobalAction); if (fetching) { return <Banner>Loading...</Banner>; } if (error) { return <Banner>Error loading. Please try again.</Banner>; } return <Banner>{data.value}</Banner>; }

Public apps 

You can still enforce shop multi-tenancy by passing the Shopify session token with your request.

Sending the session token 

When you send Shopify's session token to Gadget, you need to use the ShopifySessionToken prefix in the Authorization header. This is ensures that your Gadget actions have the correct shop context.

Gadget provides a @gadgetinc/shopify-extensions package you can install into your extension that makes it easy to add the session token as a header to all requests made using your Gadget app's API client.

You can install this package in your extension by running this in the extensions/<your-extension-name> folder:

terminal
yarn add @gadgetinc/shopify-extensions

Then you can make use of the exported Provider and useGadget hook to automatically add the session token to requests made using your API client:

extensions/your-extension-name/src/Extension.jsx
React
import { reactExtension, useApi } from "@shopify/ui-extensions-react/customer-account"; import { Provider, useGadget } from "@gadgetinc/shopify-extensions/react"; import { useFindMany } from "@gadgetinc/react"; import { Client } from "@gadget-client/example-app"; // initialize a new Client for your Gadget API const apiClient = new Client(); // the Provider is set up in the reactExtension() initialization function export default reactExtension("your.extension.target", () => <GadgetUIExtension />); // component to set up the Provider with the sessionToken from Shopify function GadgetUIExtension() { const { sessionToken } = useApi(); return ( <Provider api={apiClient} sessionToken={sessionToken}> <MyExtension /> </Provider> ); } function MyExtension() { // get the 'api' client and a 'ready' boolean from the useGadget hook const { api, ready } = useGadget<Client>(); const [{ data, fetching, error }] = useFindMany(api.customModel, { // use 'ready' to pause hooks until the API client is ready to make authenticated requests pause: !ready, }); // the rest of your extension component... }
import { reactExtension, useApi } from "@shopify/ui-extensions-react/customer-account"; import { Provider, useGadget } from "@gadgetinc/shopify-extensions/react"; import { useFindMany } from "@gadgetinc/react"; import { Client } from "@gadget-client/example-app"; // initialize a new Client for your Gadget API const apiClient = new Client(); // the Provider is set up in the reactExtension() initialization function export default reactExtension("your.extension.target", () => <GadgetUIExtension />); // component to set up the Provider with the sessionToken from Shopify function GadgetUIExtension() { const { sessionToken } = useApi(); return ( <Provider api={apiClient} sessionToken={sessionToken}> <MyExtension /> </Provider> ); } function MyExtension() { // get the 'api' client and a 'ready' boolean from the useGadget hook const { api, ready } = useGadget<Client>(); const [{ data, fetching, error }] = useFindMany(api.customModel, { // use 'ready' to pause hooks until the API client is ready to make authenticated requests pause: !ready, }); // the rest of your extension component... }

If you aren't using your app's API client, this example shows how to send the session token in a fetch request when reading model data using a findOne query:

extensions/your-extension-name/src/Checkout.jsx
React
import { Banner, reactExtension, useApi } from "@shopify/ui-extensions-react/checkout"; import { useState, useEffect } from "react"; export default reactExtension("purchase.checkout.block.render", () => <Extension />); function Extension() { // get the session token from the useApi hook const { sessionToken } = useApi(); const [productData, setProductData] = useState(null); useEffect(() => { // Specify the GraphQL endpoint const url = "https://my-extension-app--development.gadget.dev/api/graphql"; // Create a GraphQL query const query = ` query GetOneShopifyProduct($id: GadgetID!) { shopifyProduct(id: $id) { title } } `; // get the session token async function getToken() { const token = await sessionToken.get(); return token; } // use fetch to make a POST request to the GraphQL endpoint getToken().then((token) => { fetch(url, { method: "POST", headers: { "Content-Type": "application/json", Accept: "application/json", // pass the session token using the Authorization header Authorization: `ShopifySessionToken ${token}`, }, body: JSON.stringify({ query: query }), }) .then((response) => response.json()) .then((jsonData) => { // handle the returned data setProductData(jsonData.data.product); }) .catch((error) => console.error("Error:", error)); }); }, [sessionToken]); return <Banner>{productData.title}</Banner>; }
import { Banner, reactExtension, useApi } from "@shopify/ui-extensions-react/checkout"; import { useState, useEffect } from "react"; export default reactExtension("purchase.checkout.block.render", () => <Extension />); function Extension() { // get the session token from the useApi hook const { sessionToken } = useApi(); const [productData, setProductData] = useState(null); useEffect(() => { // Specify the GraphQL endpoint const url = "https://my-extension-app--development.gadget.dev/api/graphql"; // Create a GraphQL query const query = ` query GetOneShopifyProduct($id: GadgetID!) { shopifyProduct(id: $id) { title } } `; // get the session token async function getToken() { const token = await sessionToken.get(); return token; } // use fetch to make a POST request to the GraphQL endpoint getToken().then((token) => { fetch(url, { method: "POST", headers: { "Content-Type": "application/json", Accept: "application/json", // pass the session token using the Authorization header Authorization: `ShopifySessionToken ${token}`, }, body: JSON.stringify({ query: query }), }) .then((response) => response.json()) .then((jsonData) => { // handle the returned data setProductData(jsonData.data.product); }) .catch((error) => console.error("Error:", error)); }); }, [sessionToken]); return <Banner>{productData.title}</Banner>; }

Post-purchase extensions 

Post-purchase extensions are a type of checkout extension that requires a JSON Web Token (JWT) to be signed and passed to the extension. This signing can be done in your app backend by passing the JWT from the extension to Gadget as an Authorization: Bearer header.

For example, in your post-purchase extension, you can make a request to get offers and determine if you should render the extension:

extensions/your-extension-name/src/index.jsx
React
/** * Extend Shopify Checkout with a custom Post Purchase user experience. * This template provides two extension points: * * 1. ShouldRender - Called first, during the checkout process, when the * payment page loads. * 2. Render - If requested by `ShouldRender`, will be rendered after checkout * completes */ // other imports such as React state hooks and extension components are omitted for brevity import React from "react"; import { extend, render } from "@shopify/post-purchase-ui-extensions-react"; // your app API client import { api } from "./api"; /** * Entry point for the `ShouldRender` Extension Point. * * Returns a value indicating whether or not to render a PostPurchase step, and * optionally allows data to be stored on the client for use in the `Render` * extension point. */ extend("Checkout::PostPurchase::ShouldRender", async ({ inputData, storage }) => { // get the variant ids of the products in the initial purchase const productVariantIds = inputData.initialPurchase.lineItems.map((lineItem) => lineItem.product.variant.id); // make request against POST-offer route in Gadget const response = await api.fetch("/offer", { method: "POST", headers: { "Content-Type": "application/json", Authorization: `Bearer ${inputData.token}`, }, body: JSON.stringify({ referenceId: inputData.initialPurchase.referenceId, productVariantIds, }), }); // get response body from route const jsonResp = await response.json(); // save offers to extension storage await storage.update({ offers: jsonResp.offers }); // For local development, always show the post-purchase page return { render: true }; }); render("Checkout::PostPurchase::Render", () => <App />); export function App() { // the rest of the post-purchase extension component // determine what is actually rendered in this component }
/** * Extend Shopify Checkout with a custom Post Purchase user experience. * This template provides two extension points: * * 1. ShouldRender - Called first, during the checkout process, when the * payment page loads. * 2. Render - If requested by `ShouldRender`, will be rendered after checkout * completes */ // other imports such as React state hooks and extension components are omitted for brevity import React from "react"; import { extend, render } from "@shopify/post-purchase-ui-extensions-react"; // your app API client import { api } from "./api"; /** * Entry point for the `ShouldRender` Extension Point. * * Returns a value indicating whether or not to render a PostPurchase step, and * optionally allows data to be stored on the client for use in the `Render` * extension point. */ extend("Checkout::PostPurchase::ShouldRender", async ({ inputData, storage }) => { // get the variant ids of the products in the initial purchase const productVariantIds = inputData.initialPurchase.lineItems.map((lineItem) => lineItem.product.variant.id); // make request against POST-offer route in Gadget const response = await api.fetch("/offer", { method: "POST", headers: { "Content-Type": "application/json", Authorization: `Bearer ${inputData.token}`, }, body: JSON.stringify({ referenceId: inputData.initialPurchase.referenceId, productVariantIds, }), }); // get response body from route const jsonResp = await response.json(); // save offers to extension storage await storage.update({ offers: jsonResp.offers }); // For local development, always show the post-purchase page return { render: true }; }); render("Checkout::PostPurchase::Render", () => <App />); export function App() { // the rest of the post-purchase extension component // determine what is actually rendered in this component }

And your Gadget POST-offer HTTP route could look like:

api/routes/POST-offer.js
JavaScript
import { RouteHandler } from "gadget-server"; import jwt from "jsonwebtoken"; import { getOffers } from "../utils/offerUtils"; const route: RouteHandler<{ Body: { referenceId: string; productVariantIds: string[]; }; }> = async ({ request, reply, api, logger, connections }) => { let token = request.headers?.Authorization as string; if (token?.startsWith("Bearer ")) { token = token.slice(7); } else { // if no bearer token is present, return 401 error await reply.code(401).send(); } // use SHOPIFY_API_SECRET (from Partners app) as an environment variable to decode the token const decodedToken = jwt.verify(token, process.env["SHOPIFY_CLIENT_SECRET"]); // get the referenceId from the decoded token const decodedReferenceId = decodedToken.input_data.initialPurchase.referenceId; const { referenceId, productVariantIds } = request.body; if (decodedReferenceId !== referenceId) { // return error if incoming jwt is not valid await reply.code(401).send(); } // fetch custom offers const offers = await getOffers({ api, logger, connections, productVariantIds }); // reply with the offers await reply.headers({ "Content-type": "application/json" }).send({ offers }); }; export default route;
import { RouteHandler } from "gadget-server"; import jwt from "jsonwebtoken"; import { getOffers } from "../utils/offerUtils"; const route: RouteHandler<{ Body: { referenceId: string; productVariantIds: string[]; }; }> = async ({ request, reply, api, logger, connections }) => { let token = request.headers?.Authorization as string; if (token?.startsWith("Bearer ")) { token = token.slice(7); } else { // if no bearer token is present, return 401 error await reply.code(401).send(); } // use SHOPIFY_API_SECRET (from Partners app) as an environment variable to decode the token const decodedToken = jwt.verify(token, process.env["SHOPIFY_CLIENT_SECRET"]); // get the referenceId from the decoded token const decodedReferenceId = decodedToken.input_data.initialPurchase.referenceId; const { referenceId, productVariantIds } = request.body; if (decodedReferenceId !== referenceId) { // return error if incoming jwt is not valid await reply.code(401).send(); } // fetch custom offers const offers = await getOffers({ api, logger, connections, productVariantIds }); // reply with the offers await reply.headers({ "Content-type": "application/json" }).send({ offers }); }; export default route;

You will also need a POST-sign-changeset HTTP route in your Gadget app to apply the order changes if a buyer accepts the offer:

api/routes/POST-sign-changeset.js
JavaScript
import { RouteHandler } from "gadget-server"; import { v4 as uuidv4 } from "uuid"; import jwt from "jsonwebtoken"; const route: RouteHandler<{ Body: { referenceId: string; changes: string; }; }> = async ({ request, reply, api, logger, connections }) => { // get token from headers let token = request.headers?.authorization as string; if (token?.startsWith("Bearer ")) { token = token.slice(7); } else { // if no bearer token is present, return 401 error await reply.code(401).send(); } // use SHOPIFY_API_SECRET (from Partners app) as an environment variable to decode the token const decodedToken = jwt.verify(token, process.env["SHOPIFY_CLIENT_SECRET"]); const decodedReferenceId = decodedToken.input_data.initialPurchase.referenceId; const { referenceId, changes } = request.body; // compare passed in referenceId with decoded referenceId if (decodedReferenceId !== referenceId) { // return error if incoming jwt is not valid await reply.code(401).send(); } // create the payload for updating the order const payload = { iss: process.env["SHOPIFY_CLIENT_KEY"], jti: uuidv4(), iat: Date.now(), sub: referenceId, changes, }; // sign the token and return back to the extension const responseToken = jwt.sign(payload, process.env["SHOPIFY_CLIENT_SECRET"]); await reply.send({ token: responseToken }); }; export default route;
import { RouteHandler } from "gadget-server"; import { v4 as uuidv4 } from "uuid"; import jwt from "jsonwebtoken"; const route: RouteHandler<{ Body: { referenceId: string; changes: string; }; }> = async ({ request, reply, api, logger, connections }) => { // get token from headers let token = request.headers?.authorization as string; if (token?.startsWith("Bearer ")) { token = token.slice(7); } else { // if no bearer token is present, return 401 error await reply.code(401).send(); } // use SHOPIFY_API_SECRET (from Partners app) as an environment variable to decode the token const decodedToken = jwt.verify(token, process.env["SHOPIFY_CLIENT_SECRET"]); const decodedReferenceId = decodedToken.input_data.initialPurchase.referenceId; const { referenceId, changes } = request.body; // compare passed in referenceId with decoded referenceId if (decodedReferenceId !== referenceId) { // return error if incoming jwt is not valid await reply.code(401).send(); } // create the payload for updating the order const payload = { iss: process.env["SHOPIFY_CLIENT_KEY"], jti: uuidv4(), iat: Date.now(), sub: referenceId, changes, }; // sign the token and return back to the extension const responseToken = jwt.sign(payload, process.env["SHOPIFY_CLIENT_SECRET"]); await reply.send({ token: responseToken }); }; export default route;

Note that post-purchase extensions require the Shopify Partner app API key and secret to be stored as environment variables in your Gadget app.

Customer account UI extensions 

Gadget's support for customer account UI extensions is in beta. See the guide for more information.

Theme app extensions 

Theme app extensions are different from other types of extensions because they are built using Liquid and JavaScript. They are not Node projects, so there is no package.json where a Gadget API client can be installed.

Instead, you need to:

  1. Include your app's direct script tag to use the API client in a theme app extension .liquid block:
extensions/your-extension-name/blocks/my-extension.liquid
liquid
<script src="https://YOUR-GADGET-DOMAIN.gadget.app/api/client/web.min.js" defer="defer" ></script> <div>My theme extension content goes here!</div> {% schema %} { "name": "My extension", "target": "body", "settings": [] } {% endschema %}
Check the environment in your domain

When you add your script tag, make sure the domain has the correct environment tag!

For example, if you are working in the development environment, your script tag src should look like https://YOUR-GADGET-DOMAIN--development.gadget.app/api/client/web.min.js

  1. Create a file in extensions/your-extension-name/assets, and initialize the API client:
extensions/your-extension-name/assets/my-extension.js
JavaScript
document.addEventListener("DOMContentLoaded", function () { // initialize an API client object const myExtensionAPI = new Gadget(); const myButton = document.getElementById("my-button"); myButton.addEventListener("click", async () => { // make a request to your app's API const response = await myExtensionAPI.myDataModel.findOne("1"); console.log(response); }); });
document.addEventListener("DOMContentLoaded", function () { // initialize an API client object const myExtensionAPI = new Gadget(); const myButton = document.getElementById("my-button"); myButton.addEventListener("click", async () => { // make a request to your app's API const response = await myExtensionAPI.myDataModel.findOne("1"); console.log(response); }); });

Authenticated requests with Shopify app proxies 

When making requests from a theme app extension to your Gadget app, you can use a Shopify app proxy to ensure that requests are made securely. The Gadget platform will handle validating the HMAC signature sent in the request query parameters for you. This is useful for ensuring that requests are coming from a valid Shopify store.

Note that a valid HMAC signature doesn't set the session to an authenticated role. This means that making a POST request to your GraphQL API would be using the unauthenticated role. You can find out more information in our route common use cases docs.

Testing extensions 

To test Shopify extensions, you can run the following command in your project root:

terminal
yarn shopify:dev

Then follow the links provided by the Shopify CLI to preview your extension in the Shopify admin, checkout, customer account, or storefront pages.

Instructions for testing may vary based on extension type. Make sure to check out Shopify's documentation for your specific extension type.

Deploying extensions 

Extensions can be deployed by running:

terminal
// deploy to development environment yarn shopify:deploy:development // deploy to production environment yarn shopify:deploy

This publishes your extension to Shopify's infrastructure, and the extension's functionality will be included as part of the connected Partner app.

Instructions may vary based on the extension type. Read Shopify's documentation for more information on deploying different extensions.

Was this page helpful?