Skip to content

Search docs

Jump between documentation pages.

Browse docs

Integrate Shopify with DaloyJS

Shopify is the commerce platform behind millions of stores. This guide uses the community shopify-api-node SDK (maintained by MONEI) to call the Shopify Admin API from a DaloyJS plugin, and verifies Shopify webhooks against the raw request body with the core verifyWebhookSignature().

REST is legacy: use GraphQL

Shopify made the REST Admin API a legacy API as of October 1, 2024, and since April 1, 2025 new public apps must be built exclusively on the GraphQL Admin API. The REST resources on shopify-api-node (shopify.product.list, shopify.order.create, and so on) still exist, but write new code against the SDK's shopify.graphql() method. Every example below uses GraphQL.

Pin apiVersion to a current stable release. Shopify ships a new version every quarter and supports each for about a year; at the time of writing the latest stable version is 2026-10. Check the versioning page when you upgrade. Do not rely on the SDK's default version.

1. Create the app and get a token

Shopify changed how custom apps are created. Per the Shopify changelog, since January 1, 2026 you can no longer create new custom apps in the Shopify admin. Create the app in the Dev Dashboard instead, then install it on your store.

  1. In Shopify's Dev Dashboard, create an app and choose the Admin API access scopes it needs (for example read_products, write_orders). Stay minimal.
  2. Install the app on the store and note its client ID and client secret.
  3. For a server-side integration with stores in your own Shopify organization, exchange those credentials for an access token with the client credentials grant. These tokens expire after 24 hours, so the plugin below refreshes them. For stores outside your organization, use token exchange or the authorization code grant (the official @shopify/shopify-api library implements both).

2. Install

bash
pnpm add shopify-api-node

The package ships its own typings (under types/), so no @types/shopify-api-node install is needed.

3. Environment variables

.envbash
SHOPIFY_SHOP=acme-test.myshopify.com
SHOPIFY_CLIENT_ID=replace_me
SHOPIFY_CLIENT_SECRET=replace_me      # also the webhook HMAC key
SHOPIFY_API_VERSION=2026-10

Shopify signs webhooks with the app's client secret, so the same secret that obtains tokens also verifies deliveries. Treat it as a production credential.

4. Plugin

src/plugins/shopify.tsts
import Shopify from "shopify-api-node";
import { resilientFetch, verifyWebhookSignature } from "@daloyjs/core";
import type { App } from "@daloyjs/core";

const shop = process.env.SHOPIFY_SHOP!;
const apiVersion = process.env.SHOPIFY_API_VERSION ?? "2026-10";
const tokenFetch = resilientFetch({ timeoutMs: 10_000, retries: 0 });

let cached: { client: Shopify; expiresAt: number } | null = null;

// Client credentials grant: tokens last 24 hours, so refresh a few minutes early.
async function getShopify(): Promise<Shopify> {
  if (cached && Date.now() < cached.expiresAt - 5 * 60_000) return cached.client;
  const res = await tokenFetch(`https://${shop}/admin/oauth/access_token`, {
    method: "POST",
    headers: { "content-type": "application/x-www-form-urlencoded" },
    body: new URLSearchParams({
      grant_type: "client_credentials",
      client_id: process.env.SHOPIFY_CLIENT_ID!,
      client_secret: process.env.SHOPIFY_CLIENT_SECRET!,
    }),
  });
  if (!res.ok) throw new Error(`Shopify token request failed: ${res.status}`);
  const { access_token, expires_in } = (await res.json()) as { access_token: string; expires_in: number };
  const client = new Shopify({
    shopName: shop,
    accessToken: access_token,
    apiVersion,
    maxRetries: 5, // retry 429s using Shopify's throttle data; mutually exclusive with autoLimit
    timeout: 30_000,
  });
  cached = { client, expiresAt: Date.now() + expires_in * 1000 };
  return client;
}

export interface ShopifyClient {
  graphql<TData = unknown>(query: string, variables?: Record<string, unknown>): Promise<TData>;
  verifyWebhook(headers: Headers, rawBody: Uint8Array): Promise<{
    ok: boolean;
    topic: string | null;
    shop: string | null;
    webhookId: string | null;
  }>;
}

