The SDK provides debugging tools to help you troubleshoot issues and monitor API interactions during development.
Debug Mode
Enable detailed logging for development and troubleshooting:
const client = new StorefrontSDK ({
storeId: 'your-store-id' ,
apiKey: 'your-api-key' ,
debug: true , // Enable debug mode
logger : ( level , message , data ) => {
console . log ( `[SDK- ${ level . toUpperCase () } ] ${ message } ` , data );
}
});
Debug Output Examples
Request Logging Response Logging Token Management Error Details [SDK-INFO] API Request Debug Info
{
method: "GET",
url: "https://prod.api.commercengine.io/api/v1/your-store-id/storefront/catalog/products?limit=20",
headers: {
"Authorization" : "Bearer eyJ...",
"Content-Type" : "application/json"
},
timestamp: "2024-01-15T10:30:00.000Z"
}
Custom Logging
Implement custom logging for production monitoring:
const productionLogger = ( level : string , message : string , data ?: any ) => {
// Only log warnings and errors in production
if ( level === 'error' || level === 'warn' ) {
// Send to monitoring service
monitoringService . log ({
level ,
message ,
data ,
timestamp: new Date (). toISOString (),
userAgent: navigator . userAgent ,
userId: getCurrentUserId ()
});
}
};
const client = new StorefrontSDK ({
storeId: process . env . STORE_ID ,
apiKey: process . env . API_KEY ,
debug: process . env . NODE_ENV === 'development' ,
logger: productionLogger
});
Response Utilities
The SDK provides utilities for working with Response objects:
import { ResponseUtils } from '@commercengine/storefront-sdk' ;
// Get response metadata
const { response } = await client . catalog . listProducts ();
if ( response ) {
const metadata = ResponseUtils . getMetadata ( response );
console . log ( 'Response metadata:' , metadata );
// Get specific headers
const requestId = ResponseUtils . getHeader ( response , 'x-request-id' );
console . log ( 'Request ID:' , requestId );
// Check if successful
const isSuccess = ResponseUtils . isSuccess ( response );
console . log ( 'Request succeeded:' , isSuccess );
}
Request Timing
Monitor request duration in your application:
const trackRequestTiming = async () => {
const startTime = performance . now ();
const { data , error } = await client . catalog . listProducts ({ limit: 20 });
const duration = performance . now () - startTime ;
console . log ( `Request took ${ duration . toFixed ( 2 ) } ms` );
// Log slow requests
if ( duration > 1000 ) {
console . warn ( `Slow request: ${ duration } ms` );
}
// Send metrics to analytics
analytics . track ( 'api_request_duration' , {
endpoint: 'catalog/products' ,
duration ,
success: !! data
});
};
Memory Usage
Monitor SDK memory usage:
const trackMemoryUsage = () => {
if ( performance . memory ) {
console . log ( 'Memory usage:' , {
used: Math . round ( performance . memory . usedJSHeapSize / 1024 / 1024 ) + ' MB' ,
total: Math . round ( performance . memory . totalJSHeapSize / 1024 / 1024 ) + ' MB' ,
limit: Math . round ( performance . memory . jsHeapSizeLimit / 1024 / 1024 ) + ' MB'
});
}
};
Common Issues & Solutions
Token Management Issues
Problem: Infinite token refresh attemptsSolution: Check token storage and refresh token validity// Debug token information
const accessToken = await client . getAccessToken ();
if ( accessToken ) {
const { data : userData } = await client . auth . retrieveUser ();
if ( userData ) {
console . log ( 'Current user:' , userData . content );
}
const isLoggedIn = await client . isLoggedIn ();
console . log ( 'Is logged in:' , isLoggedIn );
}
Cross-tab token sync issues
Problem: Tokens not syncing between browser tabsSolution: Use BrowserTokenStorage which automatically syncs via localStorageconst storage = new BrowserTokenStorage ();
// Check current tokens
storage . getAccessToken (). then ( token => {
console . log ( 'Current access token:' , token ? 'present' : 'none' );
});
API Request Issues
Problem: Cross-origin request blockedSolution: Verify your domain is allowlisted with Commerce Engine support// Log request details for CORS debugging
const client = new StorefrontSDK ({
storeId: 'your-store-id' ,
debug: true ,
logger : ( level , message , data ) => {
if ( message . includes ( 'CORS' )) {
console . error ( 'CORS Error Details:' , data );
}
}
});
Problem: Requests timing outSolution: Configure appropriate timeout and check network conditionsconst client = new StorefrontSDK ({
storeId: 'your-store-id' ,
timeout: 30000 , // 30 second timeout
debug: true
});
// Monitor network conditions
if ( navigator . connection ) {
console . log ( 'Network type:' , navigator . connection . effectiveType );
console . log ( 'Downlink speed:' , navigator . connection . downlink );
}
Error Monitoring
Integration with Error Tracking
const client = new StorefrontSDK ({
storeId: 'your-store-id' ,
apiKey: 'your-api-key' ,
debug: process . env . NODE_ENV === 'development' ,
logger : ( level , message , data ) => {
if ( level === 'error' ) {
// Send to error tracking service
Sentry . captureException ( new Error ( message ), {
extra: data ,
tags: { source: 'storefront-sdk' },
level: 'error'
});
}
}
});
Error Pattern Analysis
// Track error patterns
const trackError = ( error : any , context : string ) => {
const errorInfo = {
message: error . message || 'Unknown error' ,
code: error . code ,
status: error . status ,
context ,
timestamp: new Date (). toISOString (),
userAgent: navigator . userAgent ,
url: window . location . href
};
// Send to analytics
analytics . track ( 'sdk_error' , errorInfo );
// Log locally for development
if ( process . env . NODE_ENV === 'development' ) {
console . error ( 'SDK Error:' , errorInfo );
}
};
// Usage
const result = await client . order . createOrder ( orderData );
if (! result . success ) {
trackError ( result . error , 'checkout_flow' );
}
Environment-Specific Debugging
Development Environment
const devClient = new StorefrontSDK ({
storeId: 'your-store-id' ,
environment: Environment . Staging ,
apiKey: process . env . DEV_API_KEY ,
debug: true ,
logger : ( level , message , data ) => {
// Detailed logging for development
console . log ( `[ ${ level } ] ${ message } ` );
if ( data ) console . log ( JSON . stringify ( data , null , 2 ));
}
});
Production Environment
const prodClient = new StorefrontSDK ({
storeId: 'your-store-id' ,
environment: Environment . Production ,
apiKey: process . env . PROD_API_KEY ,
debug: false , // Disable debug in production
logger : ( level , message , data ) => {
// Only log errors in production
if ( level === 'error' ) {
errorTracker . captureError ( message , data );
}
}
});
Best Practices
Enable Debug in Development Always enable debug mode during development to catch issues early
Monitor Error Rates Track error patterns and response times to identify performance issues
Use Appropriate Timeouts Set reasonable timeouts based on your application’s needs and network conditions
Implement Custom Logging Create custom loggers for different environments and monitoring requirements
Cross-References
The debugging features help you understand SDK behavior during development. For production applications, implement appropriate monitoring and error tracking to maintain visibility into API performance.