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

[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);
}

Performance Monitoring

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

API Request Issues

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.