Skip to main content
The StorefrontSDK provides extensive configuration options to fit any environment or use case, from simple prototyping to complex production deployments.

Basic Configuration

Minimal Setup

import { createStorefront } from "@commercengine/storefront";

const sdk = createStorefront({
  storeId: "your-store-id",      // Required
  apiKey: "your-api-key"         // Required for anonymous authentication
});

Production Setup

import {
  createStorefront,
  Environment,
  CookieTokenStorage
} from "@commercengine/storefront";

const sdk = createStorefront({
  storeId: process.env.NEXT_PUBLIC_STORE_ID!,
  environment: Environment.Production,
  apiKey: process.env.NEXT_PUBLIC_API_KEY!,
  tokenStorage: new CookieTokenStorage({
    prefix: "myapp_",
    secure: true,
    sameSite: "Lax"
  }),
  timeout: 15000,
  debug: false
});

Configuration Options

Core Configuration

storeId
string
required
Your unique store identifier from the Commerce Engine dashboard.
const sdk = createStorefront({
  storeId: "01ABCD1234567890ABCDEFG", // Your store ID
  // ... other options
});
apiKey
string
required
API key for authentication endpoints. Required for anonymous authentication and initial token acquisition.
const sdk = createStorefront({
  storeId: "your-store-id",
  apiKey: "sk_live_abcdef1234567890", // Production API key
  // ... other options
});

Environment Management

environment
Environment
default:"Environment.Production"
Target environment for API requests. Controls which API endpoints are used.
import { Environment } from "@commercengine/storefront";

const sdk = createStorefront({
  storeId: "your-store-id",
  environment: Environment.Staging, // or Environment.Production
  // ... other options
});
Available Environments:
  • Environment.Productionhttps://prod.api.commercengine.io/api/v1/{storeId}/storefront
  • Environment.Staginghttps://staging.api.commercengine.io/api/v1/{storeId}/storefront
baseUrl
string
Custom base URL that overrides the environment setting. Useful for on-premise deployments or custom endpoints.
const sdk = createStorefront({
  storeId: "your-store-id",
  baseUrl: "https://api.mycompany.com/v1/storefront", // Custom URL
  // ... other options
});
When baseUrl is provided, the environment setting is ignored. Ensure your custom URL follows the correct API path structure.

Token Management

accessToken
string
Initial access token for manual token management or as a starting token for automatic management.
const sdk = createStorefront({
  storeId: "your-store-id",
  accessToken: "eyJhbGciOiJIUzI1NiIs...", // JWT access token
  // ... other options
});
Behavior:
  • With tokenStorage: Used as initial token, then managed automatically
  • Without tokenStorage: Used for manual token management
refreshToken
string
Initial refresh token. Only used when tokenStorage is provided for automatic token management.
const sdk = createStorefront({
  storeId: "your-store-id",
  accessToken: "eyJhbGciOiJIUzI1NiIs...",
  refreshToken: "eyJhbGciOiJIUzI1NiIs...", // Only used with tokenStorage
  tokenStorage: new BrowserTokenStorage(),
  // ... other options
});
tokenStorage
TokenStorage
Token storage implementation for automatic token management. See Token Management for detailed information.
import { BrowserTokenStorage } from "@commercengine/storefront";

const sdk = createStorefront({
  storeId: "your-store-id",
  tokenStorage: new BrowserTokenStorage("myapp_"),
  // ... other options
});

Request Configuration

timeout
number
default:"undefined"
Request timeout in milliseconds. When not set, uses the default fetch timeout behavior.
const sdk = createStorefront({
  storeId: "your-store-id",
  timeout: 15000, // 15 seconds
  // ... other options
});
Recommended timeouts:
  • Development: 30000ms (30 seconds) for easier debugging
  • Production: 10000ms (10 seconds) for better user experience
  • Server-side: 5000ms (5 seconds) for API routes
defaultHeaders
SupportedDefaultHeaders
Default headers applied to all API requests. These can be overridden at the method level.
const sdk = createStorefront({
  storeId: "your-store-id",
  defaultHeaders: {
    customer_group_id: "01JHS28V83KDWTRBXXJQRTEKA0" // For pricing & promotions
  },
  // ... other options
});
Supported Headers:
  • customer_group_id: Used for customer-specific pricing, promotions, and subscription rates

Debugging & Logging

debug
boolean
default:"false"
Enable detailed request/response logging for development and troubleshooting.
const sdk = createStorefront({
  storeId: "your-store-id",
  debug: true, // Enable debug logging
  // ... other options
});
Debug Information Includes:
  • Request URLs, methods, headers, and bodies
  • Response status, headers, and bodies
  • Token refresh attempts and results
  • Network errors and retry attempts
logger
DebugLoggerFn
Custom logger function for debug information. If not provided and debug is enabled, uses console.log.
const sdk = createStorefront({
  storeId: "your-store-id",
  debug: true,
  logger: (level, message, data) => {
    // Custom logging logic
    console.log(`[${level.toUpperCase()}] ${message}`);
    if (data) console.table(data);
  },
  // ... other options
});
Logger Interface:
interface DebugLoggerFn {
  (level: "info" | "warn" | "error", message: string, data?: any): void;
}

Framework-Specific Configurations

For detailed framework integration patterns including token storage, context setup, and best practices, see our dedicated guides:

