API Reference
Shopify Admin API
GraphQL Admin API wrappers with automatic pagination, retry, and rate limiting.
services/shopify/index.tsshopifyAdmin(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
| Name | Type | Description |
|---|---|---|
| shopDomain | string | The .myshopify.com domain (e.g. 'example.myshopify.com') |
Returns: ShopifyAdminClient — an object with all Admin API methods
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
| Name | Type | Description |
|---|---|---|
| options.first | number | Number of items to fetch (default: 20, max: 250) |
| options.after | string | Cursor for forward pagination |
| options.query | string | Shopify search query (e.g. 'title:Shirt') |
| options.status | string | Filter by status: ACTIVE, ARCHIVED, DRAFT |
Returns: PaginatedResult<ShopifyProduct> with items, hasNextPage, endCursor
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
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
| Name | Type | Description |
|---|---|---|
| options.first | number | Number of items (default: 20) |
| options.query | string | Search query (e.g. 'financial_status:paid') |
Returns: PaginatedResult<ShopifyOrder>
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
| Name | Type | Description |
|---|---|---|
| limit | number | Number of recent orders (default: 10) |
Returns: ShopifyOrder[]
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
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
| Name | Type | Description |
|---|---|---|
| options.first | number | Number of items (default: 20) |
| options.query | string | Search query (e.g. 'email:john@example.com') |
Returns: PaginatedResult with customer objects
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
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
| Name | Type | Description |
|---|---|---|
| options.ownerId | string | GraphQL ID of the resource |
| options.namespace | string | Filter by namespace (optional) |
Returns: Metafield[]
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
| Name | Type | Description |
|---|---|---|
| ownerId | string | GraphQL ID of the resource |
| metafield | MetafieldInput | { namespace, key, type, value } |
Returns: Metafield — the created/updated metafield
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
| Name | Type | Description |
|---|---|---|
| query | string | GraphQL query string |
| variables | Record<string, unknown> | Query variables (optional) |
Returns: T — typed response data
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.tsgetShopPlan(shopId)
async getShopPlan(shopId: string): Promise<PlanName>
Get the current subscription plan for a shop. Returns 'free' if no plan is set.
Parameters
| Name | Type | Description |
|---|---|---|
| shopId | string | Internal shop UUID from the database |
Returns: PlanName — 'free' | 'pro' | 'business'
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
| Name | Type | Description |
|---|---|---|
| shopDomain | string | The shop's .myshopify.com domain |
| planName | PlanName | 'pro' or 'business' (free plan cannot be subscribed) |
| accessToken | string | Shop's OAuth access token |
Returns: { confirmationUrl } on success, { error } on failure
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
| Name | Type | Description |
|---|---|---|
| shop | string | Shop domain |
| name | string | Plan name from Shopify |
| status | string | Subscription status (ACTIVE, ACCEPTED) |
Returns: void
// 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
| Name | Type | Description |
|---|---|---|
| shop | string | Shop domain |
Returns: void
// Called automatically when subscription is CANCELLED/DECLINED/EXPIRED
await billingService.handleSubscriptionDeactivated("example.myshopify.com");
// Shop is now on the free planAuthentication API
Session Token verification, Token Exchange, and automatic token refresh.
utils/shopify-auth.server.tsverifySessionToken(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
| Name | Type | Description |
|---|---|---|
| idToken | string | The session token from App Bridge (Authorization header) |
Returns: SessionTokenPayload with iss, dest, sub, exp, shop, userId
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
| Name | Type | Description |
|---|---|---|
| shop | string | Shop domain to validate |
Returns: boolean — true if valid myshopify.com domain
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
| Name | Type | Description |
|---|---|---|
| shopDomain | string | The shop's .myshopify.com domain |
Returns: string — the decrypted access token
import { getAccessToken } from "~/utils/shopify-auth";
const token = await getAccessToken("example.myshopify.com");
// Use token for direct API callsauthenticatePage(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
| Name | Type | Description |
|---|---|---|
| request | Request | The 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 }
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.tswebhookRegistry.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
| Name | Type | Description |
|---|---|---|
| topic | WebhookTopic | Shopify webhook topic (e.g. 'ORDERS_CREATE') |
| handler | WebhookHandler | async (shop: string, payload: unknown) => void |
Returns: void
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
| Name | Type | Description |
|---|---|---|
| topic | string | Webhook topic string |
| shop | string | Shop domain |
| payload | unknown | Webhook payload from Shopify |
Returns: boolean — true if at least one handler was found
// 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
const topics = webhookRegistry.getRegisteredTopics();
// ["APP_UNINSTALLED", "ORDERS_CREATE", "PRODUCTS_UPDATE", ...]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
| Name | Type | Description |
|---|---|---|
| id | String (UUID) | Primary key |
| shopifyDomain | String (unique) | The .myshopify.com domain |
| shopifyToken | String | Encrypted OAuth access token (AES-256-GCM) |
| plan | String | Current plan: 'free' | 'pro' | 'business' |
| locale | String | Shop's preferred locale (default: 'en') |
| isDeleted | Boolean | Soft-delete flag (set by APP_UNINSTALLED) |
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
| Name | Type | Description |
|---|---|---|
| id | String | Session ID (managed by Shopify SDK) |
| shop | String | Shop domain |
| isOnline | Boolean | true for online tokens, false for offline |
| accessToken | String | OAuth access token |
| refreshToken | String? | Token for automatic refresh (online tokens) |
// 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
| Name | Type | Description |
|---|---|---|
| db:push | command | Push schema changes to database (dev only) |
| db:migrate | command | Run pending migrations (production) |
| db:migrate:dev | command | Run migrations in dev (resets if drift) |
| db:migrate:create | command | Create a new migration file |
| db:seed | command | Seed database with demo data |
# 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 migrationGraphQL Client
Typed GraphQL queries and mutations with automatic error handling.
services/shopify/_core.tsgraphql<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
| Name | Type | Description |
|---|---|---|
| query | string | GraphQL query/mutation string |
| variables | Record<string, unknown> | Query variables (optional) |
Returns: T — the data field from the GraphQL response, typed
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
| Name | Type | Description |
|---|---|---|
| Token caching | feature | Per-request token caching — decrypted once, reused within the same request |
| Auto retry | feature | Transient errors retried up to 2 times with exponential backoff |
| 401 handling | feature | Expired/revoked tokens throw a clear error message |
| Error normalization | feature | GraphQL userErrors and HTTP errors unified into thrown Error objects |
// 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