AgentSkillsCN

ce-setup

在任意项目中快速搭建 Commerce Engine 的 TypeScript SDK。包括框架检测、令牌存储方案选择、环境变量配置,以及迁移指南。

SKILL.md
--- frontmatter
name: ce-setup
description: Set up the Commerce Engine TypeScript SDK in any project. Framework detection, token storage selection, environment variables, and migration guidance.
license: MIT
allowed-tools: Bash
metadata:
  author: commercengine
  version: "1.0.0"

Setting Up Commerce Engine

This skill sets up the Commerce Engine TypeScript SDK for your project.

Quick Reference

StepAction
1. Detect frameworkCheck package.json and config files
2. Install SDKnpm install @commercengine/storefront-sdk
3. Choose token storageBrowserTokenStorage (SPA), CookieTokenStorage (SSR), MemoryTokenStorage (Node.js)
4. Set env varsCE_STORE_ID and CE_API_KEY
5. Initialize SDKCreate lib/storefront.ts
6. Get anonymous tokensdk.auth.getAnonymousToken() before any API call

Framework Detection

Check package.json and config files to identify the framework:

IndicatorFrameworkSDK PackageToken Storage
next in deps + next.config.*Next.js@commercengine/storefront-sdk-nextjsCookieTokenStorage
vite.config.ts + @vitejs/plugin-reactReact SPA@commercengine/storefront-sdkBrowserTokenStorage
vite.config.ts + @vitejs/plugin-vueVue SPA@commercengine/storefront-sdkBrowserTokenStorage
svelte.config.jsSvelte/SvelteKit@commercengine/storefront-sdkBrowserTokenStorage
solid-js in depsSolid@commercengine/storefront-sdkBrowserTokenStorage
express in depsExpress/Node.js@commercengine/storefront-sdkMemoryTokenStorage
None of aboveVanilla JS@commercengine/storefront-sdkBrowserTokenStorage

Decision Tree

code
User Request: "Set up Commerce Engine" / "Add e-commerce"
    │
    ├─ Read package.json + config files
    │
    ├─ Next.js detected?
    │   ├─ YES → Install @commercengine/storefront-sdk-nextjs
    │   │        → Use storefront() function + StorefrontSDKInitializer
    │   │        → See ce-nextjs-patterns for advanced usage
    │   └─ NO → Install @commercengine/storefront-sdk
    │
    ├─ Choose token storage based on framework
    │
    ├─ Set environment variables
    │
    └─ Initialize SDK + get anonymous token

Setup by Framework

Next.js (App Router)

bash
npm install @commercengine/storefront-sdk-nextjs
typescript
// lib/storefront.ts
export { storefront } from "@commercengine/storefront-sdk-nextjs";
typescript
// app/layout.tsx
import { StorefrontSDKInitializer } from "@commercengine/storefront-sdk-nextjs/client";

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html>
      <body>
        <StorefrontSDKInitializer />
        {children}
      </body>
    </html>
  );
}
env
# .env.local
NEXT_PUBLIC_STORE_ID=your-store-id
NEXT_PUBLIC_API_KEY=your-api-key

React / Vue / Svelte / Solid (SPA)

bash
npm install @commercengine/storefront-sdk
typescript
// lib/storefront.ts
import StorefrontSDK, { Environment, BrowserTokenStorage } from "@commercengine/storefront-sdk";

export const sdk = new StorefrontSDK({
  storeId: import.meta.env.VITE_STORE_ID,
  environment: import.meta.env.PROD ? Environment.Production : Environment.Staging,
  apiKey: import.meta.env.VITE_API_KEY,
  tokenStorage: new BrowserTokenStorage("myapp_"),
});
env
# .env
VITE_STORE_ID=your-store-id
VITE_API_KEY=your-api-key

Node.js / Express

bash
npm install @commercengine/storefront-sdk
typescript
// src/lib/storefront.ts
import StorefrontSDK, { Environment, MemoryTokenStorage } from "@commercengine/storefront-sdk";

const sdk = new StorefrontSDK({
  storeId: process.env.CE_STORE_ID!,
  environment: process.env.NODE_ENV === "production" ? Environment.Production : Environment.Staging,
  apiKey: process.env.CE_API_KEY!,
  tokenStorage: new MemoryTokenStorage(),
  timeout: 30000,
});

export default sdk;

Token Storage Guide

StorageUse CasePersistenceSSR Safe
BrowserTokenStorageSPAs (React, Vue, Svelte, Solid)localStorageNo
CookieTokenStorageSSR frameworks (Next.js)CookiesYes
MemoryTokenStorageServer-side (Node.js, Express)In-memoryYes

First API Call

After setup, always authenticate anonymously before making any API calls:

typescript
// Every visitor starts as anonymous
const { data, error } = await sdk.auth.getAnonymousToken();

if (error) {
  console.error("Auth failed:", error.message);
} else {
  // Tokens are automatically managed by the SDK
  // Now you can call any API
  const { data: products } = await sdk.catalog.listProducts();
}

Environment Variables

VariableRequiredDescription
CE_STORE_ID / NEXT_PUBLIC_STORE_IDYesYour store identifier
CE_API_KEY / NEXT_PUBLIC_API_KEYYesStorefront API key (safe for client-side)
NEXT_BUILD_CACHE_TOKENSNoSet true for faster Next.js builds with token caching

Default Headers

The SDK supports defaultHeaders in the config — headers that are automatically sent with every API call. This is useful for B2B storefronts with customer groups (retailers, stockists, distributors), where pricing and promotions vary by group.

typescript
const sdk = new StorefrontSDK({
  storeId: "...",
  apiKey: "...",
  tokenStorage: new BrowserTokenStorage("myapp_"),
  defaultHeaders: {
    customer_group_id: "01JHS28V83KDWTRBXXJQRTEKA0",
  },
});

Set the customer_group_id after the user logs in (from the user's profile or auth response). All SDK methods that support customer group pricing will automatically receive it — no need to pass it on every call. See catalog/ § "Customer Groups & Pricing" for what it affects.

Analytics

Analytics are server-side and automated. Commerce Engine collects e-commerce events per the Segment spec. Merchants pipe these events into Segment, Rudderstack, or other tools via integrations in the Admin dashboard. Nothing needs to be done on the storefront to enable or disable analytics.

Common Pitfalls

LevelIssueSolution
CRITICALMissing anonymous authMust call sdk.auth.getAnonymousToken() before any API call
CRITICALExposing admin API keysOnly storefront API keys (CE_API_KEY) are safe for client-side
HIGHWrong token storage for SSRUse CookieTokenStorage for Next.js, not BrowserTokenStorage
HIGHMissing env varsSDK throws if storeId or apiKey is missing — check env var names
MEDIUMMissing StorefrontSDKInitializerRequired in Next.js root layout for automatic anonymous auth
MEDIUMWrong environmentUse Environment.Staging for dev, Environment.Production for prod

See Also

  • auth/ - Authentication & login flows
  • nextjs-patterns/ - Advanced Next.js patterns with storefront()
  • cart-checkout/ - Cart management after setup

Documentation