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.
Why Migrate to the SDK?
Automatic Token Management No more manual token refresh logic - handled automatically by the SDK
100% Type Safety Complete TypeScript support with IntelliSense and compile-time error checking
Simplified Error Handling Consistent error patterns with typed error responses across all endpoints
Built-in Best Practices Authentication flows and performance optimizations included out of the box
Migration Steps
Install the SDK
Replace your manual fetch calls with the SDK: npm install @commercengine/storefront-sdk
Initialize the Client
Replace your API configuration with SDK initialization: Before (Direct API) After (SDK) // Manual configuration
const API_BASE_URL = 'https://api.example.com' ;
const API_KEY = 'your-api-key' ;
let accessToken = '' ;
let refreshToken = '' ;
// Manual token refresh logic
async function getValidToken () {
// Complex token validation and refresh logic
if ( isTokenExpired ( accessToken )) {
const response = await fetch ( ` ${ API_BASE_URL } /auth/refresh-token` , {
method: 'POST' ,
headers: { 'Content-Type' : 'application/json' },
body: JSON . stringify ({ refresh_token: refreshToken })
});
const data = await response . json ();
accessToken = data . access_token ;
refreshToken = data . refresh_token ;
}
return accessToken ;
}
Update API Calls
Replace manual fetch calls with type-safe SDK methods: Before (Direct API) After (SDK) // Manual fetch with error handling
async 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 );
});
}
Update Authentication
Replace manual authentication with SDK auth methods: Before (Direct API) After (SDK) // Manual authentication flow
async function loginWithEmail ( email : string ) {
try {
// Step 1: Initiate login
const loginResponse = await fetch ( ` ${ API_BASE_URL } /auth/login/email` , {
method: 'POST' ,
headers: {
'Authorization' : `Bearer ${ await getValidToken () } ` ,
'Content-Type' : 'application/json'
},
body: JSON . stringify ({
email ,
register_if_not_exists: true
})
});
const loginData = await loginResponse . json ();
const otpToken = loginData . content . otp_token ;
// Step 2: Get OTP from user (UI logic)
const otp = await getUserOTPInput ();
// Step 3: Verify OTP
const verifyResponse = await fetch ( ` ${ API_BASE_URL } /auth/verify-otp` , {
method: 'POST' ,
headers: {
'Authorization' : `Bearer ${ await getValidToken () } ` ,
'Content-Type' : 'application/json'
},
body: JSON . stringify ({
otp ,
otp_token: otpToken ,
otp_action: 'login'
})
});
const verifyData = await verifyResponse . json ();
// Manual token storage
accessToken = verifyData . content . access_token ;
refreshToken = verifyData . content . refresh_token ;
localStorage . setItem ( 'access_token' , accessToken );
localStorage . setItem ( 'refresh_token' , refreshToken );
return { success: true , user: verifyData . content . user };
} catch ( error ) {
return { success: false , error: error . message };
}
}
Common Migration Patterns
Cart Management
Before (Direct API) After (SDK) // Manual cart creation and management
async function createCartWithItem ( productId : string , quantity : number ) {
const token = await getValidToken ();
const response = await fetch ( ` ${ API_BASE_URL } /carts` , {
method: 'POST' ,
headers: {
'Authorization' : `Bearer ${ token } ` ,
'Content-Type' : 'application/json'
},
body: JSON . stringify ({
items: [{ product_id: productId , variant_id: null , quantity }]
})
});
if (! response . ok ) {
throw new Error ( 'Failed to create cart' );
}
const cart = await response . json ();
return cart ;
}
Error Handling
Before (Direct API) After (SDK) // Manual error handling
try {
const response = await fetch ( url , options );
if ( response . status === 401 ) {
// Handle unauthorized
await refreshTokens ();
// Retry request manually
} else if ( response . status === 400 ) {
const error = await response . json ();
// Handle validation errors
} else if (! response . ok ) {
throw new Error ( `HTTP ${ response . status } ` );
}
const data = await response . json ();
return data ;
} catch ( error ) {
// Generic error handling
}
Migration Checklist
Replace API Configuration
Install SDK package
Replace manual API config with SDK initialization
Configure token storage (BrowserTokenStorage, CookieTokenStorage, etc.)
Update Authentication
Replace manual token management with SDK auth methods
Remove custom token refresh logic
Update login/logout flows to use SDK methods
Migrate API Calls
Replace fetch calls with SDK client methods
Add TypeScript types to replace any
types
Update error handling to use SDK error patterns
Test & Optimize
Test all authentication flows
Verify token management across browser tabs
Enable debug mode for development
Add performance monitoring
Benefits After Migration
IntelliSense : Complete autocomplete for all API methods and parameters
Type Safety : Compile-time error checking prevents runtime issues
Better Debugging : Built-in logging and error tracking
Reduced Boilerplate : No more manual token management code
Authentication & Security
Automatic Token Refresh : No more expired token errors
Secure Storage : Built-in secure token storage options
Cross-tab Sync : Token updates sync across browser tabs
Session Management : Handles anonymous-to-authenticated transitions
Performance & Reliability
Need Help?
If you encounter issues during migration:
Enable Debug Mode : Set debug: true
in SDK configuration
Check Documentation : Review API Reference for endpoint details
Follow Patterns : Reference Storefront Guides for business logic
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.