shopify-sdk-patterns
Apply production-ready patterns for @shopify/shopify-api including typed GraphQL clients, session management, and retry logic. Use when implementing Shopify integrations, refactoring SDK usage, or establishing team coding standards for Shopify. Trigger with phrases like "shopify SDK patterns", "shopify best practices", "shopify code patterns", "idiomatic shopify", "shopify client wrapper".
Best use case
shopify-sdk-patterns is best used when you need a repeatable AI agent workflow instead of a one-off prompt.
Apply production-ready patterns for @shopify/shopify-api including typed GraphQL clients, session management, and retry logic. Use when implementing Shopify integrations, refactoring SDK usage, or establishing team coding standards for Shopify. Trigger with phrases like "shopify SDK patterns", "shopify best practices", "shopify code patterns", "idiomatic shopify", "shopify client wrapper".
Teams using shopify-sdk-patterns should expect a more consistent output, faster repeated execution, less prompt rewriting.
When to use this skill
- You want a reusable workflow that can be run more than once with consistent structure.
When not to use this skill
- You only need a quick one-off answer and do not need a reusable workflow.
- You cannot install or maintain the underlying files, dependencies, or repository context.
Installation
Claude Code / Cursor / Codex
Manual Installation
- Download SKILL.md from GitHub
- Place it in
.claude/skills/shopify-sdk-patterns/SKILL.mdinside your project - Restart your AI agent — it will auto-discover the skill
How shopify-sdk-patterns Compares
| Feature / Agent | shopify-sdk-patterns | Standard Approach |
|---|---|---|
| Platform Support | Not specified | Limited / Varies |
| Context Awareness | High | Baseline |
| Installation Complexity | Unknown | N/A |
Frequently Asked Questions
What does this skill do?
Apply production-ready patterns for @shopify/shopify-api including typed GraphQL clients, session management, and retry logic. Use when implementing Shopify integrations, refactoring SDK usage, or establishing team coding standards for Shopify. Trigger with phrases like "shopify SDK patterns", "shopify best practices", "shopify code patterns", "idiomatic shopify", "shopify client wrapper".
Where can I find the source code?
You can find the source code on GitHub using the link provided at the top of the page.
Related Guides
AI Agents for Coding
Browse AI agent skills for coding, debugging, testing, refactoring, code review, and developer workflows across Claude, Cursor, and Codex.
Best AI Skills for Claude
Explore the best AI skills for Claude and Claude Code across coding, research, workflow automation, documentation, and agent operations.
Cursor vs Codex for AI Workflows
Compare Cursor and Codex for AI coding workflows, repository assistance, debugging, refactoring, and reusable developer skills.
SKILL.md Source
# Shopify SDK Patterns
## Overview
Production-ready patterns for the `@shopify/shopify-api` library: singleton clients, typed GraphQL operations, session management, cursor-based pagination, and error handling wrappers.
## Prerequisites
- `@shopify/shopify-api` v9+ installed
- Familiarity with Shopify's GraphQL Admin API
- Understanding of async/await and TypeScript generics
## Instructions
### Step 1: Typed GraphQL Client Wrapper
```typescript
// src/shopify/client.ts
import "@shopify/shopify-api/adapters/node";
import { shopifyApi, Session, GraphqlClient } from "@shopify/shopify-api";
const shopify = shopifyApi({
apiKey: process.env.SHOPIFY_API_KEY!,
apiSecretKey: process.env.SHOPIFY_API_SECRET!,
hostName: process.env.SHOPIFY_HOST_NAME!,
apiVersion: "2024-10",
isCustomStoreApp: !!process.env.SHOPIFY_ACCESS_TOKEN,
adminApiAccessToken: process.env.SHOPIFY_ACCESS_TOKEN,
});
// Singleton session cache per shop
const sessionCache = new Map<string, Session>();
export function getSession(shop: string): Session {
if (!sessionCache.has(shop)) {
const session = shopify.session.customAppSession(shop);
sessionCache.set(shop, session);
}
return sessionCache.get(shop)!;
}
export function getGraphqlClient(shop: string): GraphqlClient {
return new shopify.clients.Graphql({
session: getSession(shop),
});
}
// Typed query helper
export async function shopifyQuery<T = any>(
shop: string,
query: string,
variables?: Record<string, unknown>
): Promise<T> {
const client = getGraphqlClient(shop);
const response = await client.request(query, { variables });
return response.data as T;
}
```
### Step 2: Error Handling with Shopify Error Types
```typescript
// src/shopify/errors.ts
import { HttpResponseError, GraphqlQueryError } from "@shopify/shopify-api";
export class ShopifyServiceError extends Error {
constructor(
message: string,
public readonly statusCode: number,
public readonly retryable: boolean,
public readonly shopifyRequestId?: string,
public readonly originalError?: Error
) {
super(message);
this.name = "ShopifyServiceError";
}
}
export function handleShopifyError(error: unknown): never {
if (error instanceof HttpResponseError) {
const retryable = [429, 500, 502, 503, 504].includes(error.response.code);
throw new ShopifyServiceError(
`Shopify API ${error.response.code}: ${error.message}`,
error.response.code,
retryable,
error.response.headers?.["x-request-id"] as string,
error
);
}
if (error instanceof GraphqlQueryError) {
// GraphQL errors in the response body
const msg = error.body?.errors
?.map((e: any) => e.message)
.join("; ") || error.message;
throw new ShopifyServiceError(msg, 200, false, undefined, error);
}
throw error;
}
// Safe wrapper
export async function safeShopifyCall<T>(
operation: () => Promise<T>
): Promise<{ data: T | null; error: ShopifyServiceError | null }> {
try {
const data = await operation();
return { data, error: null };
} catch (err) {
try {
handleShopifyError(err);
} catch (shopifyErr) {
return { data: null, error: shopifyErr as ShopifyServiceError };
}
return { data: null, error: err as ShopifyServiceError };
}
}
```
### Step 3: Cursor-Based Pagination
```typescript
// src/shopify/pagination.ts
// Shopify uses Relay-style cursor pagination for all list queries
interface PageInfo {
hasNextPage: boolean;
endCursor: string | null;
}
interface PaginatedResult<T> {
edges: Array<{ node: T; cursor: string }>;
pageInfo: PageInfo;
}
export async function* paginateShopify<T>(
shop: string,
query: string,
connectionPath: string, // e.g. "products" or "orders"
variables: Record<string, unknown> = {},
pageSize: number = 50
): AsyncGenerator<T[], void, undefined> {
let cursor: string | null = null;
let hasNextPage = true;
while (hasNextPage) {
const response = await shopifyQuery(shop, query, {
...variables,
first: pageSize,
after: cursor,
});
// Navigate to the connection in the response
const connection = connectionPath
.split(".")
.reduce((obj: any, key) => obj[key], response) as PaginatedResult<T>;
yield connection.edges.map((e) => e.node);
hasNextPage = connection.pageInfo.hasNextPage;
cursor = connection.pageInfo.endCursor;
}
}
// Usage example:
// for await (const batch of paginateShopify<Product>(
// "store.myshopify.com",
// PRODUCTS_QUERY,
// "products",
// { query: "status:active" }
// )) {
// await processProducts(batch);
// }
```
### Step 4: Multi-Tenant Client Factory
```typescript
// src/shopify/factory.ts
// For apps installed on multiple stores
import { Session, GraphqlClient } from "@shopify/shopify-api";
interface TenantConfig {
shop: string;
accessToken: string;
}
class ShopifyClientFactory {
private clients = new Map<string, GraphqlClient>();
getClient(config: TenantConfig): GraphqlClient {
if (!this.clients.has(config.shop)) {
const session = new Session({
id: config.shop,
shop: config.shop,
state: "",
isOnline: false,
accessToken: config.accessToken,
});
this.clients.set(
config.shop,
new shopify.clients.Graphql({ session })
);
}
return this.clients.get(config.shop)!;
}
// Evict when merchant uninstalls
removeClient(shop: string): void {
this.clients.delete(shop);
}
}
export const clientFactory = new ShopifyClientFactory();
```
### Step 5: Response Validation with Zod
```typescript
// src/shopify/validators.ts
import { z } from "zod";
// Validate Shopify product response shape
const ShopifyMoneySchema = z.object({
amount: z.string(),
currencyCode: z.string(),
});
const ShopifyProductSchema = z.object({
id: z.string().startsWith("gid://shopify/Product/"),
title: z.string(),
handle: z.string(),
status: z.enum(["ACTIVE", "ARCHIVED", "DRAFT"]),
totalInventory: z.number(),
variants: z.object({
edges: z.array(z.object({
node: z.object({
id: z.string(),
title: z.string(),
price: z.string(),
sku: z.string().nullable(),
}),
})),
}),
});
export type ShopifyProduct = z.infer<typeof ShopifyProductSchema>;
// Validated fetch
export async function fetchProducts(shop: string): Promise<ShopifyProduct[]> {
const data = await shopifyQuery(shop, PRODUCTS_QUERY);
return data.products.edges.map(
(e: any) => ShopifyProductSchema.parse(e.node)
);
}
```
## Output
- Type-safe GraphQL client with singleton session management
- Structured error handling that distinguishes retryable from permanent errors
- Cursor-based pagination generator for large datasets
- Multi-tenant client factory for apps serving multiple stores
- Zod validation for API response shape verification
## Error Handling
| Pattern | Use Case | Benefit |
|---------|----------|---------|
| `safeShopifyCall` | All API calls | Returns `{data, error}` instead of throwing |
| `handleShopifyError` | Error translation | Maps HTTP/GraphQL errors to typed errors |
| Cursor pagination | Large datasets | Memory-efficient streaming with backpressure |
| Zod validation | Response parsing | Catches breaking API changes immediately |
| Client factory | Multi-tenant apps | Isolated sessions per merchant |
## Examples
### Retry with Exponential Backoff
```typescript
export async function withRetry<T>(
operation: () => Promise<T>,
maxRetries = 3,
baseDelayMs = 1000
): Promise<T> {
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
return await operation();
} catch (err) {
if (err instanceof ShopifyServiceError && err.retryable && attempt < maxRetries) {
const delay = baseDelayMs * Math.pow(2, attempt - 1) + Math.random() * 500;
console.warn(`Shopify retry ${attempt}/${maxRetries} in ${delay.toFixed(0)}ms`);
await new Promise((r) => setTimeout(r, delay));
continue;
}
throw err;
}
}
throw new Error("Unreachable");
}
```
## Resources
- [@shopify/shopify-api Reference](https://github.com/Shopify/shopify-api-js)
- [GraphQL Pagination (Relay Spec)](https://shopify.dev/docs/api/usage/pagination-graphql)
- [Zod Documentation](https://zod.dev/)
## Next Steps
Apply patterns in `shopify-core-workflow-a` for real-world product management.Related Skills
workhuman-sdk-patterns
Workhuman sdk patterns for employee recognition and rewards API. Use when integrating Workhuman Social Recognition, or building recognition workflows with HRIS systems. Trigger: "workhuman sdk patterns".
wispr-sdk-patterns
Wispr Flow sdk patterns for voice-to-text API integration. Use when integrating Wispr Flow dictation, WebSocket streaming, or building voice-powered applications. Trigger: "wispr sdk patterns".
windsurf-sdk-patterns
Apply production-ready Windsurf workspace configuration and Cascade interaction patterns. Use when configuring .windsurfrules, workspace rules, MCP servers, or establishing team coding standards for Windsurf AI. Trigger with phrases like "windsurf patterns", "windsurf best practices", "windsurf config patterns", "windsurfrules", "windsurf workspace".
windsurf-reliability-patterns
Implement reliable Cascade workflows with checkpoints, rollback, and incremental editing. Use when building fault-tolerant AI coding workflows, preventing Cascade from breaking builds, or establishing safe practices for multi-file AI edits. Trigger with phrases like "windsurf reliability", "cascade safety", "windsurf rollback", "cascade checkpoint", "safe cascade workflow".
webflow-sdk-patterns
Apply production-ready Webflow SDK patterns — singleton client, typed error handling, pagination helpers, and raw response access for the webflow-api package. Use when implementing Webflow integrations, refactoring SDK usage, or establishing team coding standards. Trigger with phrases like "webflow SDK patterns", "webflow best practices", "webflow code patterns", "idiomatic webflow", "webflow typescript".
vercel-sdk-patterns
Production-ready Vercel REST API patterns with typed fetch wrappers and error handling. Use when integrating with the Vercel API programmatically, building deployment tools, or establishing team coding standards for Vercel API calls. Trigger with phrases like "vercel SDK patterns", "vercel API wrapper", "vercel REST API client", "vercel best practices", "idiomatic vercel API".
vercel-reliability-patterns
Implement reliability patterns for Vercel deployments including circuit breakers, retry logic, and graceful degradation. Use when building fault-tolerant serverless functions, implementing retry strategies, or adding resilience to production Vercel services. Trigger with phrases like "vercel reliability", "vercel circuit breaker", "vercel resilience", "vercel fallback", "vercel graceful degradation".
veeva-sdk-patterns
Veeva Vault sdk patterns for REST API and clinical operations. Use when working with Veeva Vault document management and CRM. Trigger: "veeva sdk patterns".
vastai-sdk-patterns
Apply production-ready Vast.ai SDK patterns for Python and REST API. Use when implementing Vast.ai integrations, refactoring SDK usage, or establishing coding standards for GPU cloud operations. Trigger with phrases like "vastai SDK patterns", "vastai best practices", "vastai code patterns", "idiomatic vastai".
twinmind-sdk-patterns
Apply production-ready TwinMind SDK patterns for TypeScript and Python. Use when implementing TwinMind integrations, refactoring API usage, or establishing team coding standards for meeting AI integration. Trigger with phrases like "twinmind SDK patterns", "twinmind best practices", "twinmind code patterns", "idiomatic twinmind".
together-sdk-patterns
Together AI sdk patterns for inference, fine-tuning, and model deployment. Use when working with Together AI's OpenAI-compatible API. Trigger: "together sdk patterns".
techsmith-sdk-patterns
TechSmith sdk patterns for Snagit COM API and Camtasia automation. Use when working with TechSmith screen capture and video editing automation. Trigger: "techsmith sdk patterns".