Next.js wrapper for the CommerceEngine Storefront SDK. Provides the perfect developer experience with automatic context detection, universal API, and zero configuration complexity.
NEXT_PUBLIC_STORE_ID=your-store-idNEXT_PUBLIC_API_KEY=your-api-key# Environment (defaults to "staging")NEXT_PUBLIC_ENVIRONMENT=staging # or "production"
Environment variables are mandatory - the SDK will throw helpful errors if missing
2
Create Your Storefront Configuration
Create lib/storefront.ts in your project:
Copy
// lib/storefront.tsimport { storefront } from "@commercengine/storefront-sdk-nextjs";// Re-export for easy importing everywhereexport { storefront };// Import any types you needexport type { UserInfo, SupportedDefaultHeaders, components, operations} from "@commercengine/storefront-sdk-nextjs";
The storefront function works with minimal configuration - environment variables handle everything automatically
3
Initialize in Root Layout
Copy
// app/layout.tsximport { StorefrontSDKInitializer } from "@commercengine/storefront-sdk-nextjs/client";export default function RootLayout({ children }: { children: React.ReactNode }) { return ( <html lang="en"> <body> <StorefrontSDKInitializer /> {children} </body> </html> );}
The StorefrontSDKInitializer is required for automatic anonymous token creation and user session continuity
4
Use Anywhere with Universal Import
Copy
// Import your configured storefront everywhereimport { storefront } from "@/lib/storefront";import { cookies } from "next/headers"; // Only for server contexts// ✅ Client Component - No cookies neededconst products = await storefront().catalog.listProducts();// ✅ Server Component, Server Action, or API Route - MUST pass cookiesconst products = await storefront(cookies()).catalog.listProducts();// ✅ Root Layout - Special exception with explicit flagconst products = await storefront({ isRootLayout: true }).catalog.listProducts();// ✅ SSG/ISR (build contexts) - Automatic fallback to memory storage// (NEXT_BUILD_CACHE_TOKENS=true enables this)const products = await storefront().catalog.listProducts();
The SDK enforces proper cookie passing in server contexts to protect user session continuity and analytics tracking
Root Layout requires explicit flag since it’s outside request context. Passing this flag will instruct the SDK to fallback to MemoryStore when rendering the root layout as the root layout runs on both server and client before cookie context is available.
Copy
// app/layout.tsximport { StorefrontSDKInitializer } from "@commercengine/storefront-sdk-nextjs/client";import { storefront } from "@/lib/storefront";// Root Layout requires explicit flag - no request context availableconst sdk = storefront({ isRootLayout: true });const { data: storeConfig } = await sdk.store.getStoreConfig();export default function RootLayout({ children }: { children: React.ReactNode }) { return ( <html lang="en"> <body> <StorefrontSDKInitializer /> <h1>Welcome to {storeConfig?.store_config?.brand.name}</h1> {children} </body> </html> );}
⚠️ Important: Any authentication endpoint that returns tokens (like loginWithPassword, verifyOtp, register, etc.) must be called in contexts where cookies can be set and managed:
✅ Server Actions (recommended for authentication flows)
✅ API Routes (/api directory)
✅ Client Components (browser environment)
❌ Server Components (cannot set cookies, tokens won’t persist)
This ensures the SDK can automatically handle token storage and user session continuity.
The SDK automatically creates anonymous tokens via the StorefrontSDKInitializer component imported in your root layout. If this component is not imported (not recommended), a new token will be minted for each request as a fallback. It is highly recommended to use the StorefrontSDKInitializer and ensure all token-returning endpoints are called from request contexts that can set cookies.
Copy
// This works everywhere - creates anonymous token automaticallyconst { data: products } = await storefront(cookies()).catalog.listProducts();
“Server context requires cookies for user continuity!”
Copy
// ❌ Wrong - server context without cookies (breaks user sessions)storefront() // ✅ Correct - server context with cookiesstorefront(cookies())// ✅ Root Layout exceptionstorefront({ isRootLayout: true })
Missing Environment Variables
Copy
# Ensure your .env.local has the required variables:NEXT_PUBLIC_STORE_ID=your-store-idNEXT_PUBLIC_API_KEY=your-api-key
Symptoms: Initialization errors, token creation failures
Fix: Verify environment variables are set and accessible
Client vs Server Context
“Cookie store passed in client environment”
Copy
// ❌ Wrong - client component with cookiesstorefront(cookies())// ✅ Correct - client component without cookies storefront()
For complete API documentation of all available endpoints, visit SDK API ReferenceThe Next.js SDK provides access to all the same endpoints as the core SDK:
sdk.auth.* - Authentication and user management
sdk.customer.* - Customer profiles and preferences
This Next.js adapter pattern ensures your authentication works consistently across Next.js server components, client components, API routes, and server actions with zero complexity for token management.