Skip to content
Tutorials Center
My learning

Topics

Lesson 49 of 55 ยท Real-World Projects

Project: Low-Stock Alerts App

Build a Shopify low-stock alerts app: inventory webhooks, thresholds stored in metafields, a notification queue with digests, and a runnable alert engine.

Merchants hate two things about stock: running out of a best seller, and finding out too late. Shopify has no built-in "tell me when a variant drops below N" rule that fits every shop, which makes it a good first app idea. In this project you design a small Low-Stock Alerts app: it listens to inventory webhooks, compares the new quantity with a threshold the merchant chose, and sends a short digest instead of a flood of messages.

The real app code (TOML, a webhook route, GraphQL, a settings page) cannot run on this site, so it is shown read-only. The decision logic is separate pure JavaScript, and that part is a runnable stand-in: the same rules, fed with hand-made events instead of Shopify. The lesson tells you at each step which is which. Examples target Admin GraphQL API version 2026-07; check the current version list before you copy anything, because Shopify releases a new one every quarter (see API Versioning and Deprecations).

What you will build

flowchart LR
  S["Shopify<br/>inventory changes"] -->|"inventory_levels/update"| W["Webhook route<br/>verify + enqueue"]
  W --> E["Alert engine<br/>threshold + state"]
  M["Metafield settings<br/>threshold, ignore list"] --> E
  E -->|"alert"| Q["Notification queue"]
  Q --> D["Digest sender<br/>email or Slack"]

The webhook route stays tiny. The engine decides; the queue and digest keep the merchant from being spammed.

The app has four moving parts:

  1. A subscription to inventory webhooks.
  2. A settings page where the merchant picks a default threshold and per-product overrides, saved in metafields.
  3. An alert engine that decides when a change is worth an alert.
  4. A notification queue that groups alerts into digests and retries failures.

Step 1: scopes and webhook subscription

The app needs to read inventory and product names, nothing else. Least privilege matters for review (Managed Installation and Access Scopes). In shopify.app.toml:

TOML
[access_scopes]
scopes = "read_inventory,read_products"

[webhooks]
api_version = "2026-07"

  [[webhooks.subscriptions]]
  topics = ["inventory_levels/update"]
  uri = "/webhooks/inventory"

  [[webhooks.subscriptions]]
  topics = ["app/uninstalled"]
  uri = "/webhooks/app-uninstalled"

The inventory_levels/update topic fires when the available quantity of one inventory item at one location changes. The payload is small and contains ids, not names. Roughly:

JSON
{
  "inventory_item_id": 271878346596884000,
  "location_id": 24826418,
  "available": 4,
  "updated_at": "2026-10-30T09:15:00-04:00",
  "admin_graphql_api_id": "gid://shopify/InventoryLevel/..."
}

Treat the exact field list as something to confirm in the webhook reference for your API version. What you can rely on is the idea: the event says which item, which location, what quantity, when. The product title you want in the email is not in it, so the app later asks the Admin API.

Step 2: the webhook route

The route does only what Reliable Webhook Handlers recommends: authenticate, store, answer quickly. In the React Router app template it looks like this (read-only, not runnable here):

JavaScript
// app/routes/webhooks.inventory.jsx
import { authenticate } from "../shopify.server";
import db from "../db.server";

export const action = async ({ request }) => {
  const { shop, topic, payload } = await authenticate.webhook(request);
  const webhookId = request.headers.get("X-Shopify-Webhook-Id");

  await db.inventoryEvent.upsert({
    where: { webhookId },
    create: {
      webhookId,
      shop,
      itemId: String(payload.inventory_item_id),
      locationId: String(payload.location_id),
      available: payload.available,
      updatedAt: new Date(payload.updated_at),
    },
    update: {},
  });

  return new Response(null, { status: 200 });
};

authenticate.webhook checks the HMAC signature (you implement the same check yourself in Verifying Webhook Signatures). The upsert on the webhook id makes duplicates harmless, a rule from Idempotency: Shopify can deliver the same event more than once. A background worker then reads new rows and runs the engine.

Step 3: the alert rules

Before writing code, write the rules in words. A naive rule such as "alert whenever available is below 5" sends a message on every sale while stock is low. That is the quickest way to get your app uninstalled. Better rules:

  • Alert on crossing. Send one alert when stock goes from above the threshold to at or below it. Do not alert again until it has recovered above the threshold (this is called re-arming).
  • Per-item override. A rare, expensive item may need a threshold of 1; a cheap bulk item may need 50.
  • Ignore list. Digital goods and made-to-order items should never alert.
  • Ignore stale events. Webhooks can arrive out of order, so an event older than the last one you processed for that item and location must be dropped.
  • Out of stock is different. Zero deserves its own, louder alert type.

This is inventory thinking applied to notifications. The engine below implements exactly these rules. It is a stand-in: it takes plain objects, not Shopify requests, so you can test it with no store. The real app calls the same function from the background worker.

Node.js The alert engine: crossing, overrides, stale events

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Read the output against the rules. The second tee event alerts, the third does not (still low), the late t=4 event is dropped as stale, and the rare item alerts only at its own threshold of 1. Note what is deliberately simple: the key is per item and location. A real merchant might want the sum across locations; that is a settings choice you can add by keeping a total per item.

Step 4: merchant settings in metafields

