<!-- Start Summary [summary] --> ## Summary
npm install ce-storefrontCE Storefront APIs: Customer-facing e-commerce API for building exceptional shopping experiences
Public-facing API for Commerce Engine storefronts, enabling seamless shopping experiences with product browsing, cart management, checkout processing, user accounts, and order tracking. Perfect for building web, mobile, and headless commerce applications.
For more information about the API: Commerce Engine API Reference Documentation
The SDK can be installed with either npm, pnpm, bun or yarn package managers.
``bash`
npm add ce-storefront
`bash`
pnpm add ce-storefront
`bash`
bun add ce-storefront
`bash`
yarn add ce-storefront
> [!NOTE]
> This package is published as an ES Module (ESM) only. For applications using
> CommonJS, use await import("ce-storefront") to import and use this package.
For supported JavaScript runtimes, please consult RUNTIMES.md.
`typescript
import { CeStorefront } from "ce-storefront";
const ceStorefront = new CeStorefront();
async function run() {
const result = await ceStorefront.auth.getAnonymousToken({
xApiKey: "
});
console.log(result);
}
run();
`
Available methods
* getAnonymousToken - Anonymous user
* generateOtp - Generate OTP
* loginWithEmail - Login with email
* loginWithPhone - Login with phone
* loginWithWhatsapp - Login with whatsapp
* logout - Logout user
* refreshToken - Refresh access token
* getUserDetail - Retrieve a user
* updateUser - Update a user
* verifyOtp - Verify OTP
* createCart - Create cart
* fulfillmentOptions - Retrieve fulfillment options
* getUserCart - Retrieve cart using user id
* removeUserCart - Delete cart using user id
* getCart - Retrieve cart detail
* deleteCart - Delete cart
* createCartAddress - Update cart address
* applyCoupon - Apply coupon
* removeCoupon - Remove coupon
* updateFulfillmentPreference - Update fulfillment preference
* updateCart - Add/delete cart item
* redeemLoyaltyPoints - Redeem loyalty points
* removeLoyaltyPoints - Remove loyalty points
* checkFulfillment - Check fulfillment
* listCategories - List all categories
* listProducts - List all products
* listCrosssellProducts - Retrieve cross-sell products
* searchProducts - Search products
* listSimilarProducts - Retrieve similar products
* listUpsellProducts - Retrieve up-sell products
* getProductDetail - Retrieve a product detail
* listProductReviews - List all product reviews
* listProductVariants - Retrieve product variants
* getVariantDetail - Retrieve variant detail
* listSkus - List all SKUs
* listCountryPincodes - Retrieve pincodes
* listCustomerCards - List all saved cards
* listSavedPaymentMethods - List all saved payment methods
* listAddresses - Retrieve all addresses
* createAddress - Create address
* getAddressDetail - Retrieve particular address
* updateAddressDetail - Update particular address
* deleteAddress - Remove particular address
* getLoyaltyDetails - Retrieve loyalty details
* listUserReviews - Retrieve all reviews
* listCategories - List all categories
* listProducts - List all products
* listCrosssellProducts - Retrieve cross-sell products
* searchProducts - Search products
* listSimilarProducts - Retrieve similar products
* listUpsellProducts - Retrieve up-sell products
* getProductDetail - Retrieve a product detail
* listProductReviews - List all product reviews
* listProductVariants - Retrieve product variants
* getVariantDetail - Retrieve variant detail
* listSkus - List all SKUs
* createOrder - Create order
* listOrders - Retrieve all orders
* getOrderDetail - Retrieve order detail
* cancelOrder - Cancel order
* getPaymentStatus - Retrieve payment status
* retryOrderPayment - Retry payment
* listOrderShipments - Retrieve order shipments
* getCardInfo - Get card information
* getSellerDetail - Retrieve seller detail
* listSellerReviews - List seller reviews
All the methods listed above are available as standalone functions. These
functions are ideal for use in applications running in the browser, serverless
runtimes or other environments where application bundle size is a primary
concern. When using a bundler to build your application, all unused
functionality will be either excluded from the final bundle or tree-shaken away.
To read more about standalone functions, check FUNCTIONS.md.
- authGenerateOtp - Generate OTP
- authGetAnonymousToken - Anonymous user
- authGetUserDetail - Retrieve a user
- authLoginWithEmail - Login with email
- authLoginWithPhone - Login with phone
- authLoginWithWhatsapp - Login with whatsapp
- authLogout - Logout user
- authRefreshToken - Refresh access token
- authUpdateUser - Update a user
- authVerifyOtp - Verify OTP
- cartsApplyCoupon - Apply coupon
- cartsCheckFulfillment - Check fulfillment
- cartsCreateCart - Create cart
- cartsCreateCartAddress - Update cart address
- cartsDeleteCart - Delete cart
- cartsFulfillmentOptions - Retrieve fulfillment options
- cartsGetCart - Retrieve cart detail
- cartsGetUserCart - Retrieve cart using user id
- cartsRedeemLoyaltyPoints - Redeem loyalty points
- cartsRemoveCoupon - Remove coupon
- cartsRemoveLoyaltyPoints - Remove loyalty points
- cartsRemoveUserCart - Delete cart using user id
- cartsUpdateCart - Add/delete cart item
- cartsUpdateFulfillmentPreference - Update fulfillment preference
- catalogGetProductDetail - Retrieve a product detail
- catalogGetVariantDetail - Retrieve variant detail
- catalogListCategories - List all categories
- catalogListCrosssellProducts - Retrieve cross-sell products
- catalogListProductReviews - List all product reviews
- catalogListProducts - List all products
- catalogListProductVariants - Retrieve product variants
- catalogListSimilarProducts - Retrieve similar products
- catalogListSkus - List all SKUs
- catalogListUpsellProducts - Retrieve up-sell products
- catalogSearchProducts - Search products
- commonListCountryPincodes - Retrieve pincodes
- customersCreateAddress - Create address
- customersDeleteAddress - Remove particular address
- customersGetAddressDetail - Retrieve particular address
- customersGetLoyaltyDetails - Retrieve loyalty details
- customersListAddresses - Retrieve all addresses
- customersListCustomerCards - List all saved cards
- customersListSavedPaymentMethods - List all saved payment methods
- customersListUserReviews - Retrieve all reviews
- customersUpdateAddressDetail - Update particular address
- marketplaceGetProductDetail - Retrieve a product detail
- marketplaceGetVariantDetail - Retrieve variant detail
- marketplaceListCategories - List all categories
- marketplaceListCrosssellProducts - Retrieve cross-sell products
- marketplaceListProductReviews - List all product reviews
- marketplaceListProducts - List all products
- marketplaceListProductVariants - Retrieve product variants
- marketplaceListSimilarProducts - Retrieve similar products
- marketplaceListSkus - List all SKUs
- marketplaceListUpsellProducts - Retrieve up-sell products
- marketplaceSearchProducts - Search products
- ordersCancelOrder - Cancel order
- ordersCreateOrder - Create order
- ordersGetOrderDetail - Retrieve order detail
- ordersGetPaymentStatus - Retrieve payment status
- ordersListOrders - Retrieve all orders
- ordersListOrderShipments - Retrieve order shipments
- ordersRetryOrderPayment - Retry payment
- paymentsGetCardInfo - Get card information
- storeGetSellerDetail - Retrieve seller detail
- storeListSellerReviews - List seller reviews
Some of the endpoints in this SDK support retries. If you use the SDK without any configuration, it will fall back to the default retry strategy provided by the API. However, the default retry strategy can be overridden on a per-operation basis, or across the entire SDK.
To change the default retry strategy for a single API call, simply provide a retryConfig object to the call:
`typescript
import { CeStorefront } from "ce-storefront";
const ceStorefront = new CeStorefront();
async function run() {
const result = await ceStorefront.auth.getAnonymousToken({
xApiKey: "
}, {
retries: {
strategy: "backoff",
backoff: {
initialInterval: 1,
maxInterval: 50,
exponent: 1.1,
maxElapsedTime: 100,
},
retryConnectionErrors: false,
},
});
console.log(result);
}
run();
`
If you'd like to override the default retry strategy for all operations that support retries, you can provide a retryConfig at SDK initialization:
`typescript
import { CeStorefront } from "ce-storefront";
const ceStorefront = new CeStorefront({
retryConfig: {
strategy: "backoff",
backoff: {
initialInterval: 1,
maxInterval: 50,
exponent: 1.1,
maxElapsedTime: 100,
},
retryConnectionErrors: false,
},
});
async function run() {
const result = await ceStorefront.auth.getAnonymousToken({
xApiKey: "
});
console.log(result);
}
run();
`
CeStorefrontError is the base class for all HTTP error responses. It has the following properties:
| Property | Type | Description |
| ------------------- | ---------- | --------------------------------------------------------------------------------------- |
| error.message | string | Error message |error.statusCode
| | number | HTTP response status code eg 404 |error.headers
| | Headers | HTTP response headers |error.body
| | string | HTTP body. Can be empty string if no body is returned. |error.rawResponse
| | Response | Raw HTTP response |error.data$
| | | Optional. Some errors may contain structured data. See Error Classes. |
typescript
import { CeStorefront } from "ce-storefront";
import * as errors from "ce-storefront/models/errors";const ceStorefront = new CeStorefront();
async function run() {
try {
const result = await ceStorefront.auth.getAnonymousToken({
xApiKey: "",
});
console.log(result);
} catch (error) {
// The base class for HTTP error responses
if (error instanceof errors.CeStorefrontError) {
console.log(error.message);
console.log(error.statusCode);
console.log(error.body);
console.log(error.headers);
// Depending on the method different errors may be thrown
if (error instanceof errors.BadRequest) {
console.log(error.data$.message); // string
console.log(error.data$.success); // boolean
console.log(error.data$.code); // string
console.log(error.data$.error); // errors.ErrorT
}
}
}
}
run();
`$3
Primary errors:
* CeStorefrontError: The base class for HTTP error responses.
Unauthorized: Not authorized for given operation on the Resource. Status code 401.
NotFound: Requested resource not found. Status code 404. Less common errors (7)
ConnectionError: HTTP client was unable to make a request to a server.
* RequestTimeoutError: HTTP request timed out due to an AbortSignal signal.
* RequestAbortedError: HTTP request was aborted by the client.
* InvalidRequestError: Any input used to create a request is invalid.
* UnexpectedClientError: Unrecognised or unexpected error.CeStorefrontError:
BadRequest: Bad request. Status code 400. Applicable to 32 of 66 methods.
* ResponseValidationError: Type mismatch between the data returned from the server and the structure expected by the SDK. See error.rawValue for the raw value and error.pretty() for a nicely formatted multi-line string.\* Check the method documentation to see if the error is applicable.
Server Selection
$3
You can override the default server globally by passing a server name to the
server: keyof typeof ServerList optional parameter when initializing the SDK client instance. The selected server will then be used as the default on the operations that use it. This table lists the names associated with the available servers:| Name | Server | Variables | Description |
| --------- | ------------------------------------------------------------------- | ---------- | -------------- |
|
staging | https://staging.api.commercengine.io/api/v1/{store_id}/storefront | store_id | Staging Server |
| prod | https://prod.api.commercengine.io/api/v1/{store_id}/storefront | store_id | Prod Server |If the selected server has variables, you may override its default values through the additional parameters made available in the SDK constructor:
| Variable | Parameter | Default | Description |
| ---------- | ----------------- | ------------ | ----------- |
|
store_id | storeId: string | "store_id" | Store ID |#### Example
`typescript
import { CeStorefront } from "ce-storefront";const ceStorefront = new CeStorefront({
server: "staging",
storeId: "store_id",
});
async function run() {
const result = await ceStorefront.auth.getAnonymousToken({
xApiKey: "",
});
console.log(result);
}
run();
`$3
The default server can also be overridden globally by passing a URL to the
serverURL: string optional parameter when initializing the SDK client instance. For example:
`typescript
import { CeStorefront } from "ce-storefront";const ceStorefront = new CeStorefront({
serverURL: "https://staging.api.commercengine.io/api/v1/store_id/storefront",
});
async function run() {
const result = await ceStorefront.auth.getAnonymousToken({
xApiKey: "",
});
console.log(result);
}
run();
`
Custom HTTP Client
The TypeScript SDK makes API calls using an
HTTPClient that wraps the native
Fetch API. This
client is a thin wrapper around fetch and provides the ability to attach hooks
around the request lifecycle that can be used to modify the request or handle
errors and response.The
HTTPClient constructor takes an optional fetcher argument that can be
used to integrate a third-party HTTP client or when writing tests to mock out
the HTTP client and feed in fixtures.The following example shows how to use the
"beforeRequest" hook to to add a
custom header and a timeout to requests and how to use the "requestError" hook
to log errors:`typescript
import { CeStorefront } from "ce-storefront";
import { HTTPClient } from "ce-storefront/lib/http";const httpClient = new HTTPClient({
// fetcher takes a function that has the same signature as native
fetch.
fetcher: (request) => {
return fetch(request);
}
});httpClient.addHook("beforeRequest", (request) => {
const nextRequest = new Request(request, {
signal: request.signal || AbortSignal.timeout(5000)
});
nextRequest.headers.set("x-custom-header", "custom value");
return nextRequest;
});
httpClient.addHook("requestError", (error, request) => {
console.group("Request Error");
console.log("Reason:",
${error});
console.log("Endpoint:", ${request.method} ${request.url});
console.groupEnd();
});const sdk = new CeStorefront({ httpClient: httpClient });
`
Authentication
$3
This SDK supports the following security scheme globally:
| Name | Type | Scheme |
| --------------- | ---- | ----------- |
|
authorization | http | HTTP Bearer |To authenticate with the API the
authorization parameter must be set when initializing the SDK client instance. For example:
`typescript
import { CeStorefront } from "ce-storefront";const ceStorefront = new CeStorefront({
authorization: "",
});
async function run() {
const result = await ceStorefront.auth.generateOtp({
requestBody: {
channel: "email",
email: "Ahmed80@gmail.com",
otpAction: "verify-email",
},
});
console.log(result);
}
run();
`$3
Some operations in this SDK require the security scheme to be specified at the request level. For example:
`typescript
import { CeStorefront } from "ce-storefront";const ceStorefront = new CeStorefront();
async function run() {
const result = await ceStorefront.auth.getAnonymousToken({
xApiKey: "",
});
console.log(result);
}
run();
`
Debugging
You can setup your SDK to emit debug logs for SDK requests and responses.
You can pass a logger that matches
console's interface as an SDK option.> [!WARNING]
> Beware that debug logging will reveal secrets, like API tokens in headers, in log messages printed to a console or files. It's recommended to use this feature only during local development and not in production.
`typescript
import { CeStorefront } from "ce-storefront";const sdk = new CeStorefront({ debugLogger: console });
``This SDK is in beta, and there may be breaking changes between versions without a major version update. Therefore, we recommend pinning usage
to a specific package version. This way, you can install the same version each time without breaking changes unless you are intentionally
looking for the latest version.
While we value open-source contributions to this SDK, this library is generated programmatically. Any manual changes added to internal files will be overwritten on the next generation.
We look forward to hearing your feedback. Feel free to open a PR or an issue with a proof of concept and we'll do our best to include it in a future release.