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.

  1. Use the Shopify CLI to generate your checkout UI extension:
terminal
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
shopify app dev
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
1import { Provider } from "@gadgetinc/react";
2import { api } from "./api";
3
4export default reactExtension(TARGET, () => (
5 <Provider api={api}>
6 <App />
7 </Provider>
8));
1import { Provider } from "@gadgetinc/react";
2import { api } from "./api";
3
4export default reactExtension(TARGET, () => (
5 <Provider api={api}>
6 <App />
7 </Provider>
8));

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
1import { useCallback, useState } from "react";
2import { reactExtension, useApi, AdminAction, BlockStack, Button, Text, NumberField } from "@shopify/ui-extensions-react/admin";
3// import app API client
4import { api } from "./api";
5import { Provider, useAction } from "@gadgetinc/react";
6
7// The target used here must match the target used in the extension's toml file (./shopify.extension.toml)
8const TARGET = "admin.product-details.action.render";
9
10// set up the Provider component so React hooks can be used
11export default reactExtension(TARGET, () => (
12 <Provider api={api}>
13 <App />
14 </Provider>
15));
16
17function App() {
18 // The useApi hook provides access to several useful APIs like i18n, close, and data.
19 const {
20 extension: { target },
21 i18n,
22 close,
23 data,
24 } = useApi(TARGET);
25
26 const [wordCount, setWordCount] = useState("100");
27
28 // custom action in Gadget that updates the product description
29 // using OpenAI to generate a description based on the word count and product images
30 const [_, updateDescription] = useAction(api.shopifyProduct.updateDescription);
31
32 const update = useCallback(async () => {
33 // get current product id from data
34 // remove the shopifyProduct gid prefix from the id
35 const productId = data.selected[0].id.split("/").pop();
36 // fire request to update the product description in Gadget
37 await updateDescription({
38 id: productId,
39 wordCount,
40 });
41 });
42
43 // The AdminAction component provides an API for setting the title and actions of the Action extension wrapper.
44 return (
45 <AdminAction
46 primaryAction={
47 <Button
48 onPress={() => {
49 update();
50 close();
51 }}
52 >
53 {i18n.translate("updateDescription")}
54 </Button>
55 }
56 secondaryAction={
57 <Button
58 onPress={() => {
59 close();
60 }}
61 >
62 {i18n.translate("close")}
63 </Button>
64 }
65 loading={fetching}
66 >
67 <BlockStack gap="large">
68 <Text fontWeight="bold">{i18n.translate("welcome", { target })}</Text>
69 <NumberField label="Select a word count" value={wordCount} onChange={setWordCount} />
70 </BlockStack>
71 </AdminAction>
72 );
73}
1import { useCallback, useState } from "react";
2import { reactExtension, useApi, AdminAction, BlockStack, Button, Text, NumberField } from "@shopify/ui-extensions-react/admin";
3// import app API client
4import { api } from "./api";
5import { Provider, useAction } from "@gadgetinc/react";
6
7// The target used here must match the target used in the extension's toml file (./shopify.extension.toml)
8const TARGET = "admin.product-details.action.render";
9
10// set up the Provider component so React hooks can be used
11export default reactExtension(TARGET, () => (
12 <Provider api={api}>
13 <App />
14 </Provider>
15));
16
17function App() {
18 // The useApi hook provides access to several useful APIs like i18n, close, and data.
19 const {
20 extension: { target },
21 i18n,
22 close,
23 data,
24 } = useApi(TARGET);
25
26 const [wordCount, setWordCount] = useState("100");
27
28 // custom action in Gadget that updates the product description
29 // using OpenAI to generate a description based on the word count and product images
30 const [_, updateDescription] = useAction(api.shopifyProduct.updateDescription);
31
32 const update = useCallback(async () => {
33 // get current product id from data
34 // remove the shopifyProduct gid prefix from the id
35 const productId = data.selected[0].id.split("/").pop();
36 // fire request to update the product description in Gadget
37 await updateDescription({
38 id: productId,
39 wordCount,
40 });
41 });
42
43 // The AdminAction component provides an API for setting the title and actions of the Action extension wrapper.
44 return (
45 <AdminAction
46 primaryAction={
47 <Button
48 onPress={() => {
49 update();
50 close();
51 }}
52 >
53 {i18n.translate("updateDescription")}
54 </Button>
55 }
56 secondaryAction={
57 <Button
58 onPress={() => {
59 close();
60 }}
61 >
62 {i18n.translate("close")}
63 </Button>
64 }
65 loading={fetching}
66 >
67 <BlockStack gap="large">
68 <Text fontWeight="bold">{i18n.translate("welcome", { target })}</Text>
69 <NumberField label="Select a word count" value={wordCount} onChange={setWordCount} />
70 </BlockStack>
71 </AdminAction>
72 );
73}

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
1import { Banner, reactExtension } from "@shopify/ui-extensions-react/checkout";
2import { Provider, useGlobalAction } from "@gadgetinc/react";
3// import your app API client
4import { api } from "../api";
5
6// set up the Provider component so React hooks can be used
7export default reactExtension("purchase.checkout.block.render", () => (
8 <Provider api={api}>
9 <Extension />
10 </Provider>
11));
12
13function Extension() {
14 // use hooks to call your API
15 // in this case, a global action
16 const [{ data, error, fetching }, refresh] = useGlobalAction(api.myCustomGlobalAction);
17
18 if (fetching) {
19 return <Banner>Loading...</Banner>;
20 }
21
22 if (error) {
23 return <Banner>Error loading. Please try again.</Banner>;
24 }
25
26 return <Banner>{data.value}</Banner>;
27}
1import { Banner, reactExtension } from "@shopify/ui-extensions-react/checkout";
2import { Provider, useGlobalAction } from "@gadgetinc/react";
3// import your app API client
4import { api } from "../api";
5
6// set up the Provider component so React hooks can be used
7export default reactExtension("purchase.checkout.block.render", () => (
8 <Provider api={api}>
9 <Extension />
10 </Provider>
11));
12
13function Extension() {
14 // use hooks to call your API
15 // in this case, a global action
16 const [{ data, error, fetching }, refresh] = useGlobalAction(api.myCustomGlobalAction);
17
18 if (fetching) {
19 return <Banner>Loading...</Banner>;
20 }
21
22 if (error) {
23 return <Banner>Error loading. Please try again.</Banner>;
24 }
25
26 return <Banner>{data.value}</Banner>;
27}

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
1import { reactExtension, useApi } from "@shopify/ui-extensions-react/customer-account";
2import { Provider, useGadget } from "@gadgetinc/shopify-extensions/react";
3import { useFindMany } from "@gadgetinc/react";
4import { Client } from "@gadget-client/example-app";
5
6// initialize a new Client for your Gadget API
7const apiClient = new Client();
8
9// the Provider is set up in the reactExtension() initialization function
10export default reactExtension("your.extension.target", () => <GadgetUIExtension />);
11
12// component to set up the Provider with the sessionToken from Shopify
13function GadgetUIExtension() {
14const { sessionToken } = useApi();
15
16return (
17
18<Provider api={apiClient} sessionToken={sessionToken}>
19 <MyExtension />
20</Provider>
21); }
22
23function MyExtension() {
24// get the 'api' client and a 'ready' boolean from the useGadget hook
25const { api, ready } = useGadget<Client>();
26
27const [{ data, fetching, error }] = useFindMany(api.customModel, {
28// use 'ready' to pause hooks until the API client is ready to make authenticated requests
29pause: !ready,
30});
31
32// the rest of your extension component...
33}
1import { reactExtension, useApi } from "@shopify/ui-extensions-react/customer-account";
2import { Provider, useGadget } from "@gadgetinc/shopify-extensions/react";
3import { useFindMany } from "@gadgetinc/react";
4import { Client } from "@gadget-client/example-app";
5
6// initialize a new Client for your Gadget API
7const apiClient = new Client();
8
9// the Provider is set up in the reactExtension() initialization function
10export default reactExtension("your.extension.target", () => <GadgetUIExtension />);
11
12// component to set up the Provider with the sessionToken from Shopify
13function GadgetUIExtension() {
14const { sessionToken } = useApi();
15
16return (
17
18<Provider api={apiClient} sessionToken={sessionToken}>
19 <MyExtension />
20</Provider>
21); }
22
23function MyExtension() {
24// get the 'api' client and a 'ready' boolean from the useGadget hook
25const { api, ready } = useGadget<Client>();
26
27const [{ data, fetching, error }] = useFindMany(api.customModel, {
28// use 'ready' to pause hooks until the API client is ready to make authenticated requests
29pause: !ready,
30});
31
32// the rest of your extension component...
33}

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
1import { Banner, reactExtension, useApi } from "@shopify/ui-extensions-react/checkout";
2import { useState, useEffect } from "react";
3
4export default reactExtension("purchase.checkout.block.render", () => <Extension />);
5
6function Extension() {
7 // get the session token from the useApi hook
8 const { sessionToken } = useApi();
9 const [productData, setProductData] = useState(null);
10
11 useEffect(() => {
12 // Specify the GraphQL endpoint
13 const url = "https://my-extension-app--development.gadget.dev/api/graphql";
14
15 // Create a GraphQL query
16 const query = `
17 query GetOneShopifyProduct($id: GadgetID!) {
18 shopifyProduct(id: $id) {
19 title
20 }
21 }
22 `;
23
24 // get the session token
25 async function getToken() {
26 const token = await sessionToken.get();
27 return token;
28 }
29
30 // use fetch to make a POST request to the GraphQL endpoint
31 getToken().then((token) => {
32 fetch(url, {
33 method: "POST",
34 headers: {
35 "Content-Type": "application/json",
36 Accept: "application/json",
37 // pass the session token using the Authorization header
38 Authorization: `ShopifySessionToken ${token}`,
39 },
40 body: JSON.stringify({ query: query }),
41 })
42 .then((response) => response.json())
43 .then((jsonData) => {
44 // handle the returned data
45 setProductData(jsonData.data.product);
46 })
47 .catch((error) => console.error("Error:", error));
48 });
49 }, [sessionToken]);
50
51 return <Banner>{productData.title}</Banner>;
52}
1import { Banner, reactExtension, useApi } from "@shopify/ui-extensions-react/checkout";
2import { useState, useEffect } from "react";
3
4export default reactExtension("purchase.checkout.block.render", () => <Extension />);
5
6function Extension() {
7 // get the session token from the useApi hook
8 const { sessionToken } = useApi();
9 const [productData, setProductData] = useState(null);
10
11 useEffect(() => {
12 // Specify the GraphQL endpoint
13 const url = "https://my-extension-app--development.gadget.dev/api/graphql";
14
15 // Create a GraphQL query
16 const query = `
17 query GetOneShopifyProduct($id: GadgetID!) {
18 shopifyProduct(id: $id) {
19 title
20 }
21 }
22 `;
23
24 // get the session token
25 async function getToken() {
26 const token = await sessionToken.get();
27 return token;
28 }
29
30 // use fetch to make a POST request to the GraphQL endpoint
31 getToken().then((token) => {
32 fetch(url, {
33 method: "POST",
34 headers: {
35 "Content-Type": "application/json",
36 Accept: "application/json",
37 // pass the session token using the Authorization header
38 Authorization: `ShopifySessionToken ${token}`,
39 },
40 body: JSON.stringify({ query: query }),
41 })
42 .then((response) => response.json())
43 .then((jsonData) => {
44 // handle the returned data
45 setProductData(jsonData.data.product);
46 })
47 .catch((error) => console.error("Error:", error));
48 });
49 }, [sessionToken]);
50
51 return <Banner>{productData.title}</Banner>;
52}

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
1/**
2 * Extend Shopify Checkout with a custom Post Purchase user experience.
3 * This template provides two extension points:
4 *
5 * 1. ShouldRender - Called first, during the checkout process, when the
6 * payment page loads.
7 * 2. Render - If requested by `ShouldRender`, will be rendered after checkout
8 * completes
9 */
10// other imports such as React state hooks and extension components are omitted for brevity
11import React from "react";
12import { extend, render } from "@shopify/post-purchase-ui-extensions-react";
13// your app API client
14import { api } from "./api";
15
16/**
17 * Entry point for the `ShouldRender` Extension Point.
18 *
19 * Returns a value indicating whether or not to render a PostPurchase step, and
20 * optionally allows data to be stored on the client for use in the `Render`
21 * extension point.
22 */
23extend("Checkout::PostPurchase::ShouldRender", async ({ inputData, storage }) => {
24 // get the variant ids of the products in the initial purchase
25 const productVariantIds = inputData.initialPurchase.lineItems.map((lineItem) => lineItem.product.variant.id);
26
27 // make request against POST-offer route in Gadget
28 const response = await api.fetch("/offer", {
29 method: "POST",
30 headers: {
31 "Content-Type": "application/json",
32 Authorization: `Bearer ${inputData.token}`,
33 },
34 body: JSON.stringify({
35 referenceId: inputData.initialPurchase.referenceId,
36 productVariantIds,
37 }),
38 });
39
40 // get response body from route
41 const jsonResp = await response.json();
42 // save offers to extension storage
43 await storage.update({ offers: jsonResp.offers });
44
45 // For local development, always show the post-purchase page
46 return { render: true };
47});
48
49render("Checkout::PostPurchase::Render", () => <App />);
50
51export function App() {
52 // the rest of the post-purchase extension component
53 // determine what is actually rendered in this component
54}
1/**
2 * Extend Shopify Checkout with a custom Post Purchase user experience.
3 * This template provides two extension points:
4 *
5 * 1. ShouldRender - Called first, during the checkout process, when the
6 * payment page loads.
7 * 2. Render - If requested by `ShouldRender`, will be rendered after checkout
8 * completes
9 */
10// other imports such as React state hooks and extension components are omitted for brevity
11import React from "react";
12import { extend, render } from "@shopify/post-purchase-ui-extensions-react";
13// your app API client
14import { api } from "./api";
15
16/**
17 * Entry point for the `ShouldRender` Extension Point.
18 *
19 * Returns a value indicating whether or not to render a PostPurchase step, and
20 * optionally allows data to be stored on the client for use in the `Render`
21 * extension point.
22 */
23extend("Checkout::PostPurchase::ShouldRender", async ({ inputData, storage }) => {
24 // get the variant ids of the products in the initial purchase
25 const productVariantIds = inputData.initialPurchase.lineItems.map((lineItem) => lineItem.product.variant.id);
26
27 // make request against POST-offer route in Gadget
28 const response = await api.fetch("/offer", {
29 method: "POST",
30 headers: {
31 "Content-Type": "application/json",
32 Authorization: `Bearer ${inputData.token}`,
33 },
34 body: JSON.stringify({
35 referenceId: inputData.initialPurchase.referenceId,
36 productVariantIds,
37 }),
38 });
39
40 // get response body from route
41 const jsonResp = await response.json();
42 // save offers to extension storage
43 await storage.update({ offers: jsonResp.offers });
44
45 // For local development, always show the post-purchase page
46 return { render: true };
47});
48
49render("Checkout::PostPurchase::Render", () => <App />);
50
51export function App() {
52 // the rest of the post-purchase extension component
53 // determine what is actually rendered in this component
54}

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

