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 and its publishable key. For where the key comes from, see Using the publishable key.
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, 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 |
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 |
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. 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 one object with an API class on each property. 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.
| Property | Class | Area |
|---|---|---|
products |
ProductsApi |
Products by id or slug |
collections |
CollectionsApi |
Collections |
categories |
CategoriesApi |
Categories |
search |
SearchApi |
Catalog and blog search, autocomplete |
cart |
CartApi |
Guest and customer cart |
orders |
OrdersApi |
Place orders, guest lookup, customer orders |
payments |
PaymentsApi |
Start a gateway payment, read its state |
paymentMethods |
PaymentMethodsApi |
The store’s enabled payment methods |
shipping |
ShippingApi |
Location areas and shipping quotes |
promotions |
PromotionsApi |
Discount code checks and suggestions |
reviews |
ReviewsApi |
Product reviews and review invitations |
customers |
CustomersApi |
The signed-in customer’s profile and metafields |
addresses |
AddressesApi |
The signed-in customer’s saved addresses |
blog |
BlogApi |
Posts, categories, tags and comments |
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 |
AuthApi is not on this 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. createStoreSdk returns an SDK bound to one store, and its authenticated classes go through the same-origin proxy so the shopper’s cookie turns into a token on the server.
import { createStoreSdk, sdk } from "@ecomweb/storefront-kit";
// Public call: the catalog.const hits = await sdk.search.searchCatalog("my-store", { q: "*", collection: "products" });
// Signed-in call: 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 and pass it to createEcomwebSdk. Every Storefront API request needs 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");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 authenticated 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 authenticated calls, so the browser never holds a token.
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.
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 SDK object from a public and an authenticated HTTP client |
sdk |
The kit’s ready SDK for public calls, with your publishable key |
createStoreSdk |
An SDK bound to one store, with authenticated calls through the proxy |
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 authenticated calls with 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 |