Migrate from direct API calls to the type-safe SDK
This guide helps you migrate from direct API calls to the Commerce Engine TypeScript SDK, highlighting the benefits and providing step-by-step migration patterns.
import { StorefrontSDK, BrowserTokenStorage } from '@commercengine/storefront-sdk';// Simple, automated configurationconst client = new StorefrontSDK({ baseUrl: 'https://api.example.com', apiKey: 'your-api-key', tokenStorage: new BrowserTokenStorage()});// Token management is now automatic!
3
Update API Calls
Replace manual fetch calls with type-safe SDK methods:
Before (Direct API)
After (SDK)
Copy
// Manual fetch with error handlingasync function fetchProducts(limit: number, categoryId?: string) { try { const token = await getValidToken(); const params = new URLSearchParams({ limit: limit.toString() }); if (categoryId) params.append('category_id', categoryId); const response = await fetch(`${API_BASE_URL}/catalog/products?${params}`, { headers: { 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json' } }); if (!response.ok) { throw new Error(`HTTP ${response.status}: ${response.statusText}`); } const data = await response.json(); return { success: true, data }; } catch (error) { return { success: false, error: error.message }; }}// Usage (no type safety)const { data, error } = await fetchProducts(20, 'electronics');if (data) { data.forEach((product: any) => { // ❌ Any type console.log(product.name); });}
Copy
// Type-safe SDK callconst { data, error } = await client.catalog.listProducts({ limit: 20, category_id: 'electronics'});if (data) { // ✅ Full type safety with IntelliSense data.products.forEach(product => { console.log(product.name); // TypeScript knows this is a string console.log(product.selling_price); // TypeScript knows this is a number });} else if (error) { // ✅ Typed error handling console.error(error.message); console.error(error.code);}
4
Update Authentication
Replace manual authentication with SDK auth methods:
// Consistent error handling across all endpointsconst result = await client.catalog.getProduct('product-id');if (result.success) { // ✅ Success - data is fully typed console.log(result.data.name);} else { // ✅ Error - structured error with type safety switch (result.error.code) { case 'NOT_FOUND': // Handle product not found break; case 'VALIDATION_ERROR': // Handle validation errors break; default: // Handle other errors }}
Type Safety: Use TypeScript for better development experience
The SDK is designed to be a drop-in replacement for direct API calls while providing significant improvements in developer experience, type safety, and reliability.