// Exported so job handlers (which run outside a request) can use it too.
export const shopifyClient: ShopifyClient = {
  async graphql(query, variables) {
    const shopify = await getShopify();
    return shopify.graphql(query, variables) as Promise<never>;
  },

  async verifyWebhook(headers, rawBody) {
    const hmac = headers.get("x-shopify-hmac-sha256");
    const ok =
      !!hmac &&
      (await verifyWebhookSignature({
        payload: rawBody,
        signature: hmac, // base64 HMAC-SHA256 of the raw body
        secret: process.env.SHOPIFY_CLIENT_SECRET!,
        algorithm: "sha256",
      }));
    return {
      ok,
      topic: headers.get("x-shopify-topic"),
      shop: headers.get("x-shopify-shop-domain"),
      webhookId: headers.get("x-shopify-webhook-id"),
    };
  },
};

// Call with the root app, not through app.register(): a decoration made
// inside a registered plugin is visible only to that plugin's own routes.
export function shopifyPlugin(app: App) {
  app.decorate("shopify", shopifyClient);
}

declare module "@daloyjs/core" {
  interface AppState {
    shopify: ShopifyClient;
  }
}

With a legacy shpat_ token, replace getShopify() with a single new Shopify({ shopName, accessToken, apiVersion, maxRetries: 5 }). To surface throttle pressure to your metrics, listen to the client's callGraphqlLimits event.

5. Query products with GraphQL

src/routes/catalog.tsts
import { z } from "zod";
import { shopifyPlugin } from "../plugins/shopify.ts";

shopifyPlugin(app);

const ProductsQuery = /* GraphQL */ `
  query Products($first: Int!, $after: String) {
    products(first: $first, after: $after) {
      pageInfo { hasNextPage endCursor }
      edges {
        node {
          id
          title
          handle
          status
          priceRangeV2 {
            minVariantPrice { amount currencyCode }
          }
        }
      }
    }
  }
`;

app.get(
  "/catalog/products",
  {
    operationId: "listShopifyProducts",
    request: {
      query: z.object({
        first: z.coerce.number().int().min(1).max(50).default(20),
        after: z.string().max(512).optional(),
      }),
    },
    responses: {
      200: {
        description: "Page of products",
        body: z.object({
          products: z.array(z.object({
            id: z.string(),
            title: z.string(),
            handle: z.string(),
            status: z.string(),
            price: z.object({ amount: z.string(), currency: z.string() }),
          })),
          nextCursor: z.string().nullable(),
        }),
      },
    },
  },
  async ({ query, state }) => {
    const data = await state.shopify.graphql<{
      products: {
        pageInfo: { hasNextPage: boolean; endCursor: string | null };
        edges: Array<{ node: {
          id: string; title: string; handle: string; status: string;
          priceRangeV2: { minVariantPrice: { amount: string; currencyCode: string } };
        } }>;
      };
    }>(ProductsQuery, { first: query.first, after: query.after ?? null });

    return {
      status: 200,
      body: {
        products: data.products.edges.map((e) => ({
          id: e.node.id,
          title: e.node.title,
          handle: e.node.handle,
          status: e.node.status,
          price: {
            amount: e.node.priceRangeV2.minVariantPrice.amount,
            currency: e.node.priceRangeV2.minVariantPrice.currencyCode,
          },
        })),
        nextCursor: data.products.pageInfo.hasNextPage ? data.products.pageInfo.endCursor : null,
      },
    };
  },
);

GraphQL pagination uses opaque cursors (endCursor). Forward the cursor as a query string to your client.

6. Receive and verify webhooks

Webhook verification
ShopifyDaloyJS routeJob worker
  1. 01requestShopifyDaloyJS routePOST /webhooks/shopifyX-Shopify-Hmac-SHA256 over raw body
  2. 02noteDaloyJS routeDaloyJS routeverifyWebhookSignature with the client secretbase64 HMAC-SHA256, constant-time compare
  3. 03responseDaloyJS routeShopify401 when the signature does not match{ error: 'invalid signature' }
  4. 04asyncDaloyJS routeJob workerenqueue keyed by X-Shopify-Webhook-Id, then 200ack well inside the 5 s budget
