DEV Community

Eiji Saito
Eiji Saito

Posted on

How to Build a Low-Stock Alert Dashboard in Shopify with Remix and the GraphQL Admin API

Table of Contents


Introduction

Every merchant has the same quiet fear: a best-selling product sells out on a Friday night and nobody notices until Monday. Shopify's admin shows inventory levels, but it doesn't tap you on the shoulder — and checking stock by hand doesn't scale once a catalog grows past a few dozen products.

The fix is a small embedded app: a low-stock alert dashboard that lives inside the Shopify admin, lists every product below a threshold you choose, and lets you flag those products with one click so the team can act on them.

In this tutorial, I'll build exactly that with the Remix app template and the GraphQL Admin API. You'll learn how authentication works in a modern Shopify app, how to query products and inventory, how to page through a large catalog, and how to write data back with a mutation. No storefront code is involved — everything here runs on the admin side, which makes it a good first step into Shopify app development if your previous work has been themes and Theme App Extensions.


What We'll Build

A single embedded admin page that:

  • Lists products below a stock threshold (default: 5 units), sorted by lowest stock first
  • Shows each product's total inventory, variant count, and status (active, draft, archived)
  • Pages through the entire catalog using cursor-based pagination, so it works for stores with thousands of products
  • Tags low-stock products with a low-stock tag via a mutation, so merchants can filter them in the admin or in reports
  • Respects the Admin API's cost-based rate limits, by keeping queries small and fetching only the fields we need

Prerequisites

  • Node.js 18 or later and npm
  • Shopify CLI installed (npm install -g @shopify/cli)
  • A Shopify Partner account and a development store to install the app on
  • Basic familiarity with Remix (loaders, actions, useLoaderData) and GraphQL syntax

How the GraphQL Admin API Works

The GraphQL Admin API is the current way for apps to read and write a store's back-office data: products, orders, customers, inventory, discounts, metafields, and more. The older REST Admin API has been legacy since October 2024, and new public apps have been required to use GraphQL since April 2025 — so if you're starting an app today, GraphQL is not a choice, it's the default.

A few facts worth knowing before you write your first query:

  • One endpoint per shop and API version. Every request is a POST to https://{shop}.myshopify.com/admin/api/{version}/graphql.json, with the query in a JSON body and the access token in the X-Shopify-Access-Token header. As of writing, the latest stable version is 2026-10, released October 1, 2026 and supported until at least October 1, 2027.
  • Versions ship quarterly and are named by date (2026-01, 2026-04, 2026-07, 2026-10). Each stable version is supported for at least 12 months. Pin a version in your app and bump it deliberately — never float on "latest".
  • Rate limits are cost-based, not request-based. Every query has a calculated cost, a single query can cost at most 1,000 points, and the bucket refills at a rate that depends on the store's plan: 100 points per second on Standard, 200 on Advanced, 1,000 on Shopify Plus. Requesting fewer fields costs less, which is a real reason to keep queries tight.
  • You never call this API from the browser. It needs an access token with scopes, so it belongs on the server. In the Remix template, that server code is a loader or an action.

The good news: the Remix template handles authentication for you. You almost never touch the raw endpoint or the token yourself — you call admin.graphql() and the template does the rest.


Step 1: Scaffold the Remix App

Create the app from the official template:

shopify app init
Enter fullscreen mode Exit fullscreen mode

Choose Remix when the CLI asks for a template, then start the development server:

cd low-stock-alerts
shopify app dev
Enter fullscreen mode Exit fullscreen mode

This spins up a tunnel, installs the app on your development store, and gives you a working embedded app. The template already includes session-token authentication, Prisma session storage (SQLite by default), webhook plumbing, and an extensions pipeline.

The file that matters most is app/shopify.server.ts. It configures the app:

// app/shopify.server.ts
import "@shopify/shopify-app-remix/adapters/node";
import {
  ApiVersion,
  AppDistribution,
  shopifyApp,
} from "@shopify/shopify-app-remix/server";
import { PrismaSessionStorage } from "@shopify/shopify-app-session-storage-prisma";
import prisma from "./db.server";

const shopify = shopifyApp({
  apiKey: process.env.SHOPIFY_API_KEY,
  apiSecretKey: process.env.SHOPIFY_API_SECRET || "",
  apiVersion: ApiVersion.October26,
  scopes: process.env.SCOPES?.split(","),
  appUrl: process.env.SHOPIFY_APP_URL || "",
  authPathPrefix: "/auth",
  sessionStorage: new PrismaSessionStorage(prisma),
  distribution: AppDistribution.AppStore,
  future: {
    unstable_newEmbeddedAuthStrategy: true,
  },
});

export default shopify;
export const apiVersion = ApiVersion.October26;
export const addDocumentResponseHeaders = shopify.addDocumentResponseHeaders;
export const authenticate = shopify.authenticate;
export const unauthenticated = shopify.unauthenticated;
export const login = shopify.login;
export const registerWebhooks = shopify.registerWebhooks;
export const sessionStorage = shopify.sessionStorage;
Enter fullscreen mode Exit fullscreen mode

