Build a post-purchase upsell app backend with Gadget
Time to build: ~1 hour
Technical Requirements
Before starting this tutorial you need the following:
Post-purchase upsell applications are a great way for merchants to increase sales by presenting shoppers with a one-click option to add additional items to their purchases. There are countless different strategies to pick between when determining what products a merchant wants to push for an upsell opportunity: it might be products that are related or frequently bought together with the products that the customer has already bought, it could be an item that the merchant is particularly interested in selling, or it could just be an item that is on sale.

The logic required to determine what products are presented to users is the interesting part of a post-purchase upsell application. But to get to the point where you are writing this business logic code, you need to go through the process of setting up a server and ensuring that it will be able to scale to handle potentially high traffic.
Using Gadget, this tutorial shows you how to skip the boilerplate server work and brings you directly to writing your post-purchase upsell logic.
You can fork this Gadget project and try it out yourself.
You still need to set up the Shopify Post-purchase Extension, add environment variables, and complete the application frontend.
Set up Shopify App Bridge Extension
Good news! Shopify already has a tutorial that covers setting up a new frontend application using the Shopify App Bridge Extension.
You should go through the entire first page of their tutorial. It will help you set up a front-end application on a development store and allows you to inject a post-purchase upsell page into your checkout workflow.
The index.jsx
code file that Shopify creates may require an additional import statement! If you see any React errors in your web
console, adding import React from "react";
at the top of your code file should be the fix!
Once your Shopify CLI app is up and running, Shopify gives you a button in your store Admin to add test products to your store automatically. Add some products!

You should also make sure your products are enabled and visible in your store, and that some products are being offered at a discounted price. To offer some products at a discount, fill in the Compare at price and Price fields on a product. You can also add some test products manually.
Do not proceed until you have the frontend of Shopify's post-purchase extension demo working!
Once you have completed the first portion of the Shopify tutorial, move on to the Upsell example. Your Gadget app will replace the Node server that you set up in Part 2: Build an app server.

This Gadget application will sync product data with your development store. This product data will be used along with and custom routing endpoints to determine what product will be offered to a shopper.
Create a new Shopify Connection
You will want the development store's Product Variant data in your Gadget app, so you need to set up a new Shopify Connection.
Connect to Shopify through the Partners dashboard
Requirements
To complete this connection, you will need a Shopify Partners account as well as a store or development store
Our first step is going to be setting up a custom Shopify application in the Partners dashboard.
- Go to the Shopify Partners dashboard
- Click on the link to the Apps page
Both the Shopify store Admin and the Shopify Partner Dashboard have an Apps section. Ensure that you are on the Shopify Partner Dashboard before continuing.

- Click the Create App button

- Click the Create app manually button

- Go to the Connections page in your Gadget app

- Copy the App URL and Allowed redirection URL
- Enter a name for your Custom Shopify app
- Paste the App URL and Allowed redirection URL from the Gadget Connections page into the Shopify app
- Click Create app to finish creating your custom Shopify app
- Click the Create app button at the top of the page
- Copy the API key and API secret key from your newly created Shopify app and paste the values into the Gadget connections page
- Click Connect

Now we get to select what Shopify scopes we give our application access to, while also picking what Shopify data models we want to import into our Gadget app.
You require the Product Read and Write scopes, and want to import the Product, Product Image, and Product Variant models.

We have successfully created our connection!
Set up Gadget routing
Shopify's upsell tutorial has you set up a local Node server to test out the post-purchase upsell frontend. You will replace this server with a Gadget app!
There are 3 things you need to add to your Gadget app to get it up and running:
- a custom route to handle the
/offer
request - a custom route to handle the
/sign-changeset
request - custom configuration to handle CORS
Custom route for /offer
The first thing you want to do is set up the /offer
route. This route will accept a payload from the frontend app, determine what product will be presented as part of the post-purchase upsell, and then return the product variant information required to render on the frontend.
Go to the Gadget file explorer and add a new file in the routes
folder.