Hash the raw bytes before parsing, reject bad signatures with 401, dedupe atomically on X-Shopify-Webhook-Id through the job idempotency key, then ack fast and do the heavy work in the worker.

Shopify signs every HTTPS webhook with X-Shopify-Hmac-SHA256, a base64 HMAC-SHA256 of the raw body keyed with your app's client secret. Dedupe on X-Shopify-Webhook-Id, which identifies one delivery. Do not dedupe on X-Shopify-Event-Id: it is shared by every delivery that one merchant action produced (several subscriptions to the same topic each get their own webhook id but the same event id), so it is a correlation id, not a dedupe key. The route follows the shared webhook pattern:

src/webhooks/shopify.tsts
import { z } from "zod";
import { readBodyLimited, jobIdempotencyKey } from "@daloyjs/core";

app.post(
  "/webhooks/shopify",
  {
    operationId: "shopifyWebhook",
    // No body schema: we hash bytes before parsing.
    responses: {
      200: { description: "ack", body: z.object({ ok: z.literal(true) }) },
      401: { description: "bad signature", body: z.object({ error: z.string() }) },
    },
  },
  async ({ request, state }) => {
    const raw = await readBodyLimited(request, 1_048_576);
    const result = await state.shopify.verifyWebhook(request.headers, raw);
    if (!result.ok) return { status: 401, body: { error: "invalid signature" } };
    if (!result.webhookId || !result.topic) return { status: 200, body: { ok: true as const } };

    await app.jobs!.enqueue({
      name: "shopify.webhook",
      // Keep the payload small; the worker re-reads current state over GraphQL.
      payload: { webhookId: result.webhookId, topic: result.topic, shop: result.shop },
      idempotencyKey: jobIdempotencyKey({ name: "shopify.webhook", key: result.webhookId }),
    });
    return { status: 200, body: { ok: true as const } };
  },
);

If the worker needs the payload itself (for example the order id on orders/paid), parse it with safeJsonParse() after verification and put only the ids into the job payload.

Shopify uses a one-second connection timeout and a five-second timeout for the whole request, and treats any non-2xx (including redirects) as a failure. It retries a failed delivery 8 times over the next 4 hours, and a subscription created through the Admin API is deleted after 8 consecutive failures. Deliveries are not ordered; use X-Shopify-Triggered-At or the payload's updated_at when order matters. See Shopify's webhook best practices.

Rate limits

The GraphQL Admin API uses a calculated cost and leaky-bucket model. Use the maxRetries option (above) so the SDK respects the throttle information that comes back on 429 responses. autoLimit only applies to the REST API and only inside a single process, so skip it for GraphQL or multi-instance deployments.

Runtimes

shopify-api-node is built on got, which depends on Node's HTTP stack. It runs on Node hosts (long-lived Node, Vercel Node.js functions, AWS Lambda, Azure Functions), but not on Cloudflare Workers or Vercel Edge. On those runtimes, call the Admin GraphQL endpoint directly with fetch; the webhook verification above already uses only core WebCrypto helpers:

ts
// edge-friendly fallback
const res = await fetch(`https://${shop}/admin/api/${apiVersion}/graphql.json`, {
  method: "POST",
  headers: { "Content-Type": "application/json", "X-Shopify-Access-Token": accessToken },
  body: JSON.stringify({ query, variables }),
});

Alternatives

Shopify also publishes the official @shopify/shopify-api library (15.x, Node 22+), which implements OAuth, token exchange, session storage, and a webhook registry for public and embedded apps. Reach for it when you build an App Store app or need to act on stores outside your organization. Reach for shopify-api-node when you build a server-side integration for your own store and want a smaller surface.

See also the payments overview, problem+json errors, and distributed rate-limit store.

Edit this page on GitHub

Last updated