API Reference

Shopify Admin API

GraphQL Admin API wrappers with automatic pagination, retry, and rate limiting.

services/shopify/index.ts

shopifyAdmin(shopDomain)

function shopifyAdmin(shopDomain: string): ShopifyAdminClient

Create a Shopify Admin API client bound to a shop domain. Returns an object with all available methods.

Parameters
NameTypeDescription
shopDomainstringThe .myshopify.com domain (e.g. 'example.myshopify.com')

Returns: ShopifyAdminClient — an object with all Admin API methods

TypeScript
import { shopifyAdmin } from "~/services/shopify";

const api = shopifyAdmin("example.myshopify.com");
const { items: products } = await api.getProducts({ first: 20 });

getProducts(options?)

async getProducts(options?: ProductQueryOptions): Promise<PaginatedResult<ShopifyProduct>>

Fetch products with cursor-based pagination. Supports filtering by title, status, and collection.

Parameters
NameTypeDescription
options.firstnumberNumber of items to fetch (default: 20, max: 250)
options.afterstringCursor for forward pagination
options.querystringShopify search query (e.g. 'title:Shirt')
options.statusstringFilter by status: ACTIVE, ARCHIVED, DRAFT

Returns: PaginatedResult<ShopifyProduct> with items, hasNextPage, endCursor

TypeScript
const { items, hasNextPage, endCursor } = await api.getProducts({
  first: 10,
  status: "ACTIVE",
  query: "vendor:Nike",
});

// Paginate
if (hasNextPage) {
  const nextPage = await api.getProducts({ first: 10, after: endCursor });
}

getAllProducts()

async getAllProducts(): Promise<ShopifyProduct[]>

Fetch ALL products with automatic pagination. Use carefully on large catalogs.

Returns: ShopifyProduct[] — all products in the shop

TypeScript
const allProducts = await api.getAllProducts();
console.log(`Total products: ${allProducts.length}`);

getOrders(options?)

async getOrders(options?: OrderQueryOptions): Promise<PaginatedResult<ShopifyOrder>>

Fetch orders with pagination. Supports filtering by status, date range, and financial status.

Parameters
NameTypeDescription
options.firstnumberNumber of items (default: 20)
options.querystringSearch query (e.g. 'financial_status:paid')

Returns: PaginatedResult<ShopifyOrder>

TypeScript
const { items: orders } = await api.getOrders({
  first: 5,
  query: "created_at:>'2026-01-01'",
});

getRecentOrders(limit?)

async getRecentOrders(limit?: number): Promise<ShopifyOrder[]>

Convenience method to get the most recent orders.

Parameters
NameTypeDescription
limitnumberNumber of recent orders (default: 10)

Returns: ShopifyOrder[]

TypeScript
const recent = await api.getRecentOrders(5);

getOrderStats()

async getOrderStats(): Promise<{ totalOrders: number; totalSales: string }>

Get aggregate order statistics for the shop.

Returns: Object with totalOrders count and totalSales amount

TypeScript
const stats = await api.getOrderStats();
console.log(`Sales: ${stats.totalSales}`);

getCustomers(options?)

async getCustomers(options?: { first?: number; query?: string }): Promise<PaginatedResult>

Fetch customers with pagination and search.

Parameters
NameTypeDescription
options.firstnumberNumber of items (default: 20)
options.querystringSearch query (e.g. 'email:john@example.com')

Returns: PaginatedResult with customer objects

TypeScript
const { items: customers } = await api.getCustomers({
  query: "tags:VIP",
});

getShopInfo()

async getShopInfo(): Promise<ShopifyShopInfo>

Get shop metadata: name, email, plan, currency, timezone, etc.

Returns: ShopifyShopInfo with name, email, plan, currency, myshopifyDomain

TypeScript
const shop = await api.getShopInfo();
console.log(shop.name, shop.currency);

getMetafields(options)

async getMetafields(options: { ownerId: string; namespace?: string }): Promise<Metafield[]>

Fetch metafields for any Shopify resource (product, order, shop, etc.).

Parameters
NameTypeDescription
options.ownerIdstringGraphQL ID of the resource
options.namespacestringFilter by namespace (optional)

