TypeScript SDK

A powerful, 100% type-safe TypeScript SDK for the CommerceEngine Storefront API. Built with modern JavaScript patterns, automatic token management, and comprehensive error handling.

✨ Key Features

100% Type Safe

Every API endpoint is fully typed with TypeScript for complete IntelliSense support

Automatic Token Management

Built-in refresh token logic for seamless authentication across all environments

Universal Compatibility

Works in browser, Node.js, and hybrid rendering environments (Next.js, Nuxt, etc.)

Production Ready

Implements all API best practices with zero configuration required

Installation

npm install @commercengine/storefront-sdk

Quick Start

Basic Setup

1

Import and initialize the SDK

import StorefrontSDK, { Environment } from "@commercengine/storefront-sdk";

const sdk = new StorefrontSDK({
  storeId: "your-store-id",
  environment: Environment.Staging, // or Environment.Production
  apiKey: "your-api-key"
});
2

Get anonymous authentication

const { data, error } = await sdk.auth.getAnonymousToken();

if (error) {
  console.error("Authentication failed:", error.message);
} else {
  // Tokens are automatically managed
  console.log("Successfully authenticated!");
}
3

Make your first API call

// Get products with full type safety
const { data: products, error } = await sdk.catalog.listProducts({
  query: {
    page: 1,
    limit: 20,
    sort: "price_asc"
  }
});

if (error) {
  console.error("Failed to fetch products:", error.message);
} else {
  console.log(`Found ${products?.products.length} products`);
}

Complete E-commerce Example

Here’s a complete example showing authentication, product browsing, and cart management:

import StorefrontSDK, { 
  Environment, 
  BrowserTokenStorage 
} from "@commercengine/storefront-sdk";

// Initialize with automatic token management
const sdk = new StorefrontSDK({
  storeId: "your-store-id",
  environment: Environment.Staging,
  apiKey: "your-api-key",
  
  // Enable automatic token persistence
  tokenStorage: new BrowserTokenStorage("myapp_"),
  
  // Optional: Handle token events
  onTokensUpdated: (accessToken, refreshToken) => {
    console.log("User authenticated successfully");
  },
  onTokensCleared: () => {
    console.log("User logged out");
  }
});

async function ecommerceWorkflow() {
  try {
    // 1. Authenticate anonymously
    const { data: authData } = await sdk.auth.getAnonymousToken();
    
    // 2. Browse products
    const { data: products } = await sdk.catalog.listProducts({
      query: { category_id: "electronics", limit: 10 }
    });
    
    // 3. Get product details
    const { data: product } = await sdk.catalog.getProduct({
      product_id_or_slug: products?.products[0].id
    });
    
    // 4. Create cart and add items
    const { data: cart } = await sdk.cart.createCart({
      items: [{
        product_id: product?.id,
        quantity: 2,
        variant_id: product?.variants[0]?.id
      }]
    });
    
    console.log("Cart created:", cart?.id);
    
  } catch (error) {
    console.error("Workflow failed:", error);
  }
}

ecommerceWorkflow();

Core Concepts

Client Architecture

The SDK uses a client-per-domain architecture for optimal organization:

const sdk = new StorefrontSDK({ /* config */ });

// Each domain has its own specialized client
sdk.auth.*      // Authentication & user management
sdk.catalog.*   // Products, categories, search
sdk.cart.*      // Cart management, coupons, promotions  
sdk.customer.*  // Customer profiles, addresses, preferences
sdk.order.*     // Order creation, tracking, history
sdk.shipping.*  // Shipping methods, rates, tracking
sdk.helpers.*   // Countries, currencies, utilities

Type Safety

Every method is fully typed with complete IntelliSense support:

// TypeScript knows all available parameters
const { data } = await sdk.catalog.listProducts({
  query: {
    page: 1,              // βœ… number
    limit: 20,            // βœ… number  
    category_id: "tech",  // βœ… string
    sort: "price_asc",    // βœ… "price_asc" | "price_desc" | "name_asc" | ...
    // TypeScript will auto-complete all valid options
  }
});

// Response data is also fully typed
console.log(data?.products[0].name);        // βœ… string
console.log(data?.products[0].variants);    // βœ… Variant[]
console.log(data?.pagination.total_count);  // βœ… number

Error Handling

All API calls return a consistent ApiResult<T> structure:

const { data, error, response } = await sdk.catalog.getProduct({
  product_id_or_slug: "product-123"
});

if (error) {
  // Handle different error types
  switch (error.code) {
    case "NETWORK_ERROR":
      console.log("Network connection failed");
      break;
    case "UNAUTHORIZED":
      console.log("Authentication required");
      break;
    case "NOT_FOUND":
      console.log("Product not found");
      break;
    default:
      console.log("API Error:", error.message);
  }
} else {
  // Success - data is fully typed
  console.log("Product:", data?.name);
}

Next Steps

The SDK automatically handles API best practices like token refresh, automatic retries on authentication failure, and proper error handling. You can focus on building your application logic while the SDK manages the infrastructure concerns.