Suggested Structure
The framework renders CMS pages through the catch all routeapp/(pages)/[...slug]. Static folders win over a catch all, so put the store in its own route group next to it.
src/
├── lib/store/
│ ├── client.ts # fetch wrapper: token, session and client headers, errors
│ ├── session.ts # cookies, lazy guest session, recovery from dead tokens
│ ├── catalog.ts # cached catalog reads
│ ├── cart.ts # cart body helper
│ ├── money.ts
│ └── types.ts
└── app/(store)/
├── shop/
│ ├── page.tsx # product list (search, filters, sort, pages)
│ ├── products/[slug]/page.tsx # product page
│ ├── categories/[slug]/page.tsx # category page
│ └── collections/[slug]/page.tsx # collection page
├── cart/
│ ├── page.tsx
│ └── actions.ts # add, update, remove, codes, gifts, shipping
├── checkout/
│ ├── page.tsx # address, shipping, pickup, review, pay
│ ├── actions.ts # verification code, store credit, place order, pay
│ ├── success/page.tsx # Stripe success return
│ └── cancel/page.tsx # Stripe cancel return
└── account/
├── page.tsx # profile
├── actions.ts
├── login/page.tsx
├── register/page.tsx
├── verify-email/page.tsx # link from the verification email
├── reset-password/page.tsx # link from the reset email (also the forgot form)
├── confirm-email/page.tsx # link from the email change email
├── orders/page.tsx
├── orders/[publicId]/page.tsx
└── security/page.tsx # password, email change, sessions
A store route shadows a CMS page with the same slug. Do not create CMS pages called
shop, cart, checkout or
account.Keep the Visitor’s Language on Store Pages
The framework’sproxy.ts sets the NEXT_LOCALE cookie from the first path segment, or to the default locale when there is none. Store pages have no locale prefix (/cart, /checkout/success, /account/verify-email), so the proxy would switch every visitor back to the default language. Change proxy.ts so it keeps the current cookie on store paths:
src/proxy.ts
import { NextRequest, NextResponse } from "next/server";
const PUBLIC_FILE = /\.(.*)$/;
const STORE_PATHS = ["/shop", "/cart", "/checkout", "/account"];
export async function proxy(req: NextRequest) {
if (
req.nextUrl.pathname.startsWith("/_next") ||
req.nextUrl.pathname.includes("/api/") ||
PUBLIC_FILE.test(req.nextUrl.pathname)
) {
return;
}
const data: { locales: string[]; default: string } = await fetch(
`${process.env.API_BASE_URL}/api/littlebox-strapi-suite/modules/locales`,
{
method: "GET",
headers: {
Authorization: `Bearer ${process.env.API_TOKEN}`,
"Content-Type": "application/json",
},
},
).then((res) => res.json());
const path = req.nextUrl.pathname.split("/");
const pathLocale = data.locales.find((locale: string) => locale === path[1]);
const isStorePath = STORE_PATHS.some(
(p) => req.nextUrl.pathname === p || req.nextUrl.pathname.startsWith(`${p}/`),
);
const current = req.cookies.get("NEXT_LOCALE")?.value;
const kept = isStorePath && current && data.locales.includes(current) ? current : undefined;
const locale = pathLocale || kept || data.default;
const response = NextResponse.next();
response.cookies.set("NEXT_LOCALE", locale);
return response;
}
slugs).
src/app/components/store-language-switcher.tsx
"use client";
import Cookies from "js-cookie";
import { useRouter } from "next/navigation";
import { useLocale } from "@/app/core/contexts/locale";
export default function StoreLanguageSwitcher({ slugs }: { slugs?: Record<string, string> }) {
const router = useRouter();
const { get, current } = useLocale();
function change(locale: string) {
Cookies.set("NEXT_LOCALE", locale, { path: "/" });
if (slugs?.[locale]) router.push(`/shop/products/${slugs[locale]}`);
router.refresh();
}
return (
<select value={current} onChange={(e) => change(e.target.value)}>
{get().map((locale) => (
<option key={locale} value={locale}>
{locale.toUpperCase()}
</option>
))}
</select>
);
}
Crawlers have no cookie, so they always see store pages in the default language. If you need product pages indexed
in several languages, add a locale segment to the store routes (for example
/pt/shop/...) and pass that locale to
the API instead of the cookie.The API Client
This helper adds the token, the session headers and the client headers to every call, and turns error answers into a typed error. Installserver-only (npm install server-only) so a client component can never import it by mistake.
src/lib/store/client.ts
import "server-only";
import { headers } from "next/headers";
const BASE_URL = `${process.env.API_BASE_URL}/api/littlebox-strapi-suite/ecommerce/storefront`;
export type StoreIssue = { path: string; code: string; detail?: string };
export type StoreAuth = { checkout?: string | null; customer?: string | null };
export class StoreApiError extends Error {
constructor(
readonly status: number,
readonly code: string | null,
readonly errors: StoreIssue[] = [],
readonly retryAfter: number | null = null,
readonly reason: string | null = null,
) {
super(code ?? `Storefront API answered ${status}`);
}
}
type StoreFetchOptions = {
method?: "GET" | "POST" | "PUT" | "DELETE";
query?: Record<string, string | number | null | undefined>;
body?: unknown;
auth?: StoreAuth;
idempotencyKey?: string;
/** Catalog only: cache the answer for this many seconds (no session or client headers). */
revalidate?: number;
};
/** The browser's IP and user agent. Adapt the IP header to what YOUR hosting sets and trusts. */
async function clientHeaders(): Promise<Record<string, string>> {
const h = await headers();
const ip = h.get("x-real-ip")?.trim() || h.get("x-forwarded-for")?.split(",")[0]?.trim() || "";
const userAgent = h.get("user-agent") ?? "";
return {
...(ip ? { "X-Storefront-Client-IP": ip } : {}),
...(userAgent ? { "X-Storefront-Client-User-Agent": userAgent } : {}),
};
}
export async function storeFetch<T>(path: string, options: StoreFetchOptions = {}): Promise<T> {
const { method = "GET", query, body, auth, idempotencyKey, revalidate } = options;
const url = new URL(`${BASE_URL}${path}`);
for (const [key, value] of Object.entries(query ?? {})) {
if (value !== undefined && value !== null && value !== "") url.searchParams.set(key, String(value));
}
const cached = revalidate !== undefined;
const requestHeaders: Record<string, string> = {
Authorization: `Bearer ${process.env.STOREFRONT_API_TOKEN}`,
Accept: "application/json",
...(cached ? {} : await clientHeaders()),
};
if (body !== undefined) requestHeaders["Content-Type"] = "application/json";
if (!cached && auth?.checkout) requestHeaders["X-Checkout-Session"] = auth.checkout;
if (!cached && auth?.customer) requestHeaders["X-Customer-Token"] = auth.customer;
if (idempotencyKey) requestHeaders["Idempotency-Key"] = idempotencyKey;
const response = await fetch(url, {
method,
headers: requestHeaders,
body: body === undefined ? undefined : JSON.stringify(body),
...(cached ? { next: { revalidate } } : { cache: "no-store" as const }),
});
if (response.status === 204) return undefined as T;
const json = await response.json().catch(() => null);
if (!response.ok) {
const details = json?.error?.details ?? {};
const retryAfter = Number(response.headers.get("Retry-After"));
throw new StoreApiError(
response.status,
details.code ?? null,
details.errors ?? [],
retryAfter > 0 ? retryAfter : null,
details.reason ?? null,
);
}
return json as T;
}
Sessions and Cookies Helper
Next.js lets you write cookies only in Server Actions and Route Handlers. Server Components can only read them. So open sessions and drop dead tokens inside actions, and treat a401 in a Server Component as “no session” for that render.
src/lib/store/session.ts
import "server-only";
import { cookies } from "next/headers";
import { storeFetch, StoreApiError, type StoreAuth } from "./client";
export const CHECKOUT_COOKIE = "store_checkout";
export const CUSTOMER_COOKIE = "store_customer";
const cookieOptions = (expiresAt: string) => ({
httpOnly: true,
secure: process.env.NODE_ENV === "production",
sameSite: "lax" as const,
path: "/",
expires: new Date(expiresAt),
});
/** Reads both tokens. Works everywhere, Server Components included. */
export async function readAuth(): Promise<StoreAuth> {
const jar = await cookies();
return {
checkout: jar.get(CHECKOUT_COOKIE)?.value ?? null,
customer: jar.get(CUSTOMER_COOKIE)?.value ?? null,
};
}
/* The functions below write cookies: call them from Server Actions or Route Handlers only. */
export async function saveCustomerToken(token: string, expiresAt: string) {
(await cookies()).set(CUSTOMER_COOKIE, token, cookieOptions(expiresAt));
}
export async function dropCustomerToken() {
(await cookies()).delete(CUSTOMER_COOKIE);
}
export async function dropCheckoutToken() {
(await cookies()).delete(CHECKOUT_COOKIE);
}
/** Opens a new guest checkout session and stores its token. */
async function openGuestSession(): Promise<string> {
const opened = await storeFetch<{ token: string; expiresAt: string }>("/checkout/session", { method: "POST" });
(await cookies()).set(CHECKOUT_COOKIE, opened.token, cookieOptions(opened.expiresAt));
return opened.token;
}
/**
* Runs a call with the session it needs and recovers once from a dead token.
* - "checkout": the login session when there is one, otherwise a guest session (opened lazily).
* - "guest": always a guest session (register, login, verify email, reset password).
* Pass `retry: false` when repeating the call on a brand new session makes no sense (orders).
*/
export async function withSession<T>(
need: "checkout" | "guest",
call: (auth: StoreAuth) => Promise<T>,
{ retry = true }: { retry?: boolean } = {},
): Promise<T> {
let { checkout, customer } = await readAuth();
for (let attempt = 0; ; attempt++) {
if ((need === "guest" || !customer) && !checkout) checkout = await openGuestSession();
try {
return await call(need === "guest" ? { checkout } : { checkout, customer });
} catch (error) {
if (!retry || attempt > 0 || !(error instanceof StoreApiError) || error.status !== 401) throw error;
if (error.code === "SESSION_INVALID") {
await dropCheckoutToken();
checkout = null;
} else if (error.code === "CUSTOMER_SESSION_INVALID") {
await dropCustomerToken();
customer = null;
} else {
throw error;
}
}
}
}
src/lib/store/result.ts
import { StoreApiError, type StoreIssue } from "./client";
export type ActionResult<T = undefined> =
| { ok: true; data: T }
| { ok: false; status: number; code: string | null; errors: StoreIssue[]; retryAfter: number | null };
export function toActionError(error: unknown): ActionResult<never> {
if (error instanceof StoreApiError) {
return { ok: false, status: error.status, code: error.code, errors: error.errors, retryAfter: error.retryAfter };
}
console.error(error);
return { ok: false, status: 500, code: null, errors: [], retryAfter: null };
}
Shared Types
src/lib/store/types.ts
export type PublicImage = { url: string; width: number; height: number; alt: string; cover: boolean };
export type CategoryRef = { id: number; name: string; slug: string };
export type Pagination = { page: number; pageSize: number; total: number; pageCount: number };
export type ProductListItem = {
id: number;
slug: string;
name: string;
shortDescription: string;
image: PublicImage | null;
priceMin: number;
priceMax: number;
compareAtPriceMin: number | null;
currency: "EUR";
available: boolean;
category: (CategoryRef & { path: CategoryRef[] }) | null;
tags: { id: number; name: string }[];
};
export type Variant = {
id: number;
option: string;
sku: string;
price: number;
compareAtPrice: number | null;
taxRate: number;
available: boolean;
images: PublicImage[];
};
export type Product = Omit<ProductListItem, "image"> & {
slugs: Record<string, string>;
description: string;
images: PublicImage[];
variants: Variant[];
};
export type GiftChoice = number | number[];
export type StoredCart = {
lines: { variantId: number; quantity: number }[];
promotionCodes: string[];
giftChoices: Record<string, GiftChoice>;
email: string | null;
destination: { country: string; postalCode?: string } | null;
shippingMethod: { providerId: string; serviceId: string } | null;
locale: string | null;
};
export type PickupStore = {
id: string;
name: string;
address: string;
address2: string | null;
postalCode: string;
city: string;
country: string;
};
export type ShippingOption = {
providerId: string;
serviceId: string;
name: string;
price: number;
estimatedDays: number | null;
requiresPickupPoint?: true;
pickupPoints?: PickupStore[];
};
export type CodeStatus =
| "APPLIED"
| "NOT_FOUND"
| "NOT_ELIGIBLE"
| "EMAIL_NOT_VERIFIED"
| "EXPIRED"
| "USAGE_LIMIT_REACHED"
| "CONDITIONS_NOT_MET"
| "CONFLICT"
| "NO_BENEFIT"
| "AWAITING_SHIPPING"
| "GIFT_UNAVAILABLE";
export type Quote = {
lines: {
variantId: number;
productId: number;
sku: string;
name: string;
option: string | null;
imageUrl: string | null;
unitPrice: number;
unitDiscount: number;
quantity: number;
total: number;
tax: number;
isGift: boolean;
promotionIds: number[];
}[];
promotions: {
promotionId: number;
name: string;
code: string | null;
amount: number;
classes: ("PRODUCT_DISCOUNT" | "ORDER_DISCOUNT" | "SHIPPING_DISCOUNT")[];
}[];
codes: { code: string; status: CodeStatus; message: string }[];
giftOptions: {
promotionId: number;
benefitIndex: number;
quantity: number;
repetitions: number;
selected: number[];
selectedVariantId: number | null;
variants: {
variantId: number;
sku: string;
name: string;
option: string | null;
imageUrl: string | null;
available: boolean;
}[];
}[];
unavailableGifts: { promotionId: number; name: string; code: string | null }[];
totals: {
itemsOriginal: number;
productDiscount: number;
subtotal: number;
orderDiscount: number;
shippingOriginal: number | null;
shippingDiscount: number;
shippingTotal: number | null;
total: number;
totalDiscount: number;
};
taxes: { rate: number; base: number; vat: number; gross: number }[];
currency: "EUR";
shippingOptions: ShippingOption[] | null;
selectedShipping: ShippingOption | null;
};
export type PaymentResult = "PAID" | "PROCESSING" | "UNPAID" | "CANCELLED";
export type OrderStatus = {
publicId: string;
reference: string;
createdAt: string | null;
locale: string;
orderStatus: "OPEN" | "ARCHIVED" | "CANCELLED";
paymentStatus: "PENDING" | "PARTIALLY_PAID" | "PAID" | "PARTIALLY_REFUNDED" | "REFUNDED" | "REFUND_DUE";
paymentResult: PaymentResult;
currency: "EUR";
totals: {
itemsOriginal: number;
productDiscount: number;
subtotal: number;
orderDiscount: number;
shippingTotal: number;
total: number;
paid: number;
due: number;
};
lines: {
name: string;
option: string | null;
sku: string;
quantity: number;
unitPrice: number;
unitDiscount: number;
total: number;
isGift: boolean;
}[];
promotions: { name: string; amount: number }[];
shipping: { name: string } | null;
};
export type AccountProfile = {
id: number;
email: string;
pendingEmail: string | null;
firstName: string;
lastName: string;
phone: string | null;
locale: string | null;
createdAt: string | null;
};