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.

An example of a post-purchase upsell page presented to a customer

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.

Fork on Gadget

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!

The default Shopify CLI app embedded in a store Admin page. It gives you a button to add test 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.

Diagram of the tech stack used in this tutorial. Gadget handling sync and custom routing, Shopify handling the store and frontend

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.

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 on Apps link in Shopify Partners Dashboard
  • Click the Create App button
Click on Create app button
  • Click the Create app manually button
Shopify's app creation landing page in the Partners Dashboard
  • Go to the Connections page in your Gadget app
The Gadget homescreen, with the Connections link highlighted
  • 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
  • Paste the copied URLs into the 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.

Gadget's scope selection page, with the Product read/write scopes selected, along wiht 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.

The button you can use to create a new route file in Gadget

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.

JavaScript
1/**
2 * Route handler for GET https://testing-out-post-purchase-stuff.gadget.app/offer
3 *
4 * @param { import("gadget-server").Request } request - incoming request data
5 * @param { import("gadget-server").Reply } reply - reply for customizing and sending a response
6 *
7 * @see {@link https://www.fastify.io/docs/latest/Reference/Request}
8 * @see {@link https://www.fastify.io/docs/latest/Reference/Reply}
9 */
10
11function defaultResponse(reply) {
12 // empty response as a default - post-purchase upsell page will be empty
13 reply.send({});
14}
15
16module.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 Extension
25 const { inputData } = body;
26
27 // get ids of variants that are in the purchase
28 const purchaseIds = inputData.initialPurchase.lineItems.map(
29 (lineItem) => lineItem.product.variant.id
30 );
31
32 // use Gadget's findMany api and filter for variants being offered at a discount that are not included in the shoppers original purchase
33 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 });
49
50 // 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 list
53 const randomVariant = Math.floor(Math.random() * (variants.length - 1));
54 const variant = variants[randomVariant];
55 const { product } = variant;
56
57 // get single image for product to be presented on upsell page
58 const productImages = await request.api.shopifyProductImage.findMany({
59 filter: {
60 product: {
61 equals: product?.id,
62 },
63 },
64 });
65
66 // grab first image for this product
67 const productImage = productImages[0];
68
69 // format data to be consumed by Shopify demo frontend application
70 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 };
78
79 // send product variant as a response to be offered to shopper
80 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:

JavaScript
1const 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.

JavaScript
1/**
2 * Route handler for GET https://testing-out-post-purchase-stuff.gadget.app/sign-changeset
3 *
4 * @param { import("gadget-server").Request } request - incoming request data
5 * @param { import("gadget-server").Reply } reply - reply for customizing and sending a response
6 *
7 * @see {@link https://www.fastify.io/docs/latest/Reference/Request}
8 * @see {@link https://www.fastify.io/docs/latest/Reference/Reply}
9 */
10
11const jwt = require("jsonwebtoken");
12const { v4: uuidv4 } = require("uuid");
13
14module.exports = async (request, reply) => {
15 const decodedToken = jwt.verify(
16 request.body.token,
17 process.env.SHOPIFY_API_SECRET
18 );
19 const decodedReferenceId = decodedToken.input_data.initialPurchase.referenceId;
20
21 if (decodedReferenceId !== request.body.referenceId) {
22 reply.status(400);
23 }
24
25 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 };
32
33 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.

View of the package.json file with added dependencies

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 menu users can click on to be brought to Gadget's environment variables page

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!

The environment variables page with the SHOPIFY_API_KEY and SHOPIFY_API_SECRET entered

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:

JavaScript
1const FastifyCors = require("fastify-cors");
2
3module.exports = async (server) => {
4 await server.register(FastifyCors, {
5 // allow CORS requests from any origin
6 // you should configure this to be domain specific for production applications
7 origin: ["*"],
8 // only allow POST requests
9 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:

The final file explorer with all custom routes and CORS handling files created

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!):
JavaScript
1const 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.

JavaScript
1const {
2 variantId,
3 productTitle,
4 productImageURL,
5 productDescription,
6 originalPrice, // <-- add this field
7 discountedPrice, // <-- add this field
8} = storage.initialData;
9
10const changes = [{ type: "add_variant", variantId, quantity: 1 }];
11
12// Extract values from the calculated purchase
13const 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 fields
20// .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!