Next.js Integration

SSR/SSG compatible configuration with automatic token management

TanStack Start Integration

Server functions, route loaders, and pre-rendering

React Integration

Client-side configuration with context providers and hooks

Node.js Integration

Server-side configuration for API routes and background jobs

Token Management

Complete guide to automatic token management and storage options

Quick Examples

Basic configuration examples for different environments:
import { StorefrontSDK, BrowserTokenStorage, Environment } from "@commercengine/storefront";

const sdk = createStorefront({
  storeId: process.env.REACT_APP_STORE_ID!,
  environment: Environment.Production,
  apiKey: process.env.REACT_APP_API_KEY!,
  tokenStorage: new BrowserTokenStorage("myapp_")
});

Advanced Configuration Patterns

Multi-Tenant Configuration

interface TenantConfig {
  storeId: string;
  environment: Environment;
  apiKey: string;
  customDomain?: string;
}

class MultiTenantSDK {
  private sdks: Map<string, StorefrontSDK> = new Map();
  
  getSDK(tenantId: string, config: TenantConfig): StorefrontSDK {
    if (!this.sdks.has(tenantId)) {
      const sdk = createStorefront({
        storeId: config.storeId,
        environment: config.environment,
        apiKey: config.apiKey,
        baseUrl: config.customDomain 
          ? `https://${config.customDomain}/api/v1/storefront`
          : undefined,
        tokenStorage: new BrowserTokenStorage(`tenant_${tenantId}_`),
        timeout: 10000
      });
      
      this.sdks.set(tenantId, sdk);
    }
    
    return this.sdks.get(tenantId)!;
  }
}

// Usage
const multiTenant = new MultiTenantSDK();
const tenantASDK = multiTenant.getSDK("tenant-a", {
  storeId: "store-a",
  environment: Environment.Production,
  apiKey: "key-a"
});

Configuration Factory

interface SDKEnvironment {
  name: string;
  storeId: string;
  apiKey: string;
  environment: Environment;
  baseUrl?: string;
}

class SDKConfigFactory {
  private environments: Record<string, SDKEnvironment> = {
    development: {
      name: "Development",
      storeId: process.env.DEV_STORE_ID!,
      apiKey: process.env.DEV_API_KEY!,
      environment: Environment.Staging
    },
    staging: {
      name: "Staging",
      storeId: process.env.STAGING_STORE_ID!,
      apiKey: process.env.STAGING_API_KEY!,
      environment: Environment.Staging
    },
    production: {
      name: "Production",
      storeId: process.env.PROD_STORE_ID!,
      apiKey: process.env.PROD_API_KEY!,
      environment: Environment.Production
    }
  };
  
  createSDK(envName: string, overrides?: Partial<StorefrontSDKOptions>): StorefrontSDK {
    const env = this.environments[envName];
    if (!env) throw new Error(`Unknown environment: ${envName}`);
    
    return createStorefront({
      storeId: env.storeId,
      environment: env.environment,
      apiKey: env.apiKey,
      baseUrl: env.baseUrl,
      
      // Environment-specific defaults
      timeout: envName === "development" ? 30000 : 10000,
      debug: envName === "development",
      
      tokenStorage: new CookieTokenStorage({
        prefix: `${envName}_`,
        secure: envName === "production"
      }),
      
      // Apply overrides
      ...overrides
    });
  }
}

// Usage
const factory = new SDKConfigFactory();
const sdk = factory.createSDK("production", {
  timeout: 15000,
  debug: true // Override for debugging production issues
});

Best Practices

✅ Configuration Recommendations

Environment Variables

Always use environment variables for sensitive configuration like API keys and store IDs

Secure Defaults

Use secure cookie settings in production with appropriate SameSite and Secure flags

Timeout Tuning

Set custom timeouts for your environment - longer for development, shorter for production

Debug Control

Enable debugging in development but disable in production for performance and security

Security Checklist

1

Use Environment Variables

// ✅ GOOD
const sdk = createStorefront({
  storeId: process.env.NEXT_PUBLIC_STORE_ID!,
  apiKey: process.env.NEXT_PUBLIC_API_KEY!,
  // ...
});

// ❌ BAD
const sdk = createStorefront({
  storeId: "hardcoded-store-id",
  apiKey: "sk_live_hardcoded_key",
  // ...
});
2

Secure Cookie Configuration

// ✅ GOOD
const tokenStorage = new CookieTokenStorage({
  secure: true,        // HTTPS only
  sameSite: "Lax",     // CSRF protection
  httpOnly: false      // Required for client access
});

// ❌ BAD
const tokenStorage = new CookieTokenStorage({
  secure: false,       // Allows HTTP transmission
  sameSite: "None"     // Vulnerable to CSRF
});
3

Environment-Specific Settings

// ✅ GOOD
const isProduction = process.env.NODE_ENV === "production";

const sdk = createStorefront({
  environment: isProduction ? Environment.Production : Environment.Staging,
  debug: !isProduction,
  timeout: isProduction ? 10000 : 30000,
  // ...
});
Never commit API keys or sensitive configuration to version control. Use environment variables and .env files that are excluded from your repository.
Configuration Summary: The SDK’s flexible configuration system allows you to adapt to any environment while maintaining security and performance. Use automatic token management with appropriate storage for your platform, and always follow security best practices for production deployments.