To connect an app built with Lovable, Bolt, Cursor or Claude Code to a Shopify store, create a custom app in Shopify's Dev Dashboard, give it only the access scopes it needs, and call the GraphQL Admin API from a server function, never from the browser. Orders come in through HMAC-verified webhooks and are read with the orders query; stock changes go out through the inventory mutations, which since API version 2026-04 require an idempotency key. This guide shows each step in TypeScript, with the November 2026 rules for versions, rate limits and IP allowlists.
Every detail below comes from shopify.dev as of November 2026, when the latest stable API version is 2026-10.
Custom app or public app: which do you need?
- Custom app. Built for one merchant. It installs on a single store, on several stores of the same Plus organization, or on development stores. It can't use Shopify's app billing. This is what you want when your own app (a portal, an internal tool, a B2B ordering app) needs to talk to your own store.
- Public app. Installed by many merchants, listed on the Shopify App Store, reviewed by Shopify and bound by extra requirements. Build it with Shopify CLI.
Shopify's distribution docs say apps can no longer be created through the Shopify admin; existing admin-created apps keep working. New custom apps are created in the Dev Dashboard: Create app → Start from Dev Dashboard, then create a version with your access scopes and Webhooks API version, release it, and install it on the store.
How does authentication work for a custom app?
Your server sends an access token in the X-Shopify-Access-Token header. How you get that token depends on where the store lives:
- Store in your own Shopify organization (it appears under the same org in the Dev Dashboard): use the client credentials grant. Your server exchanges the app's Client ID and Client secret for a token. No redirect flow. Tokens expire after 24 hours, so cache and refresh them. You won't see the token in the Shopify admin.
- Store outside your organization (for example a client's store): choose Custom distribution, generate an install link for that store, and authenticate with the authorization code grant (app outside the Shopify admin) or token exchange (embedded app). Shopify CLI handles this for you. The client credentials grant returns
shop_not_permittedhere.
IP allowlist. From 20 November 2026 a custom app needs an IP allowlist before it can be installed on a store outside your organization, and from 1 January 2027 every such existing install needs one too. Shopify recommends it for in-organization apps as well. Requests from outside the list fail with 403. Serverless platforms have changing IPs, so Shopify suggests allowing your hosting provider's ASNs, narrowed to the countries you run in. See IP allowlist.
Scopes. Ask for the minimum: for this guide read_orders, read_products, read_inventory and write_inventory. By default only the last 60 days of orders are accessible; older orders need approved read_all_orders access. Protected customer data (names, emails, addresses) needs approval too. When you add scopes in a new app version, the merchant must approve them before your token carries them.
// Client credentials grant (app and store in the same organization)
const SHOP = Deno.env.get('SHOPIFY_SHOP')!; // "your-store", without .myshopify.com
let token: string | null = null;
let tokenExpiresAt = 0;
async function getToken(): Promise<string> {
if (token && Date.now() < tokenExpiresAt - 60_000) return token;
const res = await fetch(`https://${SHOP}.myshopify.com/admin/oauth/access_token`, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({
grant_type: 'client_credentials',
client_id: Deno.env.get('SHOPIFY_CLIENT_ID')!,
client_secret: Deno.env.get('SHOPIFY_CLIENT_SECRET')!,
}),
});
if (!res.ok) throw new Error(`Token request failed: ${res.status}`);
const { access_token, expires_in } = await res.json(); // expires_in is 86399
token = access_token;
tokenExpiresAt = Date.now() + expires_in * 1000;
return token!;
}Do not send a scope parameter: Shopify ignores it, and the token carries whatever scopes the store granted. Read the scope field in the response to see them.
GraphQL or REST Admin API?
GraphQL. The REST Admin API has been legacy since 1 October 2024, and since 1 April 2025 all new public apps must use the GraphQL Admin API only. AI tools trained on older examples often generate REST calls like /admin/api/.../orders.json; ask for GraphQL instead.
Which API version should you pin?
Shopify releases a version every quarter and supports each stable version for at least 12 months (versioning). At the time of writing the supported stable versions are 2026-01, 2026-04, 2026-07 and 2026-10 (latest), with 2027-01 as release candidate. The version is part of the URL. If you request an unsupported version, Shopify falls forward to the oldest supported one, which can change behaviour silently; the X-Shopify-API-Version response header tells you what you got. Put the version in one constant and plan an upgrade every few quarters. Webhook payloads use the Webhooks API version set on your app version, not the one in your request URL.
A GraphQL client that respects rate limits
GraphQL rate limits are cost-based (rate limits). Each app-and-store pair has a bucket that refills at a rate set by the store's plan: 100 points per second on standard plans, 200 on Advanced, 1,000 on Plus and 2,000 on Shopify for enterprise. A single query may not cost more than 1,000 points, and array inputs are capped at 250 items. Every response reports its cost under extensions.cost.
const API_VERSION = '2026-10';
export async function shopifyGraphQL(query: string, variables: Record<string, unknown> = {}) {
for (let attempt = 0; attempt < 5; attempt++) {
const res = await fetch(`https://${SHOP}.myshopify.com/admin/api/${API_VERSION}/graphql.json`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Shopify-Access-Token': await getToken(),
},
body: JSON.stringify({ query, variables }),
});
if (res.status === 429) { await sleep(1000 * (attempt + 1)); continue; }
if (!res.ok) throw new Error(`Shopify HTTP ${res.status}`);
const json = await res.json();
const cost = json.extensions?.cost;
if (json.errors?.length) {
// If the bucket is short of points, wait for it to refill and retry.
const status = cost?.throttleStatus;
if (status && status.currentlyAvailable < cost.requestedQueryCost) {
const waitMs = ((cost.requestedQueryCost - status.currentlyAvailable) / status.restoreRate) * 1000;
await sleep(Math.max(waitMs, 1000));
continue;
}
throw new Error(`Shopify GraphQL errors: ${JSON.stringify(json.errors)}`);
}
return json.data;
}
throw new Error('Shopify: gave up after repeated throttling');
}
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));Note that mutation problems such as invalid input come back in each mutation's userErrors, not in top-level errors. Always check both.
How do you read orders?
Use the orders query with cursor pagination and a search filter. To sync incrementally, sort by UPDATED_AT and filter on updated_at since your last run:
const ORDERS_QUERY = `
query Orders($cursor: String, $query: String) {
orders(first: 50, after: $cursor, query: $query, sortKey: UPDATED_AT) {
pageInfo { hasNextPage endCursor }
nodes {
id
name
createdAt
updatedAt
displayFinancialStatus
displayFulfillmentStatus
totalPriceSet { shopMoney { amount currencyCode } }
lineItems(first: 50) {
nodes { title sku quantity variant { id inventoryItem { id } } }
}
}
}
}`;
export async function fetchOrdersUpdatedSince(isoDate: string) {
const all = [];
let cursor: string | null = null;
do {
const data = await shopifyGraphQL(ORDERS_QUERY, {
cursor,
query: `updated_at:>'${isoDate}'`,
});
all.push(...data.orders.nodes);
cursor = data.orders.pageInfo.hasNextPage ? data.orders.pageInfo.endCursor : null;
} while (cursor);
return all;
}Only request fields you use: each field adds to the query cost. Customer fields such as email fall under protected customer data and need approval.
How do you update inventory safely?
Shopify tracks stock per inventory item (one per variant) per location. First find the IDs:
const LOOKUP = `
query Lookup($sku: String!, $locationId: ID!) {
productVariants(first: 1, query: $sku) {
nodes {
id
sku
inventoryItem {
id
inventoryLevel(locationId: $locationId) {
quantities(names: ["available"]) { name quantity }
}
}
}
}
}`;
// Location IDs: query { locations(first: 10) { nodes { id name } } }
const data = await shopifyGraphQL(LOOKUP, { sku: `sku:${sku}`, locationId });Then choose the mutation:
inventorySetQuantitiessets an absolute number. Shopify says to use it only when your system is the source of truth for stock.inventoryAdjustQuantitiesapplies a delta, for example-2after a sale in another channel. Use it otherwise.
Since API version 2026-04, both need two safety features. An idempotency key through the @idempotent directive, so a retried request is applied once. And a changeFromQuantity per item: the update only happens if the current stored quantity matches it, otherwise you get a CHANGE_FROM_QUANTITY_STALE error (compare-and-swap). Passing null opts out, which Shopify discourages.
const SET_QTY = `
mutation SetQty($input: InventorySetQuantitiesInput!, $idempotencyKey: String!) {
inventorySetQuantities(input: $input) @idempotent(key: $idempotencyKey) {
inventoryAdjustmentGroup { reason changes { name delta quantityAfterChange } }
userErrors { code field message }
}
}`;
export async function setAvailable(opts: {
inventoryItemId: string; locationId: string; newQty: number; expectedQty: number;
operationId: string; // stable per business operation, e.g. `${warehouseSyncRunId}:${sku}`
}) {
const data = await shopifyGraphQL(SET_QTY, {
idempotencyKey: opts.operationId,
input: {
name: 'available',
reason: 'correction',
referenceDocumentUri: `myapp://stock-sync/${opts.operationId}`,
quantities: [{
inventoryItemId: opts.inventoryItemId,
locationId: opts.locationId,
quantity: opts.newQty,
changeFromQuantity: opts.expectedQty,
}],
},
});
const errs = data.inventorySetQuantities.userErrors;
if (errs.length) {
// On CHANGE_FROM_QUANTITY_STALE: re-read the current quantity, decide again, retry.
throw new Error(JSON.stringify(errs));
}
}Keep the idempotency key stable for one logical operation. A new random UUID on every retry defeats the purpose. Shopify recommends UUIDs; derive or store one per operation and reuse it when retrying.
How do you receive Shopify webhooks securely?
Subscribe. Apps built with Shopify CLI can declare app-specific subscriptions in shopify.app.toml, which Shopify keeps up to date. Otherwise, subscribe through the API with webhookSubscriptionCreate. Use the uri field; callbackUrl is deprecated.
mutation {
webhookSubscriptionCreate(
topic: ORDERS_CREATE
webhookSubscription: { uri: "https://<project-ref>.supabase.co/functions/v1/shopify-webhook" }
) {
webhookSubscription { id topic uri }
userErrors { field message }
}
}Verify. Each HTTPS delivery carries a base64 HMAC-SHA256 of the raw body, computed with your app's client secret, in X-Shopify-Hmac-SHA256 (verify webhook deliveries). Verify before parsing, and deduplicate on X-Shopify-Webhook-Id. In a Supabase Edge Function (Deno), Web Crypto does a constant-time check for you:
// supabase/functions/shopify-webhook/index.ts (verify_jwt = false in config.toml)
import { createClient } from 'npm:@supabase/supabase-js@2';
const admin = createClient(Deno.env.get('SUPABASE_URL')!, Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!);
const enc = new TextEncoder();
const keyPromise = crypto.subtle.importKey(
'raw', enc.encode(Deno.env.get('SHOPIFY_CLIENT_SECRET')!),
{ name: 'HMAC', hash: 'SHA-256' }, false, ['verify'],
);
Deno.serve(async (req) => {
const raw = new Uint8Array(await req.arrayBuffer()); // raw bytes, before any parsing
const hmac = req.headers.get('X-Shopify-Hmac-SHA256');
if (!hmac) return new Response('Missing HMAC', { status: 401 });
let signature: Uint8Array;
try {
signature = Uint8Array.from(atob(hmac), (c) => c.charCodeAt(0));
} catch {
return new Response('Bad HMAC', { status: 401 });
}
const valid = await crypto.subtle.verify('HMAC', await keyPromise, signature, raw);
if (!valid) return new Response('Invalid HMAC', { status: 401 });
const webhookId = req.headers.get('X-Shopify-Webhook-Id')!;
const topic = req.headers.get('X-Shopify-Topic');
const shop = req.headers.get('X-Shopify-Shop-Domain');
// Store first, process later: keeps the response well under Shopify's 5-second timeout.
const { error } = await admin.from('shopify_webhooks').insert({
id: webhookId, // primary key: duplicates fail here
topic,
shop,
payload: JSON.parse(new TextDecoder().decode(raw)),
});
if (error && error.code !== '23505') return new Response('db error', { status: 500 });
return new Response('ok', { status: 200 });
});What Shopify expects from your endpoint:
- A
200-range response. Anything else, including3xx, counts as an error. - A one-second connection timeout and a five-second limit for the whole request. Queue the work.
- On errors or no response, Shopify retries 8 times over the next 4 hours. After 8 consecutive failures, a subscription created through the Admin API is deleted automatically, and warning emails go to the app's emergency developer address.
- Duplicates are possible. Use
X-Shopify-Webhook-Idto deduplicate single deliveries;X-Shopify-Event-Idlinks deliveries from the same merchant action across several subscriptions.
Shopify also recommends a reconciliation job that periodically fetches data you might have missed. With the fetchOrdersUpdatedSince function above, a nightly run that catches up on the last two days covers missed or deleted webhooks.
How do you test against a store safely?
- Create a dev store from the Dev Dashboard's Dev stores page. A dev store created from the Shopify admin is not in your organization, and the client credentials grant will refuse it.
- Install the app on the dev store, place test orders and change stock there, never on the live store first.
- Use
shopify app webhook trigger(Shopify CLI) with--client-secretto send a sample payload with a validX-Shopify-Hmac-SHA256header to your endpoint. The payload is always the same, failed triggers are not retried, and it cannot validate subscriptions you created through the API, so finish with real events on the dev store. - Check the
X-Shopify-API-Versionresponse header to confirm the version you think you are on. - Before enforcing an IP allowlist, use the Test against recent traffic button in the Dev Dashboard.
Common errors
- "Invalid API key or access token": the client ID or secret was sent to the Admin API directly. Exchange them for an access token first.
shop_not_permitted: client credentials used on a store outside your organization. Use custom distribution and OAuth instead.403after enabling the IP allowlist: your serverless function's IPs or ASN are not on the list.- Orders older than 60 days missing: you need approved
read_all_orders. - Inventory mutation rejected: missing
@idempotentkey or missingchangeFromQuantityon 2026-04 or later, or aCHANGE_FROM_QUANTITY_STALEconflict. - HMAC never matches: the body was parsed or re-serialized before verification, or the wrong secret is used. After rotating the client secret, Shopify can take up to an hour to sign with the new one.
- Webhooks stopped: the API-created subscription was deleted after 8 consecutive failures. Re-create it and fix the endpoint.
- New scopes not working: the merchant has not approved the new app version's scopes yet.
- REST calls in generated code: rewrite them against the GraphQL Admin API.
Brief for your AI coding tool
Paste this into Lovable, Claude Code or Cursor and adjust names:
Connect this app to our Shopify store using the GraphQL Admin API, version 2026-10.
Architecture:
- All Shopify calls run in Supabase Edge Functions. Secrets: SHOPIFY_SHOP, SHOPIFY_CLIENT_ID,
SHOPIFY_CLIENT_SECRET. Get tokens with the client credentials grant
(POST https://{shop}.myshopify.com/admin/oauth/access_token, grant_type=client_credentials),
cache for 24 h, refresh 60 s before expiry. Send X-Shopify-Access-Token.
- One shopifyGraphQL(query, variables) helper with the API version in a single constant. It
retries on HTTP 429 and when extensions.cost.throttleStatus shows too few points, and it
surfaces both top-level errors and each mutation's userErrors.
- Orders: incremental sync with orders(first: 50, after, sortKey: UPDATED_AT,
query: "updated_at:>'...'"), store a last-synced timestamp, plus a nightly reconciliation run.
- Inventory: look up inventoryItem.id by SKU and location; update with
inventorySetQuantities (only if we are the source of truth) or inventoryAdjustQuantities,
always with @idempotent(key) using a key that stays the same across retries of one operation,
and changeFromQuantity set to the quantity we last read. On CHANGE_FROM_QUANTITY_STALE,
re-read and retry.
- Webhooks: subscribe with webhookSubscriptionCreate (uri, not callbackUrl). Endpoint
"shopify-webhook" (verify_jwt=false) verifies X-Shopify-Hmac-SHA256 over the raw bytes with
the client secret using crypto.subtle.verify, dedupes on X-Shopify-Webhook-Id (primary key),
stores the payload and returns 200 within 5 seconds; processing happens in a separate job.
Safety rules:
- No Shopify credentials or tokens in frontend code or VITE_ variables.
- No REST Admin API calls. Minimum scopes only: read_orders, read_products, read_inventory,
write_inventory.
- Work against our dev store until I confirm the live store.When should you bring in a developer?
Reading orders and nudging stock for one store is a fair DIY project. Bring in help when:
- Shopify must stay in sync with an ERP, warehouse system or accounting system, in both directions.
- Several sales channels or locations share stock and overselling costs you money.
- You are building for a client's store (custom distribution, OAuth, IP allowlist) or for many stores (a public app with App Store review).
- You need customer data and must handle Shopify's protected customer data requirements and GDPR properly.
- Order volume is growing and you are seeing throttling, missed webhooks or reconciliation gaps.
We build and repair these integrations, including ones that started life in Lovable or Cursor: see integrations for vibe-coded apps, or ask for a code audit first. More about our Shopify work and integration services. Rocksoft is a software company with teams in Poland and Norwegian-speaking staff, building integrations and custom software for companies in Norway and across Europe.
Related guides
- Connecting a vibe-coded app to real systems: secrets, webhooks, duplicates and rate limits in general.
- Before you switch on an integration in production: a checklist
- Briefs for your AI coding tool: copy-paste briefs for integrations.
- Online store and Tripletex: Shopify and WooCommerce: getting orders into accounting.
FAQ
Can I still create a custom app in the Shopify admin?
No. Shopify says that method is no longer available for new apps; existing ones keep working. Create new apps in the Dev Dashboard.
Is the REST Admin API going away?
It has been legacy since 1 October 2024, and new public apps must use GraphQL only since 1 April 2025. Build new integrations on GraphQL.
Do I need OAuth for my own store?
Not if the app and the store are in the same Shopify organization: the client credentials grant gives you tokens without a redirect flow. For a store outside your organization you need custom distribution and OAuth (or token exchange for embedded apps).
How long does a Shopify access token last?
Tokens from the client credentials grant last 24 hours (expires_in 86399). Request a new one shortly before expiry.
Why do I get the same webhook twice?
Retries after timeouts, or several subscriptions to one topic. Deduplicate on X-Shopify-Webhook-Id and make processing idempotent.
What does the IP allowlist mean for a serverless app?
Serverless functions don't have fixed IPs, so Shopify suggests allowing your provider's ASNs, limited to the countries you run in. It is required for custom apps installed on stores outside your organization from 20 November 2026.
Which API version should I use today?
2026-10, the latest stable version at the time of writing. Each version is supported for at least 12 months, so schedule upgrades.