Returns: Metafield[]

TypeScript
const metafields = await api.getMetafields({
  ownerId: productGid,
  namespace: "custom",
});

setMetafield(ownerId, metafield)

async setMetafield(ownerId: string, metafield: MetafieldInput): Promise<Metafield>

Create or update a metafield on any Shopify resource.

Parameters
NameTypeDescription
ownerIdstringGraphQL ID of the resource
metafieldMetafieldInput{ namespace, key, type, value }

Returns: Metafield — the created/updated metafield

TypeScript
await api.setMetafield(productGid, {
  namespace: "custom",
  key: "badge",
  type: "single_line_text_field",
  value: "Best Seller",
});

graphql<T>(query, variables?)

async graphql<T>(query: string, variables?: Record<string, unknown>): Promise<T>

Raw GraphQL escape hatch. Use for queries not covered by the built-in methods.

Parameters
NameTypeDescription
querystringGraphQL query string
variablesRecord<string, unknown>Query variables (optional)

Returns: T — typed response data

TypeScript
const data = await api.graphql<{ shop: { name: string } }>(
  `query { shop { name } }`
);
console.log(data.shop.name);

Billing API

Subscription creation, modification, cancellation, and webhook handling.

services/billing.service.ts

getShopPlan(shopId)

async getShopPlan(shopId: string): Promise<PlanName>

Get the current subscription plan for a shop. Returns 'free' if no plan is set.

Parameters
NameTypeDescription
shopIdstringInternal shop UUID from the database

Returns: PlanName — 'free' | 'pro' | 'business'

TypeScript
import { billingService } from "~/services/billing.service";

const plan = await billingService.getShopPlan(shopId);
if (plan === "free") {
  // Gate premium features
}

createSubscription(shop, plan, token)

async createSubscription(shopDomain: string, planName: PlanName, accessToken: string): Promise<{ confirmationUrl: string } | { error: string }>

Create a Shopify subscription via GraphQL. Returns a confirmation URL for the merchant to approve.

Parameters
NameTypeDescription
shopDomainstringThe shop's .myshopify.com domain
planNamePlanName'pro' or 'business' (free plan cannot be subscribed)
accessTokenstringShop's OAuth access token

Returns: { confirmationUrl } on success, { error } on failure

TypeScript
const result = await billingService.createSubscription(
  "example.myshopify.com",
  "pro",
  accessToken
);

if ("confirmationUrl" in result) {
  // Redirect merchant to Shopify's approval page
  return redirect(result.confirmationUrl);
} else {
  // Handle error
  console.error(result.error);
}

handleSubscriptionActivated(shop, name, status)

async handleSubscriptionActivated(shop: string, name: string, status: string): Promise<void>

Handle subscription activation webhook. Updates the shop's plan in the database. Called automatically by the webhook registry.

Parameters
NameTypeDescription
shopstringShop domain
namestringPlan name from Shopify
statusstringSubscription status (ACTIVE, ACCEPTED)

Returns: void

TypeScript
// Called automatically by APP_SUBSCRIPTIONS_UPDATE webhook
// Manual usage is rare but possible:
await billingService.handleSubscriptionActivated(
  "example.myshopify.com",
  "Pro",
  "ACTIVE"
);

handleSubscriptionDeactivated(shop)

async handleSubscriptionDeactivated(shop: string): Promise<void>

Handle subscription cancellation/expiration. Downgrades the shop to the free plan.

Parameters
NameTypeDescription
shopstringShop domain

Returns: void

TypeScript
// Called automatically when subscription is CANCELLED/DECLINED/EXPIRED
await billingService.handleSubscriptionDeactivated("example.myshopify.com");
// Shop is now on the free plan

Authentication API

Session Token verification, Token Exchange, and automatic token refresh.

utils/shopify-auth.server.ts

verifySessionToken(idToken)

function verifySessionToken(idToken: string): SessionTokenPayload

Verify a Shopify Session Token (JWT) and return its payload. Throws if the token is invalid or expired.

Parameters
NameTypeDescription
idTokenstringThe session token from App Bridge (Authorization header)

Returns: SessionTokenPayload with iss, dest, sub, exp, shop, userId

