TypeScript SDK for the Storefront API
npm install @commercengine/storefront-sdkA powerful, type-safe TypeScript SDK for the CommerceEngine Storefront API. Built with modern JavaScript patterns, automatic token management, and comprehensive error handling.
✨ Key Features:
- 100% Type Safe: Every API endpoint is fully typed with TypeScript
- Automatic Token Management: Built-in refresh token logic for seamless authentication
- Universal Compatibility: Works in browser, Node.js, and hybrid rendering environments
- Production Ready: Implements all API best practices out of the box
- Zero Configuration: Works with sensible defaults, extensive customization available
``bash`
npm install @commercengine/storefront-sdk
`bash`
yarn add @commercengine/storefront-sdk
`bash`
pnpm add @commercengine/storefront-sdk
`typescript
import StorefrontSDK, { Environment } from "@commercengine/storefront-sdk";
// Basic initialization
const sdk = new StorefrontSDK({
storeId: "your-store-id",
environment: Environment.Staging,
apiKey: "your-api-key", // Required for authentication
});
// Get started with anonymous authentication
const { data, error } = await sdk.auth.getAnonymousToken();
if (error) {
console.log(error)
} else {
accessToken = data.accessToken
}
`
The SDK supports extensive configuration to fit your needs:
`typescript`
const sdk = new StorefrontSDK({
// Required
storeId: "your-store-id",
// Environment (optional, defaults to Production)
environment: Environment.Staging, // or Environment.Production
// API key for authentication (required for auth endpoints)
apiKey: "your-api-key",
});
`typescript`
const sdk = new StorefrontSDK({
storeId: "your-store-id",
environment: Environment.Production,
// Token Management
accessToken: "initial-access-token", // Initial access token
refreshToken: "initial-refresh-token", // Initial refresh token (for automatic mode)
// Custom base URL (optional, overrides environment) - Not needed for most implementations
baseUrl: "https://your-custom-api.example.com",
// Request Configuration
timeout: 10000, // Request timeout in milliseconds
// Default Headers (auto applied to all applicable requests)
defaultHeaders: {
customer_group_id: "01JHS28V83KDWTRBXXJQRTEKA0", // For pricing and promotions
},
// Debug and Logging
debug: true, // Enable detailed request/response logging - Uses console.log by default
logger: console.log, // Custom logger function - structure your logs any way you want. Also helpful to pipe logs into external services
});
The SDK offers two approaches to token management:
For basic use cases where you manage tokens yourself:
`typescript
const sdk = new StorefrontSDK({
storeId: "your-store-id",
apiKey: "your-api-key",
});
// Login and set tokens manually
const { data: loginData } = await sdk.auth.loginWithPassword({
email: "user@example.com",
password: "password",
});
if (loginData) {
await sdk.setTokens(loginData.access_token);
}
`
For production applications with automatic token refresh and persistence:
`typescript
import StorefrontSDK, { BrowserTokenStorage } from "@commercengine/storefront-sdk";
const sdk = new StorefrontSDK({
storeId: "your-store-id",
apiKey: "your-api-key",
// Enable automatic token management
tokenStorage: new BrowserTokenStorage("myapp_"), // Prefix for localStorage keys
// Optional callbacks
onTokensUpdated: (accessToken, refreshToken) => {
console.log("Tokens updated!");
},
onTokensCleared: () => {
console.log("User logged out");
},
});
`
Choose the storage method that fits your environment:
#### Browser localStorage
`typescript
import { BrowserTokenStorage } from "@commercengine/storefront-sdk";
const tokenStorage = new BrowserTokenStorage("myapp_"); // Optional prefix
`
#### Cookies (for SSR or cross-tab sync)
`typescript
import { CookieTokenStorage } from "@commercengine/storefront-sdk";
const tokenStorage = new CookieTokenStorage({
prefix: "myapp_",
maxAge: 7 24 60 * 60, // 7 days
secure: true,
sameSite: "Lax",
});
`
#### Memory (for server-side or temporary storage)
`typescript
import { MemoryTokenStorage } from "@commercengine/storefront-sdk";
const tokenStorage = new MemoryTokenStorage();
`
#### Custom Storage
`typescript`
class CustomTokenStorage implements TokenStorage {
async getAccessToken(): Promise
// Your implementation
}
async setAccessToken(token: string): Promise
// Your implementation
}
// ... implement other required methods
}
typescript
// Get anonymous token for guest users
const { data } = await sdk.auth.getAnonymousToken();
if (data) {
await sdk.setTokens(data.access_token, data.refresh_token);
}
`$3
`typescript
// Step 1: Initiate login
const { data: otpData } = await sdk.auth.loginWithPhone({
phone: "9876543210",
country_code: "+91",
register_if_not_exists: true,
});// Step 2: Verify OTP
if (otpData) {
const { data: authData } = await sdk.auth.verifyOtp({
otp: "123456",
otp_token: otpData.otp_token,
otp_action: otpData.otp_action,
});
if (authData) {
await sdk.setTokens(authData.access_token, authData.refresh_token);
}
}
`$3
`typescript
const { data } = await sdk.auth.loginWithPassword({
email: "user@example.com",
password: "your-password",
});if (data) {
await sdk.setTokens(data.access_token, data.refresh_token);
}
`API Clients & Complete Type Safety
The SDK provides complete access to every CommerceEngine API endpoint with full TypeScript support. All clients are automatically generated from the OpenAPI specification, ensuring 100% accuracy and type safety.
$3
`typescript
// Authentication & User Management
sdk.auth.* // Login, registration, OTP, password management
sdk.customer.* // Customer profiles, addresses, preferences// E-commerce Core
sdk.catalog.* // Products, categories, search, variants
sdk.cart.* // Cart management, coupons, promotions
sdk.order.* // Order creation, tracking, history
// Supporting Services
sdk.shipping.* // Shipping methods, rates, tracking
sdk.helpers.* // Countries, currencies, utilities
`$3
`typescript
// Every method is fully typed - IntelliSense shows all available parameters
const { data: products } = await sdk.catalog.listProducts({
query: {
page: 1,
limit: 20,
category_id: "electronics",
sort: "price_asc",
}
});// Get product details
const { data: product } = await sdk.catalog.getProduct({
product_id_or_slug: "product-id"
});
// Create a cart with full type checking
const { data: cart } = await sdk.cart.createCart({
items: [
{
product_id: "product-id",
quantity: 2,
variant_id: "variant-id",
}
]
});
`> 📚 API Reference: For complete endpoint documentation, parameters, and response schemas, visit docs.commercengine.io/api-reference
User Information & JWT Utilities
Extract user information from tokens with built-in utilities:
`typescript
// Get current user info
const userInfo = await sdk.getUserInfo();
console.log(userInfo?.userId, userInfo?.email, userInfo?.customerId);// Check authentication status
const isLoggedIn = await sdk.isLoggedIn();
const isAnonymous = await sdk.isAnonymous();
// Get specific user data
const userId = await sdk.getUserId();
const customerId = await sdk.getCustomerId();
const customerGroupId = await sdk.getCustomerGroupId();
`Error Handling
All API calls return a consistent
ApiResult structure with full error information:`typescript
const { data, error, response } = await sdk.catalog.listProducts();if (error) {
console.error("API Error:", error.message, error.code);
console.log("Status:", response.status);
} else {
console.log("Success:", data);
}
`$3
`typescript
const result = await sdk.catalog.getProduct({ product_id_or_slug: "invalid-id" });if (result.error) {
switch (result.error.code) {
case "NETWORK_ERROR":
console.log("Network connection failed");
break;
case "UNAUTHORIZED":
console.log("Authentication required");
break;
default:
console.log("API Error:", result.error.message);
}
}
`Debug Mode
Enable detailed logging for development:
`typescript
const sdk = new StorefrontSDK({
storeId: "your-store-id",
debug: true,
// Optional: Pass a custom logger
logger: (message, data) => {
console.log([SDK Debug] ${message}, data);
},
});
`Debug mode logs:
- Request URLs, methods, headers, and bodies
- Response status, headers, and bodies
- Token refresh attempts and results
- Network errors and retry attempts
TypeScript Support
The SDK is built with TypeScript-first design:
`typescript
import type {
ApiResult,
UserInfo,
DebugLoggerFn,
SupportedDefaultHeaders
} from "@commercengine/storefront-sdk";// All API responses are properly typed
const { data }: ApiResult = await sdk.catalog.listProducts();
// IntelliSense works for all nested properties
console.log(data?.products[0].name);
`Universal Compatibility
The SDK works seamlessly across all JavaScript environments:
$3
- React, Vue, Angular: Use BrowserTokenStorage for persistent sessions
- Automatic token refresh: Handles token expiry transparently
- Cross-tab synchronization: With CookieTokenStorage$3
- Node.js, Bun, Deno: Use MemoryTokenStorage or custom storage
- API routes: Perfect for Next.js API routes, Express middleware
- Background jobs: Reliable token management for long-running processes$3
- Next.js: Use NextJSTokenStorage for universal client/server token access
- Nuxt, SvelteKit: Use CookieTokenStorage for seamless client/server token handoff
- Cookie-based storage: Maintains sessions across server/client boundaries
- Hydration-safe: No client/server state mismatchesBest Practices Built-In
The SDK implements CommerceEngine API best practices automatically:
- ✅ Automatic token refresh before expiry
- ✅ Proper error handling for all edge cases
- ✅ Request retries for transient failures
- ✅ Rate limiting compliance with proper backoff
- ✅ Security headers and CSRF protection
- ✅ Timeout handling with configurable limits
- ✅ Memory leak prevention with proper cleanup
Contributing
$3
This project uses Changeset for version management and publishing. Here's how to contribute:
#### Creating Changes
When you make changes to the SDK, create a changeset to document them:
`bash
pnpm changeset
`This will prompt you to:
- Select the type of change (patch/minor/major)
- Write a summary of what changed
- Create a markdown file in the
.changeset/ folder#### Version Types
- Patch (0.0.x): Bug fixes, documentation updates, internal refactoring
- Minor (0.x.0): New features, new API endpoints, backwards-compatible changes
- Major (x.0.0): Breaking changes, API modifications that affect existing code
#### Release Process
1. During Development: Create changesets for your changes
`bash
pnpm changeset
`2. Before Release: Consume changesets and update versions
`bash
pnpm version
`
This updates package.json, generates/updates CHANGELOG.md, and removes consumed changesets.3. Publishing: Build and publish to npm
`bash
pnpm release
`#### Available Scripts
-
pnpm changeset - Create a new changeset
- pnpm run version - Consume changesets and bump version
- pnpm run release` - Build and publish to npmThe changeset workflow ensures proper semantic versioning, comprehensive changelogs, and coordinated releases.
All Rights Reserved