Install and configure the SDK
This page takes you from an empty Next.js app to a storefront that can call the Storefront API. It names the SDK classes and kit helpers you use at each step and links each one to its reference page. You need a store, its publishable key and a storefront secret key. For where the keys come from, see Publishable and storefront secret keys.
Install the packages
Section titled “Install the packages”@ecomweb/sdk is the typed client for the Storefront API. @ecomweb/storefront-kit sits on top of it and adds the sign-in session, the cart, checkout, order status and the middleware. The kit needs Next.js 16 or later and React 19 or later, and it depends on the SDK.
pnpm add @ecomweb/sdk @ecomweb/storefront-kitKeep both packages on the same version. They are released together, and the platform reads both versions from every request to tell you when a storefront is out of date. To move to a newer release, see Upgrade the storefront kit.
The SDK has one entry point, @ecomweb/sdk. The kit has five, and the next sections use each one.
| Import from | Use it in | What it holds |
|---|---|---|
@ecomweb/storefront-kit |
Client and server components | The provider, the hooks, the ready SDK client and formatting helpers |
@ecomweb/storefront-kit/server |
Route handlers and server components | The auth and proxy routes, getServerSdk, requireSession, server config |
@ecomweb/storefront-kit/middleware |
proxy.ts |
The middleware that keeps the shopper’s session fresh |
@ecomweb/storefront-kit/config |
Anywhere | Config parsing, resolveMode, the build-time version check |
@ecomweb/storefront-kit/theme |
Theme code and build tools | defineSchema and defineTheme, with no side effects |
Choose a mode
Section titled “Choose a mode”The kit runs in one of two modes. ECOMWEB_MODE picks it on the server, and NEXT_PUBLIC_ECOMWEB_MODE picks it in the browser and wins when both are set. A mode that is not single or multi stops the app with a configuration error that names the variable. When you set neither, the kit uses single.
| Mode | What it is | Reads |
|---|---|---|
single |
One store is the whole site. Pages live at the site root and same-origin routes under /api. This is the mode for your own storefront. |
NEXT_PUBLIC_ECOMWEB_STORE_REF, NEXT_PUBLIC_ECOMWEB_PUBLISHABLE_KEY, NEXT_PUBLIC_SITE_URL, and optionally NEXT_PUBLIC_ECOMWEB_API_URL. Server only: ECOMWEB_SECRET_KEY |
multi |
The shared EcomWeb storefront, where every store lives under /store/<ref> or on its own domain. |
NEXT_PUBLIC_API_URL, NEXT_PUBLIC_PLATFORM_API_KEY, NEXT_PUBLIC_APP_URL and others. Server only: PLATFORM_SECRET_KEY |
In single mode the API address defaults to https://apibase.ecomweb.app/api/v1. The quickstart shows how to copy ECOMWEB_STORE_REF, ECOMWEB_PUBLISHABLE_KEY and SITE_URL into the NEXT_PUBLIC_ names in next.config.mjs. A missing or invalid value makes the first request fail with a message that lists every variable to fix. The storefront secret key is different: it is set in the server’s environment only, never copied to a NEXT_PUBLIC_ name and never into next.config.mjs. The kit refuses a NEXT_PUBLIC_ variable that holds a value starting sk_. See Publishable and storefront secret keys. resolveMode and publicConfig read the same values from your own code.
import { publicConfig, resolveMode } from "@ecomweb/storefront-kit/config";
console.log(resolveMode(process.env)); // "single"console.log(publicConfig().apiUrl); // "https://apibase.ecomweb.app/api/v1"Create an SDK client
Section titled “Create an SDK client”createEcomwebSdk takes two HTTP clients and returns the public classes only, the ones that read the catalog and content. publicHttp calls public routes and carries the publishable key. authHttp calls routes that need a signed-in shopper. Each class has one method for each Storefront API request in its area. Calling a private class on this object, such as sdk.cart, is a type error.
| Property | Class | Area |
|---|---|---|
products |
ProductsApi |
Products by id or slug |
collections |
CollectionsApi |
Collections |
categories |
CategoriesApi |
Categories |
search |
SearchApi |
Catalog and blog search, autocomplete |
paymentMethods |
PaymentMethodsApi |
The store’s enabled payment methods |
shipping |
ShippingApi |
Location areas |
promotions |
PromotionsApi |
Discount code suggestions |
reviews |
ReviewsApi |
Product reviews (reads) |
blog |
BlogApi |
Posts, categories, tags and comments (reads) |
contentPages |
ContentPagesApi |
Published content pages |
menus |
MenusApi |
Navigation menus |
metaobjects |
MetaobjectsApi |
Custom data entries |
stores |
StoresApi |
The store’s public configuration, by ref, subdomain or domain |
themes |
ThemesApi |
Theme previews |
redirects |
RedirectsApi |
URL redirects the merchant set up |
createEcomwebServerSdk takes the same options plus secretKey, the storefront secret key, and returns every class. Use it in server code only. It adds the storefront secret key to each request as x-storefront-api-key, and it throws when secretKey is blank, when it is a publishable key (pk_) or when it runs in a browser. The extra classes and methods are the private ones.
| Property | Class | Area |
|---|---|---|
cart |
CartApi |
Guest and customer cart |
orders |
OrdersApi |
Place orders, guest lookup, customer orders |
payments |
PaymentsApi |
Start a gateway payment, read its state |
customers |
CustomersApi |
The signed-in customer’s profile and metafields |
addresses |
AddressesApi |
The signed-in customer’s saved addresses |
shipping, promotions, reviews, blog |
the same classes with more methods | Shipping quotes, discount code checks, review submissions and invitations, blog comment submissions |
AuthApi is not on either object. It belongs to one store and one HTTP client, so you build it yourself with new AuthApi(http, storeRef). The kit’s auth routes do that for you.
In a Next.js app, use the clients the kit already made. The kit’s sdk sends your publishable key and works for public calls. In the browser, createStoreSdk returns an SDK bound to one store. Its private classes go through your same-origin backend route, where the proxy adds the storefront secret key and turns the shopper’s cookie into a token. In server components and route handlers, await getServerSdk() returns the server SDK signed with the storefront secret key.
import { createStoreSdk, sdk } from "@ecomweb/storefront-kit";
// Public call: the catalog.const hits = await sdk.search.searchCatalog("my-store", { q: "*", collection: "products" });
// Private call from the browser: the shopper's own addresses.const addresses = await createStoreSdk("my-store").addresses.list("my-store");Outside Next.js, write an HTTP client that returns the SDK’s ApiResponse shape. For a browser, pass it to createEcomwebSdk with the publishable key in x-storefront-api-key. The SDK adds an X-Ecomweb-Client header with its version on top.
import { createEcomwebSdk } from "@ecomweb/sdk";import type { ApiResponse, IHttpClient, RequestOptions } from "@ecomweb/sdk";
const API_URL = "https://apibase.ecomweb.app/api/v1";
function createHttp(publishableKey: string): IHttpClient { async function send<T>(method: string, url: string, body?: unknown, options?: RequestOptions): Promise<ApiResponse<T>> { const response = await fetch(`${API_URL}${url}`, { method, headers: { "Content-Type": "application/json", "x-storefront-api-key": publishableKey, ...options?.headers }, body: body === undefined ? undefined : JSON.stringify(body), signal: options?.signal, }); const json = await response.json().catch(() => ({})); if (response.ok) return { success: true, data: json as T }; return { success: false, error: { message: json.message ?? "Request failed", statusCode: response.status, error: json.code, details: json.details }, }; }
return { get: (url, options) => send("GET", url, undefined, options), post: (url, data, options) => send("POST", url, data, options), put: (url, data, options) => send("PUT", url, data, options), patch: (url, data, options) => send("PATCH", url, data, options), delete: (url, options) => send("DELETE", url, undefined, options), };}
const http = createHttp(process.env.ECOMWEB_PUBLISHABLE_KEY!);const sdk = createEcomwebSdk({ publicHttp: http, authHttp: http });
const store = await sdk.stores.getById("my-store");On your own server, build the server SDK with the storefront secret key. The SDK sets x-storefront-api-key for you, so the client can leave it out. The example reuses the client from the browser example with a placeholder key, which the SDK replaces.
import { createEcomwebServerSdk } from "@ecomweb/sdk";
const serverHttp = createHttp("unused");const serverSdk = createEcomwebServerSdk({ publicHttp: serverHttp, authHttp: serverHttp, secretKey: process.env.ECOMWEB_SECRET_KEY!,});
const cart = await serverSdk.cart.getCart("my-store", sessionId, false);For a browser that needs private calls and has its own proxy, createEcomwebProxiedSdk({ publicHttp, proxyHttp }) sends public calls through publicHttp and private ones through proxyHttp, a same-origin route that holds the storefront secret key. createStoreSdk is that function with the kit’s clients.
An authHttp has to send the shopper’s Authorization: Bearer <access token> header. The kit keeps that token in an httpOnly cookie on the server and never gives it to the browser, which is why it routes private calls through its proxy. If you build your own client, decide where the token lives. The SDK offers createAuthAwareHttpClient with a TokenStorage you supply. It refreshes the session once on a 401 and retries the request.
Wire the provider and middleware
Section titled “Wire the provider and middleware”Three files and one layout connect the kit to your app. The proxy keeps the session fresh. The two route handlers are the same-origin endpoints that sign shoppers in and forward private calls, so the browser never holds a token or the storefront secret key. The backend route now carries every private call, guests included, such as a guest’s cart and checkout, and not only signed-in calls. Without it those calls fail in the browser. In multi mode the same routes answer under /store/<ref>/api/.
import { createStorefrontMiddleware } from "@ecomweb/storefront-kit/middleware";
export default createStorefrontMiddleware();
export const config = { matcher: ["/((?!api|_next/static|_next/image|favicon.ico).*)"],};import { createAuthRoutes } from "@ecomweb/storefront-kit/server";
export const { GET, POST } = createAuthRoutes();import { createBackendProxy } from "@ecomweb/storefront-kit/server";
export const { GET, POST, PUT, PATCH, DELETE } = createBackendProxy();Then wrap your layout in StorefrontKitProvider. It loads the cart and the shopper’s identity for the store you pass. onNotice receives the kit’s messages, such as an item added or a request that failed, so you can show them as toasts. The kit never renders these itself.
import { notFound } from "next/navigation";import { getCachedStore, resolveStoreRef, StorefrontKitProvider } from "@ecomweb/storefront-kit";
export const dynamic = "force-dynamic";
export default async function RootLayout({ children }: { children: React.ReactNode }) { const store = await getCachedStore(await resolveStoreRef()); if (!store) notFound();
return ( <html lang="en"> <body> <StorefrontKitProvider store={store}>{children}</StorefrontKitProvider> </body> </html> );}getCachedStore returns null when the store does not exist, and it throws when the store is suspended or still coming soon. The errors page shows how to handle both.
Server-only code
Section titled “Server-only code”@ecomweb/storefront-kit/server imports server-only, so a client component that imports it fails the build. Use it for route handlers and server components. getServerSdk gives those the server SDK for the current request, signed with the storefront secret key and carrying the shopper’s IP address. Shopper-side methods on it fail with SDK_SHOPPER_CALL_ON_SERVER.
import { getServerSdk } from "@ecomweb/storefront-kit/server";
const sdk = await getServerSdk();const invitation = await sdk.reviews.getReviewInvitation(storeRef, token);import { requireSession, resolveRootStoreRef } from "@ecomweb/storefront-kit/server";
export default async function AccountPage() { const storeRef = (await resolveRootStoreRef())!; const customer = await requireSession(storeRef, "/login"); return <h1>Hello, {customer.name}</h1>;}resolveRootStoreRef returns the configured store in single mode and looks the store up by host in multi mode. requireSession redirects when nobody is signed in. serverConfig reads the server-side values, and readStorePreviewToken reads the token for a store preview. See Customer accounts for the sign-in flow.
Theme settings
Section titled “Theme settings”If you build a theme, the /theme entry point holds the pieces that need no storefront configuration, so build tools can import it. defineSchema declares the settings a merchant can fill in. defineTheme ties the schema to the components for each page.
import { defineSchema } from "@ecomweb/storefront-kit/theme";
export const schema = defineSchema([ { name: "Header", settings: [{ type: "text", id: "announcement", label: "Announcement", default: "Free shipping over 500k" }], },]);Inside a client component, useThemeSettings from the main entry point reads the resolved values. To get a theme’s code onto your machine and deploy it, see Edit a theme’s code and deploy it.
Key methods
Section titled “Key methods”| Method | What it does |
|---|---|
createEcomwebSdk |
Builds the public SDK object from a public and an authenticated HTTP client |
createEcomwebServerSdk |
Builds the full SDK from your clients and a storefront secret key. Server only |
createEcomwebProxiedSdk |
Builds the full SDK for a browser from a public client and a proxy client |
sdk |
The kit’s ready SDK for public calls, with your publishable key |
createStoreSdk |
An SDK bound to one store for the browser, with private calls through the proxy |
getServerSdk |
The server SDK for the current request, signed with the storefront secret key |
createStorefrontMiddleware |
The proxy.ts handler that refreshes sessions and handles redirects |
createAuthRoutes |
The route handlers for sign-in, sign-out and account emails |
createBackendProxy |
The route handlers that forward private calls with the storefront secret key and the shopper’s token |
StorefrontKitProvider |
Loads the cart and identity for a store and passes the kit’s notices to you |
getCachedStore |
Reads a store’s configuration once for each request |
resolveStoreRef |
Gives the store ref for the current route in either mode |
resolveMode |
Reads which mode the environment selects |
publicConfig |
The parsed public configuration |
defineSchema |
Declares a theme’s settings |