TypeScript
import { verifySessionToken } from "~/utils/shopify-auth";

try {
  const payload = verifySessionToken(idToken);
  console.log(payload.dest); // "https://example.myshopify.com"
} catch {
  // Token invalid or expired
}

isValidShopDomain(shop)

function isValidShopDomain(shop: string): boolean

Validate that a string is a legitimate .myshopify.com domain. SSRF prevention.

Parameters
NameTypeDescription
shopstringShop domain to validate

Returns: boolean — true if valid myshopify.com domain

TypeScript
import { isValidShopDomain } from "~/utils/shopify-auth";

if (!isValidShopDomain(shop)) {
  throw new Response("Invalid shop domain", { status: 400 });
}

getAccessToken(shopDomain)

async getAccessToken(shopDomain: string): Promise<string>

Retrieve the decrypted OAuth access token for a shop from the database.

Parameters
NameTypeDescription
shopDomainstringThe shop's .myshopify.com domain

Returns: string — the decrypted access token

TypeScript
import { getAccessToken } from "~/utils/shopify-auth";

const token = await getAccessToken("example.myshopify.com");
// Use token for direct API calls

authenticatePage(request)

async authenticatePage(request: Request): Promise<AuthResult>

Full page authentication. Handles bounce redirect for embedded apps, token refresh, and session validation. Returns { shop, accessToken } or a redirect Response.

Parameters
NameTypeDescription
requestRequestThe incoming Remix request

Returns: { ok: true, shop: { id, shopifyDomain, plan, shopifyScope, locale, createdAt }, accessToken: string } | { ok: false, response: Response } | { ok: false, needsRefresh: true, shopDomain: string }

TypeScript
import { authenticatePage } from "~/utils/shopify-auth";

export async function loader({ request }: LoaderFunctionArgs) {
  const auth = await authenticatePage(request);
  if (!auth.ok) return auth.response; // redirect to OAuth

  const { shop, accessToken } = auth;
  // Proceed with authenticated request
}

Webhook API

Webhook registration, verification, and GDPR-compliant data handling.

services/webhook-registry.ts

webhookRegistry.on(topic, handler)

function on(topic: WebhookTopic, handler: WebhookHandler): void

Register a handler for a webhook topic. Multiple handlers per topic are supported. Built-in handlers (APP_UNINSTALLED, APP_SUBSCRIPTIONS_UPDATE, GDPR) are pre-registered.

Parameters
NameTypeDescription
topicWebhookTopicShopify webhook topic (e.g. 'ORDERS_CREATE')
handlerWebhookHandlerasync (shop: string, payload: unknown) => void

Returns: void

TypeScript
import { webhookRegistry } from "~/services/webhook-registry";

webhookRegistry.on("ORDERS_CREATE", async (shop, payload) => {
  const order = payload as { name: string; totalPrice: string };
  console.log(`New order ${order.name} in ${shop}`);
});

webhookRegistry.on("PRODUCTS_UPDATE", async (shop, payload) => {
  // Sync product data to your database
});

webhookRegistry.dispatch(topic, shop, payload)

async dispatch(topic: string, shop: string, payload: unknown): Promise<boolean>

Dispatch a webhook to all registered handlers. Called automatically by routes/webhooks.tsx. Includes retry with exponential backoff.

Parameters
NameTypeDescription
topicstringWebhook topic string
shopstringShop domain
payloadunknownWebhook payload from Shopify

Returns: boolean — true if at least one handler was found

TypeScript
// Called automatically by the webhook route.
// Manual dispatch is rare:
const handled = await webhookRegistry.dispatch(
  "ORDERS_CREATE",
  "example.myshopify.com",
  orderPayload
);

webhookRegistry.getRegisteredTopics()

function getRegisteredTopics(): string[]

Get all registered webhook topics. Used internally to auto-configure webhook subscriptions in shopify.server.ts.

Returns: string[] — array of topic names

TypeScript
const topics = webhookRegistry.getRegisteredTopics();
// ["APP_UNINSTALLED", "ORDERS_CREATE", "PRODUCTS_UPDATE", ...]

Database (Prisma)

Schema definition, migrations, and common query patterns.

prisma/schema.prisma

Shop model