You can then rename the auto-generated file to POST-offer.js
. Custom routes in Gadget need to be prepended with one of the accepted Fastify request types. The remainder of the file name is the path of the route! You can read more information about creating custom routes in the Gadget documentation.
You are going to pass information from the post-purchase Shopify App Bridge Extension to our Gadget app. This information includes the line items the customer is purchasing, as well as the total price of the order. You can use this information to determine what kind of offer you want to present to the customer. For this tutorial, you will select a random product variant that is not included as part of the original purchase and is being discounted to offer the customer.
Paste the following code snippet into your POST-offer.js
file.
JavaScript1/**2 * Route handler for GET https://testing-out-post-purchase-stuff.gadget.app/offer3 *4 * @param { import("gadget-server").Request } request - incoming request data5 * @param { import("gadget-server").Reply } reply - reply for customizing and sending a response6 *7 * @see {@link https://www.fastify.io/docs/latest/Reference/Request}8 * @see {@link https://www.fastify.io/docs/latest/Reference/Reply}9 */1011function defaultResponse(reply) {12 // empty response as a default - post-purchase upsell page will be empty13 reply.send({});14}1516module.exports = async (request, reply) => {17 /**18 * This is where the fun begins!19 *20 * Find product variants in the store that are being offered at a discount and cost less than the total of the original purchase, then recommend them as a post-purchase offer.21 */22 const { body } = request;23 if (body) {24 // get the purchase information from the Shopify App Bridge Extension25 const { inputData } = body;2627 // get ids of variants that are in the purchase28 const purchaseIds = inputData.initialPurchase.lineItems.map(29 (lineItem) => lineItem.product.variant.id30 );3132 // use Gadget's findMany api and filter for variants being offered at a discount that are not included in the shoppers original purchase33 const variants = await request.api.shopifyProductVariant.findMany({34 filter: {35 AND: [36 {37 compareAtPrice: {38 isSet: true,39 },40 },41 {42 id: {43 notIn: purchaseIds,44 },45 },46 ],47 },48 });4950 // only present an offer if there are variants that meet the criteria (cheaper than initial purchase and on sale)51 if (variants.length > 0) {52 // pick a random variant from the list53 const randomVariant = Math.floor(Math.random() * (variants.length - 1));54 const variant = variants[randomVariant];55 const { product } = variant;5657 // get single image for product to be presented on upsell page58 const productImages = await request.api.shopifyProductImage.findMany({59 filter: {60 product: {61 equals: product?.id,62 },63 },64 });6566 // grab first image for this product67 const productImage = productImages[0];6869 // format data to be consumed by Shopify demo frontend application70 const initialData = {71 variantId: parseInt(variant.id),72 productTitle: product?.title,73 productImageURL: productImage?.source,74 productDescription: product?.body?.split(/<br.*?>/),75 originalPrice: variant.compareAtPrice,76 discountedPrice: variant.price,77 };7879 // send product variant as a response to be offered to shopper80 reply.send(initialData);81 } else {82 defaultResponse(reply);83 }84 } else {85 defaultResponse(reply);86 }87};
This file uses the Gadget API to call shopifyProductVariant.findMany()
and then applies a filter condition to get product variants that are on sale and not included in the original purchase:
JavaScript1const variants = await request.api.shopifyProductVariant.findMany({2 filter: {3 AND: [4 {5 compareAtPrice: {6 isSet: true,7 },8 },9 {10 id: {11 notIn: purchaseIds,12 },13 },14 ],15 },16});
Notice that the Gadget API is available through the request parameter.
You then select a random variant and return it to the frontend. This is the business logic code. You can replace this code when writing a custom post-purchase upsell application.
Custom route for /sign-changeset
If the customer chooses to purchase the product presented to them in the post-purchase upsell window, you need to modify the original order. Another route is needed to authenticate this transaction - Shopify requires a signed JWT to proceed. It is best to handle this with another custom route.
Create another new file in our routes
folder and call it POST-sign-changeset.js
.
Paste the following code snippet to respond to requests to this endpoint with a signed JWT. This code is almost identical to the server example provided in the Shopify tutorial.
JavaScript1/**2 * Route handler for GET https://testing-out-post-purchase-stuff.gadget.app/sign-changeset3 *4 * @param { import("gadget-server").Request } request - incoming request data5 * @param { import("gadget-server").Reply } reply - reply for customizing and sending a response6 *7 * @see {@link https://www.fastify.io/docs/latest/Reference/Request}8 * @see {@link https://www.fastify.io/docs/latest/Reference/Reply}9 */1011const jwt = require("jsonwebtoken");12const { v4: uuidv4 } = require("uuid");1314module.exports = async (request, reply) => {15 const decodedToken = jwt.verify(16 request.body.token,17 process.env.SHOPIFY_API_SECRET18 );19 const decodedReferenceId = decodedToken.input_data.initialPurchase.referenceId;2021 if (decodedReferenceId !== request.body.referenceId) {22 reply.status(400);23 }2425 const payload = {26 iss: process.env.SHOPIFY_API_KEY,27 jti: uuidv4(),28 iat: Date.now(),29 sub: request.body.referenceId,30 changes: request.body.changes,31 };3233 const token = jwt.sign(payload, process.env.SHOPIFY_API_SECRET);34 reply.send({ token });35};
This will allow the original order to be modified successfully. But first, you need to import the jsonwebtoken
and uuid
modules and provide the SHOPIFY_API_KEY
and SHOPIFY_API_SECRET
environment variables required by our snippet.
Load npm modules
To be able to run this snippet you need to import some modules in the package.json
file: jsonwebtoken
and uuid
. To load these modules in your Gadget application, open the package.json
file in the file explorer and add them as dependencies:
json"jsonwebtoken": "^8.5.1","uuid": "^8.3.2"
Click the Run yarn button in the top right of package.json
window to import the packages.

The status page that opens will let you know when the yarn install process is complete.
Add environment variables
To add environment variables in Gadget, go to Settings -> Environment variables in the navigation bar.

The SHOPIFY_API_KEY
and SHOPIFY_API_SECRET
can be found in your Shopify Partners Dashboard. Make sure to grab the keys for the custom frontend application you set up, not the keys generated for your Gadget app!

Our POST-sign-changeset.js
snippet is already set up to read environment variables. You can access them in Gadget the same way you would access them in any other Node project: process.env.<ENVIRONMENT_VARIABLE_NAME>
.
Those are the only two routes required for a post-purchase upsell app! Now you just need to enable cross-origin requests so that our tunnelled local frontend can retrieve information from our Gadget app.
Handle CORS
Gadget's custom routes are built on top of Fastify. This means you can use Fastify plugins such as fastify/cors
to customize your routing. You can read more about extending route functionality in Gadget in our documentation.
To add the fastify-cors
module to our Gadget application, open the package.json
file and add it as a dependency: "fastify-cors": "^6.0.3"
.
Click the Run yarn button in the top right of package.json
window to import the package.
Now you need to add a file that handles the injection of Fastify plugins into our router. Create a new file in the routes
folder and call it +scope.js
. Then paste the following snippet in the file:
JavaScript1const FastifyCors = require("fastify-cors");23module.exports = async (server) => {4 await server.register(FastifyCors, {5 // allow CORS requests from any origin6 // you should configure this to be domain specific for production applications7 origin: ["*"],8 // only allow POST requests9 methods: ["POST"],10 });11};
This allows for cross-origin requests from Shopify, our backend Gadget app should now be reachable!
Need a different flavour of CORS handling for your custom app? Check out our docs for more details on how you can handle CORS settings.
Your Gadget file explorer should now look like this:

Complete application frontend
Our Gadget app is finished! Now you can continue with the Shopify tutorial starting back at Step 3: Update the extension code and finish setting up our application extension frontend. There are tweaks you need to make to the provided Shopify frontend code:
- replace the
postPurchaseOffer
fetch request with the following snippet to change the/offers
request to a POST, allowing you to send inputData to your Gadget app in the request body (make sure to replace the placeholder URL with the URL of your Gadget app!):
JavaScript1const postPurchaseOffer = await fetch("https://<gadget-app-name>.gadget.app/offer", {2 method: "POST",3 headers: {4 "Content-Type": "application/json",5 },6 body: JSON.stringify({ inputData }),7}).then((res) => res.json());
replace the default URL for the
/sign-changeset
request with the URL for your Gadget app (for example:https://post-purchase-demo.gadget.app/sign-changeset
)the current Shopify demo is not making use of the returned originalPrice and purchasePrice; you can comment out the below snippets and instead include these fields as part of the
storage.inputData
destructuring.
JavaScript1const {2 variantId,3 productTitle,4 productImageURL,5 productDescription,6 originalPrice, // <-- add this field7 discountedPrice, // <-- add this field8} = storage.initialData;910const changes = [{ type: "add_variant", variantId, quantity: 1 }];1112// Extract values from the calculated purchase13const shipping =14 calculatedPurchase?.addedShippingLines[0]?.priceSet?.presentmentMoney?.amount;15const taxes =16 calculatedPurchase?.addedTaxLines[0]?.priceSet?.presentmentMoney?.amount;17const total = calculatedPurchase?.totalOutstandingSet.presentmentMoney.amount;18// const discountedPrice =19// calculatedPurchase?.updatedLineItems[0].totalPriceSet.presentmentMoney <-- comment out these fields20// .amount;21// const originalPrice =22// calculatedPurchase?.updatedLineItems[0].priceSet.presentmentMoney.amount;
Try it out!
And you're done, congrats!
If you simulate a fake purchase in our Shopify store, you should now be redirected to the post-purchase upsell screen before our purchase summary. And choosing to purchase the offered product will add it to the order.
You can use this as a template for writing your own post-purchase upsell application. All you need to do is replace the business logic in the POST-offer.js
file with your custom code!