> ## Documentation Index
> Fetch the complete documentation index at: https://www.commercengine.io/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Debugging & Performance

> Debug SDK issues with built-in logging and monitoring tools

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:

```typescript theme={"theme":{"light":"github-light","dark":"github-dark"}}
const client = createStorefront({
  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

<Tabs>
  <Tab title="Request Logging">
    ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
    [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"
    }
    ```
  </Tab>

  <Tab title="Response Logging">
    ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
    [SDK-INFO] API Response Debug Info
    {
      url: "https://prod.api.commercengine.io/api/v1/your-store-id/storefront/catalog/products",
      status: 200,
      statusText: "OK",
      ok: true,
      headers: {
        "content-type": "application/json",
        "x-request-id": "req_123456"
      },
      timestamp: "2024-01-15T10:30:01.234Z"
    }
    ```
  </Tab>

  <Tab title="Token Management">
    ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
    [SDK-INFO] Token refresh required
    [SDK-INFO] Refreshing token using refresh token
    [SDK-INFO] Token refreshed successfully
    [SDK-INFO] Retrying original request with new token
    ```
  </Tab>

  <Tab title="Error Details">
    ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
    [SDK-ERROR] API request failed
    {
      status: 400,
      error: {
        code: "VALIDATION_ERROR",
        message: "Invalid product_id",
        details: { field: "product_id", value: "invalid" }
      },
      request: {
        url: "/carts/123/items",
        method: "POST"
      }
    }
    ```
  </Tab>
</Tabs>

## Custom Logging

Implement custom logging for production monitoring:

```typescript theme={"theme":{"light":"github-light","dark":"github-dark"}}
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 = createStorefront({
  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:

```typescript theme={"theme":{"light":"github-light","dark":"github-dark"}}
import { ResponseUtils } from '@commercengine/storefront';

// 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:

```typescript theme={"theme":{"light":"github-light","dark":"github-dark"}}
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:

```typescript theme={"theme":{"light":"github-light","dark":"github-dark"}}
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

<AccordionGroup>
  <Accordion title="Token refresh loops">
    **Problem:** Infinite token refresh attempts

    **Solution:** Check token storage and refresh token validity

    ```typescript theme={"theme":{"light":"github-light","dark":"github-dark"}}
    // Debug token information
    const accessToken = await client.getAccessToken();
    if (accessToken) {
      const { data: userData } = await client.auth.retrieveUser();
      if (userData) {
        console.log('Current user:', userData.user);
      }
      
      const isLoggedIn = await client.isLoggedIn();
      console.log('Is logged in:', isLoggedIn);
    }
    ```
  </Accordion>

  <Accordion title="Cross-tab token sync issues">
    **Problem:** Tokens not syncing between browser tabs

    **Solution:** Use BrowserTokenStorage which automatically syncs via localStorage

    ```typescript theme={"theme":{"light":"github-light","dark":"github-dark"}}
    const storage = new BrowserTokenStorage();

    // Check current tokens
    storage.getAccessToken().then(token => {
      console.log('Current access token:', token ? 'present' : 'none');
    });
    ```
  </Accordion>
</AccordionGroup>

### API Request Issues

<AccordionGroup>
  <Accordion title="CORS errors">
    **Problem:** Cross-origin request blocked

    **Solution:** Verify your domain is allowlisted with Commerce Engine support

    ```typescript theme={"theme":{"light":"github-light","dark":"github-dark"}}
    // Log request details for CORS debugging
    const client = createStorefront({
      storeId: 'your-store-id',
      debug: true,
      logger: (level, message, data) => {
        if (message.includes('CORS')) {
          console.error('CORS Error Details:', data);
        }
      }
    });
    ```
  </Accordion>

  <Accordion title="Network timeouts">
    **Problem:** Requests timing out

    **Solution:** Configure appropriate timeout and check network conditions

    ```typescript theme={"theme":{"light":"github-light","dark":"github-dark"}}
    const client = createStorefront({
      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);
    }
    ```
  </Accordion>
</AccordionGroup>

## Error Monitoring

### Integration with Error Tracking

```typescript theme={"theme":{"light":"github-light","dark":"github-dark"}}
const client = createStorefront({
  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

```typescript theme={"theme":{"light":"github-light","dark":"github-dark"}}
// 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

```typescript theme={"theme":{"light":"github-light","dark":"github-dark"}}
const devClient = createStorefront({
  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

```typescript theme={"theme":{"light":"github-light","dark":"github-dark"}}
const prodClient = createStorefront({
  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

<CardGroup cols={2}>
  <Card title="Enable Debug in Development" icon="bug">
    Always enable debug mode during development to catch issues early
  </Card>

  <Card title="Monitor Error Rates" icon="chart-line">
    Track error patterns and response times to identify performance issues
  </Card>

  <Card title="Use Appropriate Timeouts" icon="clock">
    Set reasonable timeouts based on your application's needs and network conditions
  </Card>

  <Card title="Implement Custom Logging" icon="file-code">
    Create custom loggers for different environments and monitoring requirements
  </Card>
</CardGroup>

## Cross-References

* **Error Handling**: [Error Handling Guide](/docs/sdk/error-handling) for comprehensive error management
* **Token Management**: [Token Management](/docs/sdk/token-management) for authentication debugging
* **API Reference**: [API Reference](/docs/api-reference) for endpoint-specific debugging

<Note>
  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.
</Note>