Note apiVersion: ApiVersion.October26 — this pins the app to the 2026-10 API version. When a new quarterly version ships, you bump this constant, test, and deploy. An unpinned client silently follows Shopify's default version and can break on a rollover.


Step 2: Ask for the Right Access Scopes

The app can only read what the merchant grants it. For a stock dashboard we need read access to products:

# shopify.app.toml
scopes = "read_products, write_products"
Enter fullscreen mode Exit fullscreen mode

read_products covers the product and inventory queries. write_products is needed only because Step 5 writes a tag back to the product — if you skip the tagging feature, read_products alone is enough. Ask for the minimum your app actually uses: merchants notice over-broad scope requests, and Shopify reviews them.

After changing scopes, run shopify app dev again and re-install the app on your development store so the new scopes take effect.


Step 3: Query Products and Inventory

The core of the dashboard is a products query. In a Remix route, data loading happens in a loader, and authentication is one line:

// app/routes/app._index.tsx
import type { LoaderFunctionArgs } from "react-router";
import { json } from "react-router";
import { useLoaderData } from "react-router";
import { authenticate } from "../shopify.server";

const LOW_STOCK_QUERY = `#graphql
  query LowStockProducts($first: Int!, $after: String) {
    products(first: $first, after: $after, sortKey: TITLE) {
      nodes {
        id
        title
        status
        totalInventory
        variants(first: 5) {
          nodes {
            id
            title
            inventoryQuantity
          }
        }
      }
      pageInfo {
        hasNextPage
        endCursor
      }
    }
  }
`;

export const loader = async ({ request }: LoaderFunctionArgs) => {
  const { admin } = await authenticate.admin(request);

  const response = await admin.graphql(LOW_STOCK_QUERY, {
    variables: { first: 50 },
  });
  const { data } = await response.json();

  return json({ products: data.products.nodes });
};

export default function Index() {
  const { products } = useLoaderData<typeof loader>();
  // Render the dashboard from `products` — see Step 6.
  return null;
}
Enter fullscreen mode Exit fullscreen mode

What is happening here:

  • authenticate.admin(request) verifies the session token Shopify App Bridge sends with the request, exchanges it for an API access token for that shop, and hands you an authenticated admin client. You never see the token.
  • admin.graphql() sends the query to the versioned endpoint pinned in shopify.server.ts.
  • The #graphql comment tag is not decoration — the template's tooling uses it to validate your query against the Admin API schema and to give you autocomplete in your editor.
  • totalInventory is the sum of inventory across all of a product's variants, which is exactly the number a low-stock check needs. Asking for variants(first: 5) as well lets the dashboard show which variants are low, not just the product total.

Keep the query narrow on purpose. Every field you request adds to the query's cost against the rate-limit bucket, and a dashboard that asks for descriptions, images, and SEO fields it never renders is paying for data it throws away.


Step 4: Paginate Through the Whole Catalog

first: 50 fetches one page. A store with 2,000 products needs forty pages, and the Admin API uses cursor-based pagination: each response tells you whether another page exists (pageInfo.hasNextPage) and where it starts (pageInfo.endCursor). You pass that cursor back as the after variable:

// app/routes/app._index.tsx — inside the loader
const THRESHOLD = 5;

async function fetchAllProducts(admin: AdminApiContext) {
  const all: Product[] = [];
  let cursor: string | null = null;

  do {
    const response = await admin.graphql(LOW_STOCK_QUERY, {
      variables: { first: 50, after: cursor },
    });
    const { data } = await response.json();
    all.push(...data.products.nodes);
    cursor = data.products.pageInfo.hasNextPage
      ? data.products.pageInfo.endCursor
      : null;
  } while (cursor);

  return all;
}

export const loader = async ({ request }: LoaderFunctionArgs) => {
  const { admin } = await authenticate.admin(request);
  const products = await fetchAllProducts(admin);
  const lowStock = products.filter((p) => p.totalInventory <= THRESHOLD);
  return json({ lowStock, threshold: THRESHOLD });
};
Enter fullscreen mode Exit fullscreen mode

Two practical notes:

  • Filter in your code, not in the query. The products connection supports a query argument with search syntax (for example inventory_total:<=5), but filtering after the fetch keeps the logic visible and testable, and lets you change the threshold without touching the query. For very large catalogs, move the filter into the query argument to save cost.
  • Fifty products per page is a reasonable default. Larger pages cost more per query, and a single query can cost at most 1,000 points. If you raise first toward the 250 maximum, check the response's extensions.cost field to see what you are actually spending.

Step 5: Flag Low-Stock Products with a Mutation

Reading data is only half the job. The dashboard should also let a merchant flag a low-stock product so it shows up in admin filters and reports. That is a mutation — GraphQL's way of writing data:

// app/routes/app._index.tsx
import type { ActionFunctionArgs } from "react-router";

const TAG_PRODUCT_MUTATION = `#graphql
  mutation TagLowStockProduct($input: ProductInput!) {
    productUpdate(input: $input) {
      product {
        id
        tags
      }
      userErrors {
        field
        message
      }
    }
  }
`;

