@devxcommerce/shopify
v0.0.117
Published
A TypeScript SDK for the Shopify Storefront API that provides a simple and intuitive interface for interacting with Shopify's GraphQL API.
Downloads
595
Readme
@devxcommerce/shopify
A TypeScript SDK for the Shopify Storefront API that provides a simple and intuitive interface for interacting with Shopify's GraphQL API.
Features
- 🚀 Type-safe: Written in TypeScript with full type definitions
- 🔄 Modern: Uses modern JavaScript features and ESM/CJS dual package support
- 🌐 Comprehensive: Supports Shopify Storefront API operations for:
- Products and Collections
- Cart Management
- Customer Accounts and Addresses
- Orders
- Pages and Menus
- Metafields
- Files
- 🔒 Secure: Best practices for API authentication
- 🧩 Modular: Organized code structure for better maintainability
Installation
# npm
npm install @devxcommerce/shopify
# yarn
yarn add @devxcommerce/shopify
# pnpm
pnpm add @devxcommerce/shopifyGetting Started
Initialize the SDK
import { ShopifySDK } from '@devxcommerce/shopify';
const sdk = new ShopifySDK({
domain: 'your-store.myshopify.com',
apiVersion: '2023-07', // Use current API version
accessToken: 'your-storefront-access-token',
// Optional: For admin API access
adminAccessToken: 'your-admin-access-token',
});Products API
Fetch products from your Shopify store:
// List products
const products = await sdk.products.list({
variables: { first: 10 },
});
// Get product by ID
const product = await sdk.products.getById({
variables: { id: 'gid://shopify/Product/123' },
});
// Get product by handle
const product = await sdk.products.getByHandle({
variables: { handle: 'my-product' },
});
// Get product recommendations
const recommendations = await sdk.products.getRecommendations({
variables: { productId: 'gid://shopify/Product/123' },
});
// List product variants
const variants = await sdk.products.listVariants({
variables: {
handle: 'my-product',
first: 10,
},
});
// List product images
const images = await sdk.products.listImages({
variables: {
handle: 'my-product',
first: 10,
},
});Collections API
Work with collections in your Shopify store:
// List collections
const collections = await sdk.collections.list({
variables: { first: 10 },
});
// Get collection by ID
const collection = await sdk.collections.getById({
variables: { id: 'gid://shopify/Collection/123' },
});
// Get collection by handle
const collection = await sdk.collections.getByHandle({
variables: { handle: 'featured-products' },
});
// List products in a collection
const products = await sdk.collections.listProducts({
variables: {
handle: 'featured-products',
first: 10,
},
});Cart API
Manage shopping carts:
// Create a cart
const cart = await sdk.cart.create();
// Add items to cart
const updatedCart = await sdk.cart.addLines({
variables: {
cartId: cart.id,
lines: [
{
merchandiseId: 'gid://shopify/ProductVariant/123',
quantity: 1,
},
],
},
});
// Update cart items
const updatedCart = await sdk.cart.updateLines({
variables: {
cartId: cart.id,
lines: [
{
id: 'existing-line-item-id',
quantity: 2,
},
],
},
});
// Remove items from cart
const updatedCart = await sdk.cart.removeLines({
variables: {
cartId: cart.id,
lineIds: ['line-item-id-to-remove'],
},
});
// Get cart by ID
const cart = await sdk.cart.get({
variables: { id: 'cart-id' },
});Customer API
Manage customer accounts:
// Create customer account
const customer = await sdk.customer.create({
variables: {
input: {
firstName: 'John',
lastName: 'Doe',
email: '[email protected]',
password: 'password123',
},
},
});
// Customer login
const accessToken = await sdk.customer.createCAT({
variables: {
input: {
email: '[email protected]',
password: 'password123',
},
},
});
// Get customer information
const customer = await sdk.customer.getProfile({
variables: {
customerAccessToken: 'customer-access-token',
},
});
// Update customer information
const updatedCustomer = await sdk.customer.updateProfile({
variables: {
customerAccessToken: 'customer-access-token',
customer: {
firstName: 'John',
lastName: 'Smith',
},
},
});Error Handling
The SDK provides a consistent error handling pattern:
import { ShopifySDK, ShopifyError } from '@devxcommerce/shopify';
try {
const products = await sdk.products.list({
variables: { first: 10 },
});
} catch (error) {
if (error instanceof ShopifyError) {
console.error(`Error (${error.statusCode}): ${error.message}`);
// If there are specific GraphQL errors
if (error.errors) {
console.error('Detailed errors:', error.errors);
}
} else {
console.error('Unknown error:', error);
}
}Advanced Usage
Custom GraphQL Queries
You can execute custom GraphQL queries directly:
const data = await sdk.fetch({
query: `
query GetShopInfo {
shop {
name
description
primaryDomain {
url
}
}
}
`,
variables: {},
});Admin API Access
For operations that require Admin API access:
// Note: Admin API requests can only be performed server-side
const data = await sdk.fetchAdmin({
query: `
query GetDraftOrders {
draftOrders(first: 10) {
edges {
node {
id
name
totalPrice
}
}
}
}
`,
variables: {},
});API Reference
The SDK provides the following classes, each with methods for interacting with different parts of the Shopify Storefront API:
ShopifySDK
The main SDK class that provides access to all other modules.
Constructor:
constructor(config: ShopifySDKConfig)- Initializes the SDK with configuration
Methods:
fetch<T, V>({ query, variables, options, headers })- Execute Storefront API queriesfetchAdmin<T, V>({ query, variables, options, headers })- Execute Admin API queries (server-side only)
Products
Access product-related operations.
Methods:
list({ variables, options })- Get a list of products
const products = await sdk.products.list({
variables: {
first: 10,
sortKey: 'TITLE',
reverse: false,
},
});getById({ variables, options })- Get a product by ID
const product = await sdk.products.getById({
variables: {
id: 'gid://shopify/Product/123456789',
metafields: ['namespace.key'], // optional, to include metafields
},
});getByHandle({ variables, options })- Get a product by handle
const product = await sdk.products.getByHandle({
variables: {
handle: 'my-awesome-product',
metafields: ['reviews.rating'], // optional
},
});get({ variables, options })- Get a product by ID or handle
// Using ID
const product = await sdk.products.get({
variables: { id: 'gid://shopify/Product/123456789' },
});
// Using handle
const product = await sdk.products.get({
variables: { handle: 'my-awesome-product' },
});getRecommendations({ variables, options })- Get product recommendations
const recommendations = await sdk.products.getRecommendations({
variables: { productId: 'gid://shopify/Product/123456789' },
});listVariants({ variables, options })- Get a list of product variants
// By product ID
const variants = await sdk.products.listVariants({
variables: {
productId: 'gid://shopify/Product/123456789',
first: 20,
},
});
// By product handle
const variants = await sdk.products.listVariants({
variables: {
productHandle: 'my-awesome-product',
first: 20,
},
});listImages({ variables, options })- Get a list of product images
// By product ID
const images = await sdk.products.listImages({
variables: {
productId: 'gid://shopify/Product/123456789',
first: 10,
},
});
// By product handle
const images = await sdk.products.listImages({
variables: {
productHandle: 'my-awesome-product',
first: 10,
},
});Collections
Access collection-related operations.
Methods:
list({ variables, options })- Get a list of collections
const collections = await sdk.collections.list({
variables: {
first: 10,
sortKey: 'TITLE',
},
});getById({ variables, options })- Get a collection by ID
const collection = await sdk.collections.getById({
variables: {
id: 'gid://shopify/Collection/123456789',
metafields: ['custom.featured'], // optional
},
});getByHandle({ variables, options })- Get a collection by handle
const collection = await sdk.collections.getByHandle({
variables: {
handle: 'summer-collection',
metafields: ['custom.season'], // optional
},
});get({ variables, options })- Get a collection by ID or handle
// Using ID
const collection = await sdk.collections.get({
variables: { id: 'gid://shopify/Collection/123456789' },
});
// Using handle
const collection = await sdk.collections.get({
variables: { handle: 'summer-collection' },
});listProductsById({ variables, options })- Get products in a collection by ID
const products = await sdk.collections.listProductsById({
variables: {
id: 'gid://shopify/Collection/123456789',
first: 20,
sortKey: 'BEST_SELLING',
},
});listProductsByHandle({ variables, options })- Get products in a collection by handle
const products = await sdk.collections.listProductsByHandle({
variables: {
handle: 'summer-collection',
first: 20,
sortKey: 'PRICE',
reverse: true, // descending
},
});listProducts({ variables, options })- Get products in a collection by ID or handle
// Using ID
const products = await sdk.collections.listProducts({
variables: {
id: 'gid://shopify/Collection/123456789',
first: 20,
},
});
// Using handle
const products = await sdk.collections.listProducts({
variables: {
handle: 'summer-collection',
first: 20,
},
});listFilteredProductIds({ variables, options })- Get filtered product IDs in a collection
const productIds = await sdk.collections.listFilteredProductIds({
variables: {
handle: 'summer-collection',
filters: [
{
price: { min: 10, max: 100 },
},
{
available: true,
},
],
},
});Cart
Manage cart operations.
Methods:
get({ variables, options })- Get a cart by IDcreate({ variables, options })- Create a new cartupdateLines({ variables, options })- Update lines in a cartaddLines({ variables, options })- Add lines to a cartremoveLines({ variables, options })- Remove lines from a cartupdateAttributes({ variables, options })- Update cart attributesupdateDiscountCodes({ variables, options })- Update cart discount codes
Customer
Manage customer accounts.
Methods:
create({ variables, options })- Create a new customer accountupdateProfile({ variables, options })- Update a customer's profilegetProfile({ variables, options })- Get a customer's profilecreateCAT({ variables, options })- Create a customer access token (login)createCATWithMultipass({ variables, options })- Create customer access token with Multipassactivate({ variables, options })- Activate a customer accountactivateByUrl({ variables, options })- Activate a customer account by URLupdate({ variables, options })- Update a customercustomerEmailMarketingConsentUpdate({ variables, options })- Update email marketing consentlist({ variables, options })- List customers (admin only)subscribeToNewsletter({ variables, options })- Subscribe to newslettergenerateAccountActivationUrl({ variables, options })- Generate account activation URLcreateFromAdmin({ variables, options })- Create customer from admin
Addresses
Manage customer addresses.
Methods:
list({ variables, options })- Get a list of customer addressescreate({ variables, options })- Create a customer addressupdate({ variables, options })- Update a customer addressdelete({ variables, options })- Delete a customer addressmakeDefault({ variables, options })- Set address as default
Orders
Access order-related operations.
Methods:
list({ variables, options })- Get a list of customer ordersget({ variables, options })- Get an order by ID
Page
Access page content.
Methods:
get({ variables, options })- Get a page by handlelist({ variables, options })- Get a list of pagesgetById({ variables, options })- Get a page by IDgetByHandle({ variables, options })- Get a page by handle
Menu
Access navigation menus.
Methods:
get({ variables, options })- Get a menu by handle
Metafield
Access metafield operations.
Methods:
list({ variables, options })- Get a list of metafields for a resourcelistByType({ variables, options })- Get a list of metafields by type
File
Access file operations.
Methods:
create({ variables, options })- Create a fileget({ variables, options })- Get a file by IDdelete({ variables, options })- Delete a file
TypeScript Support
This SDK is written in TypeScript and includes comprehensive type definitions for all Shopify Storefront API objects and operations.
License
ISC
Author
Kritik Jiyaviya ([email protected])