model Shop { id, shopifyDomain, shopifyToken, plan, locale, isDeleted, ... }

Core shop entity. Stores OAuth tokens (encrypted), plan status, locale preference. One record per installed shop.

Parameters
NameTypeDescription
idString (UUID)Primary key
shopifyDomainString (unique)The .myshopify.com domain
shopifyTokenStringEncrypted OAuth access token (AES-256-GCM)
planStringCurrent plan: 'free' | 'pro' | 'business'
localeStringShop's preferred locale (default: 'en')
isDeletedBooleanSoft-delete flag (set by APP_UNINSTALLED)
TypeScript
import prisma from "~/db.server";

// Find active shop by domain
const shop = await prisma.shop.findUnique({
  where: { shopifyDomain: "example.myshopify.com" },
});

// Query active shops on paid plans
const paidShops = await prisma.shop.findMany({
  where: { isDeleted: false, plan: { not: "free" } },
});

Session model

model Session { id, shop, state, isOnline, accessToken, refreshToken, ... }

OAuth session storage. Managed by @shopify/shopify-app-session-storage-prisma. Supports both online and offline tokens with refresh token lifecycle.

Parameters
NameTypeDescription
idStringSession ID (managed by Shopify SDK)
shopStringShop domain
isOnlineBooleantrue for online tokens, false for offline
accessTokenStringOAuth access token
refreshTokenString?Token for automatic refresh (online tokens)
TypeScript
// Sessions are managed automatically by the Shopify SDK.
// Manual access is rare but possible:
const sessions = await prisma.session.findMany({
  where: { shop: "example.myshopify.com" },
});

Common commands

npm run db:push | npm run db:migrate | npm run db:seed

Prisma CLI commands available in ShopForge for database management.

Parameters
NameTypeDescription
db:pushcommandPush schema changes to database (dev only)
db:migratecommandRun pending migrations (production)
db:migrate:devcommandRun migrations in dev (resets if drift)
db:migrate:createcommandCreate a new migration file
db:seedcommandSeed database with demo data
TypeScript
# Add a new model to prisma/schema.prisma, then:
npm run db:push          # Dev: instant sync
npm run db:migrate:create --name add_my_model  # Prod: create migration
npm run db:migrate       # Prod: apply migration

GraphQL Client

Typed GraphQL queries and mutations with automatic error handling.

services/shopify/_core.ts

graphql<T>(query, variables?)

async graphql<T>(query: string, variables?: Record<string, unknown>): Promise<T>

Execute a typed GraphQL query against the Shopify Admin API. Includes automatic retry (2 attempts), 401 token-expired detection, and error normalization. This is the underlying method used by all shopifyAdmin() methods.

Parameters
NameTypeDescription
querystringGraphQL query/mutation string
variablesRecord<string, unknown>Query variables (optional)

Returns: T — the data field from the GraphQL response, typed

TypeScript
const api = shopifyAdmin("example.myshopify.com");

// Simple query
const { shop } = await api.graphql<{ shop: { name: string } }>(
  `query { shop { name } }`
);

// Mutation with variables
const result = await api.graphql<{ productCreate: { product: { id: string } } }>(
  `mutation ($input: ProductInput!) {
    productCreate(input: $input) {
      product { id title }
      userErrors { field message }
    }
  }`,
  { input: { title: "New Product", productType: "T-Shirt" } }
);

Built-in features

Token caching · Retry with backoff · 401 detection · Error normalization

The GraphQL client includes production-ready features out of the box.

Parameters
NameTypeDescription
Token cachingfeaturePer-request token caching — decrypted once, reused within the same request
Auto retryfeatureTransient errors retried up to 2 times with exponential backoff
401 handlingfeatureExpired/revoked tokens throw a clear error message
Error normalizationfeatureGraphQL userErrors and HTTP errors unified into thrown Error objects
TypeScript
// All features are automatic — just use the method:
try {
  const data = await api.graphql<MyType>(query, vars);
} catch (error) {
  // "Shopify access token expired" → reinstall needed
  // "GraphQL error: ..." → check your query
  // "Shopify API error 429" → rate limited (auto-retried)
}

Looking for guides instead?

Back to Documentation