Advanced
SSR & Next.js
Server-side rendering and Next.js integration
Custom Fetch
For SSR environments where globalThis.fetch behaves differently, pass a custom fetch:
import { BehioStorefront } from '@behio/storefront-sdk';
const client = new BehioStorefront({
apiKey: process.env.BEHIO_API_KEY!,
baseUrl: process.env.BEHIO_API_URL!,
fetch: fetch, // Node.js 18+ built-in fetch
});Next.js App Router
Server Components
Use the client directly in server components:
// app/products/page.tsx
import { BehioStorefront } from '@behio/storefront-sdk';
const client = new BehioStorefront({
apiKey: process.env.BEHIO_PUBLIC_KEY!,
baseUrl: process.env.BEHIO_API_URL!,
});
export default async function ProductsPage() {
const { items } = await client.catalog.getProducts({ limit: 12 });
return (
<div>
{items.map(p => <ProductCard key={p.id} product={p} />)}
</div>
);
}Client Components with Hooks
For interactive features (cart, auth), use hooks in client components:
'use client';
import { useCart, useAddToCart } from '@behio/storefront-sdk/react';
export function AddToCartButton({ productId }: { productId: string }) {
const addItem = useAddToCart();
return (
<button
onClick={() => addItem.mutateAsync({ productId, quantity: 1 })}
disabled={addItem.isPending}
>
{addItem.isPending ? 'Adding...' : 'Add to Cart'}
</button>
);
}Token Persistence
For SSR, store tokens in HTTP-only cookies:
// middleware.ts
import { NextResponse } from 'next/server';
export function middleware(request) {
const token = request.cookies.get('cart_session')?.value;
// Pass to client via header or context
}Environment Variables
BEHIO_PUBLIC_KEY=pk_live_your_key
BEHIO_API_URL=https://api.yourdomain.com