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.
- In your local terminal, run the
ggt dev
command replacing<YOUR APP DOMAIN>
to pull down your app to your local machine:
terminalggt 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.
cd
into your project, and open it in an editor.- Add the following
workspaces
andtrustedDependencies
to yourpackage.json
:
package.jsonjson{"workspaces": ["extensions/*"],"trustedDependencies": ["@shopify/plugin-cloudflare"]}
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:
terminalyarn add -W <package>
This is required by Yarn workspaces to ensure that all packages are installed in the correct location.
- Add a
.ignore
file to the root of your project. - Add the following to both
.ignore
(and.gitignore
if you are using source control):
add to .ignore and .gitignoreextensions/*/distextensions/*/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.
- Use the Shopify CLI to generate your checkout UI extension:
terminalshopify app generate extension
The following steps are for admin, checkout, or customer account extensions. For theme app extensions, see the theme app extensions section.
- Select the same Partner app and development store you used to connect to Shopify when prompted by Shopify's CLI.
- 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.
- Start your extension development server by running:
terminalshopify app dev
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.jsxJavaScriptimport { 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.
- Install the
@gadgetinc/react
package:
terminalyarn add @gadgetinc/react
- Set up the
Provider
in your extension by wrapping the exported extension component or app with theProvider
component and passing in your API client instance:
1import { Provider } from "@gadgetinc/react";2import { api } from "./api";34export default reactExtension(TARGET, () => (5 <Provider api={api}>6 <App />7 </Provider>8));
1import { Provider } from "@gadgetinc/react";2import { api } from "./api";34export 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:
1import { useCallback, useState } from "react";2import { reactExtension, useApi, AdminAction, BlockStack, Button, Text, NumberField } from "@shopify/ui-extensions-react/admin";3// import app API client4import { api } from "./api";5import { Provider, useAction } from "@gadgetinc/react";67// 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";910// set up the Provider component so React hooks can be used11export default reactExtension(TARGET, () => (12 <Provider api={api}>13 <App />14 </Provider>15));1617function 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);2526 const [wordCount, setWordCount] = useState("100");2728 // custom action in Gadget that updates the product description29 // using OpenAI to generate a description based on the word count and product images30 const [_, updateDescription] = useAction(api.shopifyProduct.updateDescription);3132 const update = useCallback(async () => {33 // get current product id from data34 // remove the shopifyProduct gid prefix from the id35 const productId = data.selected[0].id.split("/").pop();36 // fire request to update the product description in Gadget37 await updateDescription({38 id: productId,39 wordCount,40 });41 });4243 // The AdminAction component provides an API for setting the title and actions of the Action extension wrapper.44 return (45 <AdminAction46 primaryAction={47 <Button48 onPress={() => {49 update();50 close();51 }}52 >53 {i18n.translate("updateDescription")}54 </Button>55 }56 secondaryAction={57 <Button58 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 client4import { api } from "./api";5import { Provider, useAction } from "@gadgetinc/react";67// 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";910// set up the Provider component so React hooks can be used11export default reactExtension(TARGET, () => (12 <Provider api={api}>13 <App />14 </Provider>15));1617function 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);2526 const [wordCount, setWordCount] = useState("100");2728 // custom action in Gadget that updates the product description29 // using OpenAI to generate a description based on the word count and product images30 const [_, updateDescription] = useAction(api.shopifyProduct.updateDescription);3132 const update = useCallback(async () => {33 // get current product id from data34 // remove the shopifyProduct gid prefix from the id35 const productId = data.selected[0].id.split("/").pop();36 // fire request to update the product description in Gadget37 await updateDescription({38 id: productId,39 wordCount,40 });41 });4243 // The AdminAction component provides an API for setting the title and actions of the Action extension wrapper.44 return (45 <AdminAction46 primaryAction={47 <Button48 onPress={() => {49 update();50 close();51 }}52 >53 {i18n.translate("updateDescription")}54 </Button>55 }56 secondaryAction={57 <Button58 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:
1import { Banner, reactExtension } from "@shopify/ui-extensions-react/checkout";2import { Provider, useGlobalAction } from "@gadgetinc/react";3// import your app API client4import { api } from "../api";56// set up the Provider component so React hooks can be used7export default reactExtension("purchase.checkout.block.render", () => (8 <Provider api={api}>9 <Extension />10 </Provider>11));1213function Extension() {14 // use hooks to call your API15 // in this case, a global action16 const [{ data, error, fetching }, refresh] = useGlobalAction(api.myCustomGlobalAction);1718 if (fetching) {19 return <Banner>Loading...</Banner>;20 }2122 if (error) {23 return <Banner>Error loading. Please try again.</Banner>;24 }2526 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 client4import { api } from "../api";56// set up the Provider component so React hooks can be used7export default reactExtension("purchase.checkout.block.render", () => (8 <Provider api={api}>9 <Extension />10 </Provider>11));1213function Extension() {14 // use hooks to call your API15 // in this case, a global action16 const [{ data, error, fetching }, refresh] = useGlobalAction(api.myCustomGlobalAction);1718 if (fetching) {19 return <Banner>Loading...</Banner>;20 }2122 if (error) {23 return <Banner>Error loading. Please try again.</Banner>;24 }2526 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:
terminalyarn 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:
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";56// initialize a new Client for your Gadget API7const apiClient = new Client();89// the Provider is set up in the reactExtension() initialization function10export default reactExtension("your.extension.target", () => <GadgetUIExtension />);1112// component to set up the Provider with the sessionToken from Shopify13function GadgetUIExtension() {14const { sessionToken } = useApi();1516return (1718<Provider api={apiClient} sessionToken={sessionToken}>19 <MyExtension />20</Provider>21); }2223function MyExtension() {24// get the 'api' client and a 'ready' boolean from the useGadget hook25const { api, ready } = useGadget<Client>();2627const [{ data, fetching, error }] = useFindMany(api.customModel, {28// use 'ready' to pause hooks until the API client is ready to make authenticated requests29pause: !ready,30});3132// 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";56// initialize a new Client for your Gadget API7const apiClient = new Client();89// the Provider is set up in the reactExtension() initialization function10export default reactExtension("your.extension.target", () => <GadgetUIExtension />);1112// component to set up the Provider with the sessionToken from Shopify13function GadgetUIExtension() {14const { sessionToken } = useApi();1516return (1718<Provider api={apiClient} sessionToken={sessionToken}>19 <MyExtension />20</Provider>21); }2223function MyExtension() {24// get the 'api' client and a 'ready' boolean from the useGadget hook25const { api, ready } = useGadget<Client>();2627const [{ data, fetching, error }] = useFindMany(api.customModel, {28// use 'ready' to pause hooks until the API client is ready to make authenticated requests29pause: !ready,30});3132// 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:
1import { Banner, reactExtension, useApi } from "@shopify/ui-extensions-react/checkout";2import { useState, useEffect } from "react";34export default reactExtension("purchase.checkout.block.render", () => <Extension />);56function Extension() {7 // get the session token from the useApi hook8 const { sessionToken } = useApi();9 const [productData, setProductData] = useState(null);1011 useEffect(() => {12 // Specify the GraphQL endpoint13 const url = "https://my-extension-app--development.gadget.dev/api/graphql";1415 // Create a GraphQL query16 const query = `17 query GetOneShopifyProduct($id: GadgetID!) {18 shopifyProduct(id: $id) {19 title20 }21 }22 `;2324 // get the session token25 async function getToken() {26 const token = await sessionToken.get();27 return token;28 }2930 // use fetch to make a POST request to the GraphQL endpoint31 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 header38 Authorization: `ShopifySessionToken ${token}`,39 },40 body: JSON.stringify({ query: query }),41 })42 .then((response) => response.json())43 .then((jsonData) => {44 // handle the returned data45 setProductData(jsonData.data.product);46 })47 .catch((error) => console.error("Error:", error));48 });49 }, [sessionToken]);5051 return <Banner>{productData.title}</Banner>;52}
1import { Banner, reactExtension, useApi } from "@shopify/ui-extensions-react/checkout";2import { useState, useEffect } from "react";34export default reactExtension("purchase.checkout.block.render", () => <Extension />);56function Extension() {7 // get the session token from the useApi hook8 const { sessionToken } = useApi();9 const [productData, setProductData] = useState(null);1011 useEffect(() => {12 // Specify the GraphQL endpoint13 const url = "https://my-extension-app--development.gadget.dev/api/graphql";1415 // Create a GraphQL query16 const query = `17 query GetOneShopifyProduct($id: GadgetID!) {18 shopifyProduct(id: $id) {19 title20 }21 }22 `;2324 // get the session token25 async function getToken() {26 const token = await sessionToken.get();27 return token;28 }2930 // use fetch to make a POST request to the GraphQL endpoint31 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 header38 Authorization: `ShopifySessionToken ${token}`,39 },40 body: JSON.stringify({ query: query }),41 })42 .then((response) => response.json())43 .then((jsonData) => {44 // handle the returned data45 setProductData(jsonData.data.product);46 })47 .catch((error) => console.error("Error:", error));48 });49 }, [sessionToken]);5051 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:
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 the6 * payment page loads.7 * 2. Render - If requested by `ShouldRender`, will be rendered after checkout8 * completes9 */10// other imports such as React state hooks and extension components are omitted for brevity11import React from "react";12import { extend, render } from "@shopify/post-purchase-ui-extensions-react";13// your app API client14import { api } from "./api";1516/**17 * Entry point for the `ShouldRender` Extension Point.18 *19 * Returns a value indicating whether or not to render a PostPurchase step, and20 * 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 purchase25 const productVariantIds = inputData.initialPurchase.lineItems.map((lineItem) => lineItem.product.variant.id);2627 // make request against POST-offer route in Gadget28 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 });3940 // get response body from route41 const jsonResp = await response.json();42 // save offers to extension storage43 await storage.update({ offers: jsonResp.offers });4445 // For local development, always show the post-purchase page46 return { render: true };47});4849render("Checkout::PostPurchase::Render", () => <App />);5051export function App() {52 // the rest of the post-purchase extension component53 // determine what is actually rendered in this component54}
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 the6 * payment page loads.7 * 2. Render - If requested by `ShouldRender`, will be rendered after checkout8 * completes9 */10// other imports such as React state hooks and extension components are omitted for brevity11import React from "react";12import { extend, render } from "@shopify/post-purchase-ui-extensions-react";13// your app API client14import { api } from "./api";1516/**17 * Entry point for the `ShouldRender` Extension Point.18 *19 * Returns a value indicating whether or not to render a PostPurchase step, and20 * 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 purchase25 const productVariantIds = inputData.initialPurchase.lineItems.map((lineItem) => lineItem.product.variant.id);2627 // make request against POST-offer route in Gadget28 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 });3940 // get response body from route41 const jsonResp = await response.json();42 // save offers to extension storage43 await storage.update({ offers: jsonResp.offers });4445 // For local development, always show the post-purchase page46 return { render: true };47});4849render("Checkout::PostPurchase::Render", () => <App />);5051export function App() {52 // the rest of the post-purchase extension component53 // determine what is actually rendered in this component54}
And your Gadget POST-offer
HTTP route could look like:
1import { RouteHandler } from "gadget-server";2import jwt from "jsonwebtoken";3import { getOffers } from "../utils/offerUtils";45const 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 error16 await reply.code(401).send();17 }1819 // use SHOPIFY_API_SECRET (from Partners app) as an environment variable to decode the token20 const decodedToken = jwt.verify(token, process.env["SHOPIFY_CLIENT_SECRET"]);2122 // get the referenceId from the decoded token23 const decodedReferenceId = decodedToken.input_data.initialPurchase.referenceId;2425 const { referenceId, productVariantIds } = request.body;2627 if (decodedReferenceId !== referenceId) {28 // return error if incoming jwt is not valid29 await reply.code(401).send();30 }3132 // fetch custom offers33 const offers = await getOffers({ api, logger, connections, productVariantIds });3435 // reply with the offers36 await reply.headers({ "Content-type": "application/json" }).send({ offers });37};3839export default route;
1import { RouteHandler } from "gadget-server";2import jwt from "jsonwebtoken";3import { getOffers } from "../utils/offerUtils";45const 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 error16 await reply.code(401).send();17 }1819 // use SHOPIFY_API_SECRET (from Partners app) as an environment variable to decode the token20 const decodedToken = jwt.verify(token, process.env["SHOPIFY_CLIENT_SECRET"]);2122 // get the referenceId from the decoded token23 const decodedReferenceId = decodedToken.input_data.initialPurchase.referenceId;2425 const { referenceId, productVariantIds } = request.body;2627 if (decodedReferenceId !== referenceId) {28 // return error if incoming jwt is not valid29 await reply.code(401).send();30 }3132 // fetch custom offers33 const offers = await getOffers({ api, logger, connections, productVariantIds });3435 // reply with the offers36 await reply.headers({ "Content-type": "application/json" }).send({ offers });37};3839export 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:
1import { RouteHandler } from "gadget-server";2import { v4 as uuidv4 } from "uuid";3import jwt from "jsonwebtoken";45const route: RouteHandler<{6 Body: {7 referenceId: string;8 changes: string;9 };10}> = async ({ request, reply, api, logger, connections }) => {11 // get token from headers12 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 error17 await reply.code(401).send();18 }1920 // use SHOPIFY_API_SECRET (from Partners app) as an environment variable to decode the token21 const decodedToken = jwt.verify(token, process.env["SHOPIFY_CLIENT_SECRET"]);22 const decodedReferenceId = decodedToken.input_data.initialPurchase.referenceId;2324 const { referenceId, changes } = request.body;25 // compare passed in referenceId with decoded referenceId26 if (decodedReferenceId !== referenceId) {27 // return error if incoming jwt is not valid28 await reply.code(401).send();29 }3031 // create the payload for updating the order32 const payload = {33 iss: process.env["SHOPIFY_CLIENT_KEY"],34 jti: uuidv4(),35 iat: Date.now(),36 sub: referenceId,37 changes,38 };3940 // sign the token and return back to the extension41 const responseToken = jwt.sign(payload, process.env["SHOPIFY_CLIENT_SECRET"]);42 await reply.send({ token: responseToken });43};4445export default route;
1import { RouteHandler } from "gadget-server";2import { v4 as uuidv4 } from "uuid";3import jwt from "jsonwebtoken";45const route: RouteHandler<{6 Body: {7 referenceId: string;8 changes: string;9 };10}> = async ({ request, reply, api, logger, connections }) => {11 // get token from headers12 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 error17 await reply.code(401).send();18 }1920 // use SHOPIFY_API_SECRET (from Partners app) as an environment variable to decode the token21 const decodedToken = jwt.verify(token, process.env["SHOPIFY_CLIENT_SECRET"]);22 const decodedReferenceId = decodedToken.input_data.initialPurchase.referenceId;2324 const { referenceId, changes } = request.body;25 // compare passed in referenceId with decoded referenceId26 if (decodedReferenceId !== referenceId) {27 // return error if incoming jwt is not valid28 await reply.code(401).send();29 }3031 // create the payload for updating the order32 const payload = {33 iss: process.env["SHOPIFY_CLIENT_KEY"],34 jti: uuidv4(),35 iat: Date.now(),36 sub: referenceId,37 changes,38 };3940 // sign the token and return back to the extension41 const responseToken = jwt.sign(payload, process.env["SHOPIFY_CLIENT_SECRET"]);42 await reply.send({ token: responseToken });43};4445export 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:
- 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.liquidliquid1<script src="https://YOUR-GADGET-DOMAIN.gadget.app/api/client/web.min.js" defer="defer"></script>23<div>My theme extension content goes here!</div>45{% schema %}6{7 "name": "My extension",8 "target": "body",9 "settings": []10}11{% endschema %}
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
- Create a file in
extensions/your-extension-name/assets
, and initialize the API client:
1document.addEventListener("DOMContentLoaded", function () {2 // initialize an API client object3 const myExtensionAPI = new Gadget();45 const myButton = document.getElementById("my-button");6 myButton.addEventListener("click", async () => {7 // make a request to your app's API8 const response = await myExtensionAPI.myDataModel.findOne("1");9 console.log(response);10 });11});
1document.addEventListener("DOMContentLoaded", function () {2 // initialize an API client object3 const myExtensionAPI = new Gadget();45 const myButton = document.getElementById("my-button");6 myButton.addEventListener("click", async () => {7 // make a request to your app's API8 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:
terminalshopify 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:
terminalshopify 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.