Behio Storefront SDK
Advanced

SSR & Next.js

First-render cart data, request isolation and cookie persistence

Fetch storefront data on the server and include it in the first HTML response. Use the Next.js guide for a request-bound client, server-rendered ordinary and bundle cart rows, and native removal forms.

For another SSR framework, construct a new SDK client for each request, restore only that visitor's cookies and write returned sessions in the framework's response handler. Do not share a session-bearing client or query cache globally.

import { BehioStorefront } from '@behio/storefront-sdk';

async function readCart(session: string, apiKey: string, baseUrl: string) {
  const client = new BehioStorefront({ apiKey, baseUrl, fetch });
  client.setCartSession(session);
  const result = await client.cart.get();
  if (result.error) throw new Error('Unable to load the cart.');
  return result.data;
}

SdkResult<T> has data and error; core SDK calls do not directly return the cart or catalog payload. Do not convert a failed request into an empty array or an empty cart. Preserve session cookies during outages and provide retry UI.

Keep authenticated/cart responses private. SSR renderers cannot rotate a single-use refresh token unless they can also persist its replacement. In Next.js, perform rotation in a Server Action or Route Handler and coordinate across tabs.

For React Query enhancements, initialize a QueryClient per server request and hydrate only non-secret cart data under ['behio', 'cart']. Both ordinary items and bundle lines contribute to cart state. useCart({enabled: false}) disables background reads; it does not perform SSR and does not disable mutations.

HTTP-only sessions remain on the server. Native forms and Server Actions keep cart editing functional before hydration and with JavaScript disabled. Validate the raw HTML response and execute these forms in both browser modes.