api/routes/POST-offer.js
JavaScript
1import { RouteHandler } from "gadget-server";
2import jwt from "jsonwebtoken";
3import { getOffers } from "../utils/offerUtils";
4
5const route: RouteHandler<{
6 Body: {
7 referenceId: string;
8 productVariantIds: string[];
9 };
10}> = async ({ request, reply, api, logger, connections }) => {
11 let token = request.headers?.Authorization as string;
12 if (token?.startsWith("Bearer ")) {
13 token = token.slice(7);
14 } else {
15 // if no bearer token is present, return 401 error
16 await reply.code(401).send();
17 }
18
19 // use SHOPIFY_API_SECRET (from Partners app) as an environment variable to decode the token
20 const decodedToken = jwt.verify(token, process.env["SHOPIFY_CLIENT_SECRET"]);
21
22 // get the referenceId from the decoded token
23 const decodedReferenceId = decodedToken.input_data.initialPurchase.referenceId;
24
25 const { referenceId, productVariantIds } = request.body;
26
27 if (decodedReferenceId !== referenceId) {
28 // return error if incoming jwt is not valid
29 await reply.code(401).send();
30 }
31
32 // fetch custom offers
33 const offers = await getOffers({ api, logger, connections, productVariantIds });
34
35 // reply with the offers
36 await reply.headers({ "Content-type": "application/json" }).send({ offers });
37};
38
39export default route;
1import { RouteHandler } from "gadget-server";
2import jwt from "jsonwebtoken";
3import { getOffers } from "../utils/offerUtils";
4
5const route: RouteHandler<{
6 Body: {
7 referenceId: string;
8 productVariantIds: string[];
9 };
10}> = async ({ request, reply, api, logger, connections }) => {
11 let token = request.headers?.Authorization as string;
12 if (token?.startsWith("Bearer ")) {
13 token = token.slice(7);
14 } else {
15 // if no bearer token is present, return 401 error
16 await reply.code(401).send();
17 }
18
19 // use SHOPIFY_API_SECRET (from Partners app) as an environment variable to decode the token
20 const decodedToken = jwt.verify(token, process.env["SHOPIFY_CLIENT_SECRET"]);
21
22 // get the referenceId from the decoded token
23 const decodedReferenceId = decodedToken.input_data.initialPurchase.referenceId;
24
25 const { referenceId, productVariantIds } = request.body;
26
27 if (decodedReferenceId !== referenceId) {
28 // return error if incoming jwt is not valid
29 await reply.code(401).send();
30 }
31
32 // fetch custom offers
33 const offers = await getOffers({ api, logger, connections, productVariantIds });
34
35 // reply with the offers
36 await reply.headers({ "Content-type": "application/json" }).send({ offers });
37};
38
39export 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
1import { RouteHandler } from "gadget-server";
2import { v4 as uuidv4 } from "uuid";
3import jwt from "jsonwebtoken";
4
5const route: RouteHandler<{
6 Body: {
7 referenceId: string;
8 changes: string;
9 };
10}> = async ({ request, reply, api, logger, connections }) => {
11 // get token from headers
12 let token = request.headers?.authorization as string;
13 if (token?.startsWith("Bearer ")) {
14 token = token.slice(7);
15 } else {
16 // if no bearer token is present, return 401 error
17 await reply.code(401).send();
18 }
19
20 // use SHOPIFY_API_SECRET (from Partners app) as an environment variable to decode the token
21 const decodedToken = jwt.verify(token, process.env["SHOPIFY_CLIENT_SECRET"]);
22 const decodedReferenceId = decodedToken.input_data.initialPurchase.referenceId;
23
24 const { referenceId, changes } = request.body;
25 // compare passed in referenceId with decoded referenceId
26 if (decodedReferenceId !== referenceId) {
27 // return error if incoming jwt is not valid
28 await reply.code(401).send();
29 }
30
31 // create the payload for updating the order
32 const payload = {
33 iss: process.env["SHOPIFY_CLIENT_KEY"],
34 jti: uuidv4(),
35 iat: Date.now(),
36 sub: referenceId,
37 changes,
38 };
39
40 // sign the token and return back to the extension
41 const responseToken = jwt.sign(payload, process.env["SHOPIFY_CLIENT_SECRET"]);
42 await reply.send({ token: responseToken });
43};
44
45export default route;
1import { RouteHandler } from "gadget-server";
2import { v4 as uuidv4 } from "uuid";
3import jwt from "jsonwebtoken";
4
5const route: RouteHandler<{
6 Body: {
7 referenceId: string;
8 changes: string;
9 };
10}> = async ({ request, reply, api, logger, connections }) => {
11 // get token from headers
12 let token = request.headers?.authorization as string;
13 if (token?.startsWith("Bearer ")) {
14 token = token.slice(7);
15 } else {
16 // if no bearer token is present, return 401 error
17 await reply.code(401).send();
18 }
19
20 // use SHOPIFY_API_SECRET (from Partners app) as an environment variable to decode the token
21 const decodedToken = jwt.verify(token, process.env["SHOPIFY_CLIENT_SECRET"]);
22 const decodedReferenceId = decodedToken.input_data.initialPurchase.referenceId;
23
24 const { referenceId, changes } = request.body;
25 // compare passed in referenceId with decoded referenceId
26 if (decodedReferenceId !== referenceId) {
27 // return error if incoming jwt is not valid
28 await reply.code(401).send();
29 }
30
31 // create the payload for updating the order
32 const payload = {
33 iss: process.env["SHOPIFY_CLIENT_KEY"],
34 jti: uuidv4(),
35 iat: Date.now(),
36 sub: referenceId,
37 changes,
38 };
39
40 // sign the token and return back to the extension
41 const responseToken = jwt.sign(payload, process.env["SHOPIFY_CLIENT_SECRET"]);
42 await reply.send({ token: responseToken });
43};
44
45export 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
1<script src="https://YOUR-GADGET-DOMAIN.gadget.app/api/client/web.min.js" defer="defer"></script>
2
3<div>My theme extension content goes here!</div>
4
5{% schema %}
6{
7 "name": "My extension",
8 "target": "body",
9 "settings": []
10}
11{% 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
1document.addEventListener("DOMContentLoaded", function () {
2 // initialize an API client object
3 const myExtensionAPI = new Gadget();
4
5 const myButton = document.getElementById("my-button");
6 myButton.addEventListener("click", async () => {
7 // make a request to your app's API
8 const response = await myExtensionAPI.myDataModel.findOne("1");
9 console.log(response);
10 });
11});
1document.addEventListener("DOMContentLoaded", function () {
2 // initialize an API client object
3 const myExtensionAPI = new Gadget();
4
5 const myButton = document.getElementById("my-button");
6 myButton.addEventListener("click", async () => {
7 // make a request to your app's API
8 const response = await myExtensionAPI.myDataModel.findOne("1");
9 console.log(response);
10 });
11});

Testing extensions 

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

terminal
shopify app 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
shopify app 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?