Where does the threshold live? You have two choices: your own database table keyed by shop, or metafields. Metafields on the shop or app installation travel with the store and are readable from extensions and functions, which a database row is not. For a settings object, an app-owned metafield on the app installation is a common choice, because the $app namespace is private to your app.

Saving the settings page (read-only code, GraphQL against API 2026-07):

JavaScript
// app/routes/app._index.jsx (action excerpt)
const { admin } = await authenticate.admin(request);

const installation = await admin.graphql(`#graphql
  query { currentAppInstallation { id } }`);
const installationId = (await installation.json()).data.currentAppInstallation.id;

const response = await admin.graphql(
  `#graphql
  mutation SaveSettings($metafields: [MetafieldsSetInput!]!) {
    metafieldsSet(metafields: $metafields) {
      metafields { id key }
      userErrors { field message code }
    }
  }`,
  {
    variables: {
      metafields: [{
        ownerId: installationId,
        namespace: "$app:alerts",
        key: "settings",
        type: "json",
        value: JSON.stringify({ defaultThreshold: 5, overrides: {}, ignored: [] }),
      }],
    },
  },
);
const { data } = await response.json();
if (data.metafieldsSet.userErrors.length) {
  return { errors: data.metafieldsSet.userErrors };
}

Always check userErrors; a request can return HTTP 200 and still have failed (Mutations and userErrors). Validate on the server too: the threshold must be an integer between 0 and some sensible maximum, and the ignore list must contain ids that belong to this shop. A settings page that trusts the browser is a security bug.

If the page needs to be fast, cache the parsed settings per shop in your database and refresh them when the merchant saves. The worker should not call the Admin API for every webhook.

Step 5: names for the email

The alert says "item 271878346596884000 is low", which means nothing to a merchant. Resolve the id to a product with one GraphQL query, using a global ID built from the numeric one:

JavaScript
const response = await admin.graphql(`#graphql
  query ItemName($id: ID!) {
    inventoryItem(id: $id) {
      sku
      variant { displayName product { title handle } }
    }
  }`, { variables: { id: `gid://shopify/InventoryItem/${itemId}` } });

Look names up only when an alert fires, not for every event; most events produce no alert, so this keeps you far inside the rate limits. For an offline job like this (there is no logged-in user), the worker uses an offline access token, explained in Online vs Offline Tokens.

Step 6: the notification queue and digest

Imagine a flash sale: fifty variants cross their thresholds in two minutes. Fifty emails are noise; one email listing fifty variants is useful. So alerts do not go out directly; they go into a queue, and a sender drains it on a schedule, grouping by shop. The sender must also survive a failing email provider: it retries with growing delays and gives up after a limit, then records the failure so the merchant can see it.

The stand-in below uses a fake clock and a fake sender that fails twice, so the output is the same every run.

Node.js A digest queue with retries

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Both shops get one message each rather than one per event, the flaky shop's digest is retried with a doubling delay (10, then 20 time units), and the late "Sticker pack" alert waits for its own window. In production the clock is real time, the batches live in a database table or a Redis queue so a restart loses nothing (Monitoring, Logging and Scaling covers workers with backpressure), and the delays are minutes, not units.

Step 7: uninstall cleanup

When a merchant uninstalls, Shopify sends app/uninstalled and revokes your access token. Delete the shop's sessions, settings cache and queued alerts, and keep only what you are legally allowed to keep. Shopify also sends the mandatory privacy webhooks, covered in Privacy, GDPR and Mandatory Webhooks. An app that keeps emailing a shop after uninstall will get reported.

Ideas for extensions

  • Alert on the sum across locations, and let the merchant choose which locations count.
  • Use days of cover (stock divided by average daily sales) instead of a fixed number, which needs an orders query (Orders, Customers and Protected Data).
  • Reconcile once a night with a bulk operation that lists every inventory level, because webhooks can be missed.
  • Offer a "snooze this product" button that writes to the ignore list.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why should the engine alert when stock crosses the threshold instead of whenever the quantity is at or below it?

    Alerting on every low reading sends a message per sale. A crossing rule sends one alert, then re-arms when stock recovers above the threshold.
  2. 2. What is the purpose of keeping the last seen timestamp per item and location?

    Webhook deliveries can arrive late or out of order. An older event must not overwrite or retrigger newer state.
  3. 3. Where is a good place to store the merchant's threshold settings if extensions might need to read them?

    Metafields travel with the shop and can be read by extensions and functions. A cached copy in your database keeps the worker from calling the API per webhook.
  4. 4. Why group alerts into a digest queue instead of sending each one immediately?

    Batching turns fifty events into one useful message, and a queue lets you retry a failing provider without losing alerts.

Summary

  • Subscribe to inventory_levels/update in shopify.app.toml, verify the signature, store the event idempotently and answer quickly.
  • Decide with pure, testable rules: alert on crossing, re-arm on recovery, allow overrides and an ignore list, drop stale events, treat zero separately.
  • Keep merchant settings in an app-owned metafield ($app namespace), write them with metafieldsSet, and check userErrors and server-side validation.
  • Resolve ids to names only when an alert fires, using an offline token in the background worker.
  • Queue alerts, group them into digests, retry with backoff, and clean up on uninstall.

Next, build a function that changes prices at checkout in Project: Tiered Volume Discount.