export const action = async ({ request }: ActionFunctionArgs) => {
  const { admin } = await authenticate.admin(request);
  const formData = await request.formData();
  const productId = formData.get("productId") as string;
  const currentTags = (formData.get("tags") as string) || "";

  const tags = [...new Set([...currentTags.split(", "), "low-stock"])];

  const response = await admin.graphql(TAG_PRODUCT_MUTATION, {
    variables: {
      input: { id: productId, tags },
    },
  });
  const { data } = await response.json();

  if (data.productUpdate.userErrors.length > 0) {
    return json(
      { error: data.productUpdate.userErrors[0].message },
      { status: 400 },
    );
  }
  return json({ ok: true });
};
Enter fullscreen mode Exit fullscreen mode

Three things to notice:

  • Mutations return userErrors, not HTTP errors. A failed mutation usually still answers with HTTP 200, and the problem is reported in userErrors on the payload. Always check that field — treating a 200 as success is one of the most common Admin API bugs.
  • The input type is ProductInput. It takes the product's global ID (gid://shopify/Product/123...) — the same id the query returned — plus the fields to change. Passing the full tag list (existing tags plus low-stock) replaces the tags, so include the current ones or you will wipe them.
  • This runs in an action, not a loader. Loaders read, actions write. That split is a Remix convention, and it maps cleanly onto the GraphQL split between queries and mutations.

Step 6: Build the Dashboard Page

The template ships with Polaris, Shopify's admin design system, so the page can look native to the admin with very little CSS. A minimal version renders the low-stock list and a "Tag as low-stock" button per row:

// app/routes/app._index.tsx
import { useLoaderData, useFetcher } from "react-router";
import { Page, Card, DataTable, Button, Badge } from "@shopify/polaris";

export default function Index() {
  const { lowStock, threshold } = useLoaderData<typeof loader>();
  const fetcher = useFetcher();

  const rows = lowStock.map((product) => [
    product.title,
    product.totalInventory,
    <Badge tone={product.totalInventory === 0 ? "critical" : "warning"}>
      {product.totalInventory === 0 ? "Out of stock" : "Low stock"}
    </Badge>,
    <fetcher.Form method="post">
      <input type="hidden" name="productId" value={product.id} />
      <Button submit>Tag as low-stock</Button>
    </fetcher.Form>,
  ]);

  return (
    <Page title="Low-stock alerts">
      <Card>
        <DataTable
          columnContentTypes={["text", "numeric", "text", "text"]}
          headings={["Product", "Inventory", "Status", ""]}
          rows={rows}
        />
      </Card>
    </Page>
  );
}
Enter fullscreen mode Exit fullscreen mode

useFetcher submits the form to the route's action without a page reload, so tagging a product feels instant. The threshold (5 units) can later become a merchant setting stored in a metafield or your own database — for a first version, a constant is fine.


Rate Limits: What to Watch Out For

The dashboard above is cheap to run, but keep these rules in mind as it grows:

  • Watch extensions.cost in responses. Every Admin API response carries the query's actual cost and the remaining budget. Log it during development so a "small" change to a query doesn't quietly triple its cost.
  • Don't refetch the whole catalog on every page load. Cache the product list server-side for a few minutes, or move the threshold filter into the query argument (query: "inventory_total:<=5") so Shopify does the filtering and you only pay for the rows you display.
  • Mutations are also costed. Tagging fifty products one at a time costs fifty mutations. For bulk work, look at bulk operations — an async pattern where you submit one bulk query or mutation and download the results as a JSONL file. That is the right tool once a dashboard turns into a sync job.
  • Five bulk operations can run at once per shop per app, so queue them rather than firing them in parallel.

Tips and Common Pitfalls

  • Global IDs, not numeric IDs. The Admin API returns IDs like gid://shopify/Product/123456789. Pass them back exactly as returned — stripping the prefix or using the old numeric ID will fail.
  • Check userErrors on every mutation. A 200 response does not mean the write worked.
  • Request only the fields you render. Query cost is calculated from the fields you ask for, so a lean query is literally cheaper.
  • Scopes must match the code. A query that reads products fails with an access error if read_products isn't in shopify.app.toml and granted on install. When a query fails, check scopes before debugging the query itself.
  • Pin the API version and bump it quarterly. A new version ships every three months; test against the release candidate before the old version's support window ends.
  • Never call the Admin API from the browser. The access token must stay on the server. If a component needs admin data, load it in a loader.

Conclusion

A low-stock dashboard is a small app, but it touches every piece of real Shopify app development: session-token authentication, the versioned GraphQL Admin API, cursor pagination, mutations with userErrors, and Polaris for an admin-native UI. The same pattern — authenticate, query narrowly, paginate, mutate carefully — covers most of what an embedded app does, whether the next feature is an order report, a customer segment, or a discount generator.

Start from the Remix template, keep your queries lean, and let the API's cost system guide you toward fetching only what the page actually shows.


References

Top comments (0)