Components and hooks
Every export of @sevigram/loom and its server entry point @sevigram/loom/server, with its
signature, a minimal example, and where it may run. New to Loom? Start with
Getting started.
@sevigram/loom/serverholds the private token and must not be imported into client code. Import it only from server modules: in a React Router app, a*.server.tsfile or aloader/action. Read the private token (sfprv_…) from a server-only environment variable such asSEVIGRAM_STOREFRONT_PRIVATE_TOKEN, never from aVITE_variable, and never pass it to a component, a loader’s return value, or browser storage. The module throws if it is ever loaded in a browser, and bundlers resolve itsbrowsercondition to a stub that throws too.
npm install @sevigram/loom @sevigram/storefront-client react react-dom@sevigram/storefront-client is a peer dependency, so your app and Loom share one client, one
cart and one set of error classes. React 19.3 or newer.
Where things run. Everything in @sevigram/loom is safe to render on the server. The cart
attaches only after StorefrontProvider mounts in the browser, so the server render and the
first browser render match. Buttons act and hooks fetch only in the browser, with the public
token. Everything in @sevigram/loom/server is server only.
@sevigram/loom
Section titled “@sevigram/loom”StorefrontProvider
Section titled “StorefrontProvider”function StorefrontProvider(props: StorefrontProviderProps): JSX.Element;Gives every Loom component its client, cart, storage and locale. Wrap your app in it once.
| Prop | Type | Notes |
|---|---|---|
client |
StorefrontClient |
From createStorefrontClient({ token }). In the browser, use the public token only. |
storefrontKey |
string |
From await storefrontKey(publicToken). Namespaces the saved cart and checkout state: one cart per key. |
storage |
KeyValueStorage |
Optional. Defaults to browserStorage() (localStorage). Pass a stable instance; a new one re-creates the cart. |
locale |
string |
Optional BCP 47 locale for Money and BookingCalendar. Set it when you render on the server (see below). |
customer |
CustomerSummary | null |
Optional. The signed-in customer your server read ({ first_name, email }), for useCustomer. Other fields are dropped; never put the token in loader data either (hydration serializes it). |
children |
ReactNode |
Set locale to the same value on the server and in the browser, for example from your root
loader. Without it each runtime formats prices and dates its own way and hydration can mismatch.
import { StorefrontProvider } from "@sevigram/loom";import { createStorefrontClient } from "@sevigram/storefront-client";
const client = createStorefrontClient({ token: publicToken });
export function App({ storefrontKey }: { storefrontKey: string }) { return ( <StorefrontProvider client={client} storefrontKey={storefrontKey} locale="en-NG"> <Routes /> </StorefrontProvider> );}StorefrontProviderProps
Section titled “StorefrontProviderProps”interface StorefrontProviderProps { client: StorefrontClient; storefrontKey: string; storage?: KeyValueStorage; locale?: string; customer?: CustomerSummary | null; children?: ReactNode;}The props of StorefrontProvider. Type only.
import { StorefrontProvider, type StorefrontProviderProps } from "@sevigram/loom";
export function ShopShell(props: StorefrontProviderProps) { return <StorefrontProvider {...props} />;}useStorefront
Section titled “useStorefront”function useStorefront(): StorefrontContextValue;Reads the provider’s values. Throws when used outside a StorefrontProvider. Server-safe;
cart is null on the server and during the first browser render.
import { useStorefront } from "@sevigram/loom";import { useEffect, useState } from "react";
export function ShopName() { const { client } = useStorefront(); const [name, setName] = useState(""); useEffect(() => { client.getShop().then((shop) => setName(shop.name)); }, [client]); return <h1>{name}</h1>;}StorefrontContextValue
Section titled “StorefrontContextValue”interface StorefrontContextValue { client: StorefrontClient; /** null on the server and during the first (hydration) render. */ cart: Cart | null; storefrontKey: string; /** The provider's storage prop, or undefined for the default browserStorage(). */ storage: KeyValueStorage | undefined; locale: string | undefined;}What useStorefront returns. Type only.
import { useStorefront, type StorefrontContextValue } from "@sevigram/loom";
function cartReady(ctx: StorefrontContextValue) { return ctx.cart !== null;}
export function CartStatus() { return <p>{cartReady(useStorefront()) ? "Cart ready" : "Loading cart"}</p>;}useCart
Section titled “useCart”function useCart(): UseCart;The cart’s lines and actions; the component re-renders when the cart changes. Server-safe: until the provider has mounted in the browser it returns an empty cart and touches no storage.
import { useCart } from "@sevigram/loom";
export function CartLink() { const { count } = useCart(); return <a href="/cart">Cart ({count})</a>;}UseCart
Section titled “UseCart”interface UseCart { lines: readonly CartLine[]; /** Throws StorefrontError{code:"validation_error"} for an invalid line, and an Error before the cart is ready. */ add(line: NewCartLine): CartLine; update(id: string, patch: CartLinePatch): CartLine | undefined; remove(id: string): void; clear(): void; /** Total quantity across lines (a service line without a quantity counts as 1). */ count: number; /** True when the cart satisfies the checkout rules. */ canCheckout: boolean;}What useCart returns. Type only. A cart holds product lines, or exactly one
service booking, not both.
import { useCart, type UseCart } from "@sevigram/loom";
function LineList({ cart }: { cart: UseCart }) { return ( <ul> {cart.lines.map((line) => ( <li key={line.id}> {line.type} × {line.quantity ?? 1}{" "} <button onClick={() => cart.remove(line.id)}>Remove</button> </li> ))} </ul> );}
export function Cart() { return <LineList cart={useCart()} />;}AddToCartButton
Section titled “AddToCartButton”const AddToCartButton: ForwardRefExoticComponent< AddToCartButtonProps & RefAttributes<HTMLButtonElement>>;A <button> that adds line to the cart. It is disabled until the cart is ready, and while
available is false. Any other button attribute is passed through. Default label “Add to cart”.
import { AddToCartButton } from "@sevigram/loom";
export function Buy({ variantId }: { variantId: string }) { return ( <AddToCartButton line={{ type: "product", variantId, quantity: 1, fulfillment: { method: "delivery" } }} onAdded={(line) => console.log("added", line.id)} onError={(error) => console.error(error)} /> );}AddToCartButtonProps
Section titled “AddToCartButtonProps”interface AddToCartButtonProps extends Omit<ButtonHTMLAttributes<HTMLButtonElement>, "onError"> { line: NewCartLine; /** Set false while no purchasable variant is selected. Default true. */ available?: boolean; onAdded?: (line: CartLine) => void; /** Receives the cart's validation_error. Without it the error is rethrown. */ onError?: (error: unknown) => void;}The props of AddToCartButton. Type only. A service line is
{ type: "service", handle, scheduledStart, packageId?, quantity?, locationId? }.
import { AddToCartButton, type AddToCartButtonProps } from "@sevigram/loom";
export function BookButton(props: Omit<AddToCartButtonProps, "children">) { return <AddToCartButton {...props}>Book this time</AddToCartButton>;}VariantSelector
Section titled “VariantSelector”function VariantSelector(props: VariantSelectorProps): JSX.Element;One <fieldset> per product option, with radio inputs. A value that no available variant has
is disabled. A value that exists but not with the other current choices gets
data-unavailable-with-selection="true" on its label; choosing it moves the other options to
the closest available variant. Controlled: pair it with useVariantSelection.
import { AddToCartButton, VariantSelector, useVariantSelection } from "@sevigram/loom";import type { Product } from "@sevigram/storefront-client";
export function ProductForm({ product }: { product: Product }) { const selection = useVariantSelection(product); return ( <> <VariantSelector product={product} value={selection.selected} onChange={selection.setSelection} /> <AddToCartButton available={selection.available} line={{ type: "product", variantId: selection.variant?.id ?? "", quantity: 1, fulfillment: { method: "delivery" }, }} /> </> );}useVariantSelection
Section titled “useVariantSelection”function useVariantSelection(product: Product): UseVariantSelection;Holds the chosen option values for a product. It starts on the first available variant, so the
first render is deterministic and buyable, and resets when product.id changes. Server-safe.
import { Money, useVariantSelection } from "@sevigram/loom";import type { Product } from "@sevigram/storefront-client";
export function VariantPrice({ product }: { product: Product }) { const { variant } = useVariantSelection(product); return variant ? <Money amount={variant.price} currency={product.currency_code} /> : null;}VariantSelectorProps
Section titled “VariantSelectorProps”interface VariantSelectorProps extends Omit<HTMLAttributes<HTMLDivElement>, "onChange"> { product: Product; value: VariantSelection; onChange: (selected: VariantSelection) => void;}The props of VariantSelector. Type only. Other attributes go to the
wrapping <div>.
import { VariantSelector, type VariantSelectorProps } from "@sevigram/loom";
export function Options(props: VariantSelectorProps) { return <VariantSelector className="options" {...props} />;}VariantSelection
Section titled “VariantSelection”type VariantSelection = Record<string, string>;Option name to chosen value, for example { Size: "M", Colour: "Blue" }. Type only.
import type { VariantSelection } from "@sevigram/loom";
export function Summary({ selected }: { selected: VariantSelection }) { return <p>{Object.values(selected).join(" / ")}</p>;}UseVariantSelection
Section titled “UseVariantSelection”interface UseVariantSelection { selected: VariantSelection; /** Chooses a value and moves the other options to the closest available variant. */ setOption(name: string, value: string): void; /** Replaces the whole selection, e.g. from VariantSelector's onChange. */ setSelection(selected: VariantSelection): void; /** The variant matching a complete selection, or null. */ variant: ProductVariant | null; /** The resolved variant exists and can be bought. */ available: boolean;}What useVariantSelection returns. Type only.
import { useVariantSelection, type UseVariantSelection } from "@sevigram/loom";import type { Product } from "@sevigram/storefront-client";
function SizeButtons({ selection }: { selection: UseVariantSelection }) { return ( <> {["S", "M", "L"].map((size) => ( <button key={size} onClick={() => selection.setOption("Size", size)}> {size} </button> ))} </> );}
export function Sizes({ product }: { product: Product }) { return <SizeButtons selection={useVariantSelection(product)} />;}function Money(props: MoneyProps): JSX.Element;A <span> with an amount formatted in a currency (Intl.NumberFormat). It uses its own
locale, else the provider’s, else the runtime default. Server-safe. Works outside a provider.
import { Money } from "@sevigram/loom";
export function Price() { return <Money amount={79.5} currency="NGN" />;}MoneyProps
Section titled “MoneyProps”interface MoneyProps extends HTMLAttributes<HTMLSpanElement> { amount: number; /** ISO 4217 code, e.g. "NGN". */ currency: string; /** BCP 47 tag. Defaults to the StorefrontProvider locale, then the runtime default. */ locale?: string;}The props of Money. Type only.
import { Money, type MoneyProps } from "@sevigram/loom";
export function SalePrice(props: MoneyProps) { return <Money className="sale" {...props} />;}const Image: ForwardRefExoticComponent<ImageProps & RefAttributes<HTMLImageElement>>;An <img> for a Storefront API image, lazy-loaded by default. It renders nothing when image
is null. alt is required. Server-safe.
import { Image } from "@sevigram/loom";import type { CatalogItemSummary } from "@sevigram/storefront-client";
export function Thumb({ item }: { item: CatalogItemSummary }) { return <Image image={item.image} alt={item.title} width={320} />;}ImageProps
Section titled “ImageProps”interface ImageProps extends Omit<ImgHTMLAttributes<HTMLImageElement>, "src" | "alt"> { image: StorefrontImage | null; alt: string;}The props of Image. Type only. Pass loading="eager" for an image above the fold.
import { Image, type ImageProps } from "@sevigram/loom";
export function Hero(props: ImageProps) { return <Image loading="eager" {...props} />;}StorefrontImage
Section titled “StorefrontImage”interface StorefrontImage { url: string;}The image shape the Storefront API returns (Image in the API reference).
Type only.
import { Image, type StorefrontImage } from "@sevigram/loom";
export function Logo({ logo }: { logo: StorefrontImage | null }) { return <Image image={logo} alt="Shop logo" />;}useAvailability
Section titled “useAvailability”function useAvailability(handle: string, params: AvailabilityParams): UseAvailability;A service’s availability for params.from to params.to (plain YYYY-MM-DD dates in the
service’s timezone, at most 62 days apart). It fetches in the browser with the provider’s
client, refetches when the inputs change, and never lets an older response overwrite a newer
one. An invalid range sets error to a validation_error and makes no request. On the server
it reports loading: true and fetches nothing.
import { useAvailability } from "@sevigram/loom";
export function OpenDays({ handle }: { handle: string }) { const { data, loading, error } = useAvailability(handle, { from: "2026-12-01", to: "2026-12-31", }); if (loading) return <p>Loading…</p>; if (error) return <p role="alert">{error.message}</p>; return <p>{data?.dates.filter((d) => d.available).length} days open</p>;}UseAvailability
Section titled “UseAvailability”interface UseAvailability { data: Availability | null; loading: boolean; error: StorefrontError | null; reload: () => void;}What useAvailability returns. Type only. Network failures arrive as a
StorefrontError too.
import { useAvailability, type UseAvailability } from "@sevigram/loom";
function Retry({ result }: { result: UseAvailability }) { return result.error ? <button onClick={result.reload}>Try again</button> : null;}
export function AvailabilityRetry({ handle }: { handle: string }) { return <Retry result={useAvailability(handle, { from: "2026-12-01", to: "2026-12-07" })} />;}BookingCalendar
Section titled “BookingCalendar”function BookingCalendar(props: BookingCalendarProps): JSX.Element;A month grid of a service’s open days with keyboard navigation (arrow keys, Home, End, Enter
and Space).
Choosing a day lists its times; choosing a time calls onSelect. It fetches in the browser
through useAvailability. Labels use locale, else the provider’s.
Time-slot services need durationMinutes: the gateway answers validation_error without it.
Pass the chosen package’s duration_minutes (with its packageId). When no package has a
duration, don’t render the calendar; ask the customer to contact the shop instead.
import { AddToCartButton, BookingCalendar } from "@sevigram/loom";import { useState } from "react";
export function Booking({ handle, pkg,}: { handle: string; pkg: { id: string; duration_minutes: number };}) { const [start, setStart] = useState<string | null>(null); return ( <> <BookingCalendar handle={handle} month="2026-12" packageId={pkg.id} durationMinutes={pkg.duration_minutes} onSelect={(slot) => setStart(slot.startAt)} /> <AddToCartButton available={start !== null} line={{ type: "service", handle, scheduledStart: start ?? "" }} > Book </AddToCartButton> </> );}BookingCalendarProps
Section titled “BookingCalendarProps”interface BookingCalendarProps { handle: string; /** YYYY-MM. */ month: string; packageId?: string; /** Slot length. Required for time-slot services; use the package's `duration_minutes`. */ durationMinutes?: number; /** BCP 47 locale for labels. Defaults to the StorefrontProvider locale, then the runtime's. */ locale?: string; onSelect: (slot: BookingSlot) => void;}The props of BookingCalendar. Type only. An invalid month renders an
alert instead of the grid.
import { BookingCalendar, type BookingCalendarProps } from "@sevigram/loom";
export function PackageCalendar(props: BookingCalendarProps & { packageId: string }) { return <BookingCalendar {...props} />;}BookingSlot
Section titled “BookingSlot”interface BookingSlot { /** Plain YYYY-MM-DD date in the service's timezone. */ date: string; /** ISO 8601 date-time. Use it as the cart line's scheduledStart. */ startAt: string; endAt: string;}What BookingCalendar passes to onSelect. Type only.
import type { BookingSlot } from "@sevigram/loom";
export function Chosen({ slot }: { slot: BookingSlot }) { return ( <p> {slot.date}: {new Date(slot.startAt).toLocaleTimeString()} </p> );}CheckoutButton
Section titled “CheckoutButton”const CheckoutButton: ForwardRefExoticComponent< CheckoutButtonProps & RefAttributes<HTMLButtonElement>>;A <button> that sends the cart to POST /checkouts (through startCheckout) and redirects the
shopper to the Sevigram-hosted checkout. It is disabled until the cart is ready and checkable,
and while a checkout is starting (aria-busy). Double clicks start one checkout, and a retry
after a network failure reuses the same session. Acts in the browser only. Default label
“Checkout”.
Pass checkout to start the checkout on your server instead (signed-in checkout: your action calls
startServerCheckout with the customer session). The button then makes no browser POST /checkouts
request and does not redirect; your function receives the cart and navigates the shopper itself (a resolved promise leaves the button pending).
Its failures go to onConflict and onError.
returnUrl must be on one of the storefront’s allowed origins, or the API answers
422 return_url_not_allowed. On the demo shop the API answers 403 demo_shop_read_only; turn
the button off there (the starter does, when shop.read_only is true).
import { CheckoutButton } from "@sevigram/loom";
export function Checkout({ appOrigin }: { appOrigin: string }) { return ( <CheckoutButton returnUrl={`${appOrigin}/orders/return`} onConflict={(error) => console.warn("fix these lines", error.lines)} onError={(error) => console.error(error)} /> );}CheckoutButtonProps
Section titled “CheckoutButtonProps”interface CheckoutButtonProps extends Omit<ButtonHTMLAttributes<HTMLButtonElement>, "onError"> { /** Where the hosted checkout sends the shopper back to. */ returnUrl: string; /** Called with the conflicting cart lines; the shopper stays on the page. */ onConflict?: (error: CheckoutConflictError) => void; /** Any other failure, and a conflict when onConflict is not given. Without it: reportError. */ onError?: (error: unknown) => void; /** Replaces startCheckout and the redirect, e.g. a post to your server action. */ checkout?: (cart: Cart) => Promise<void>;}The props of CheckoutButton. Type only.
import { CheckoutButton, type CheckoutButtonProps } from "@sevigram/loom";
export function DemoAwareCheckout({ readOnly, ...props}: CheckoutButtonProps & { readOnly: boolean }) { return <CheckoutButton {...props} disabled={readOnly || props.disabled} />;}SignInForm
Section titled “SignInForm”function SignInForm(props: SignInFormProps): JSX.Element;Email step, then code step, as a plain form that posts intent (request_code, verify or
resend), email and code to your own server action. It renders what the action returns
(SignInState) and never sees the session token. Labelled inputs; the error is a role="alert";
focus moves to the code field on the second step. “Send a new code” stays disabled with a live
countdown for resendAfterSeconds (default 60) after the code step mounts. On the demo shop the
gateway returns a demo_code, shown as Demo code: 246810 in a role="status" element.
import { Form, useActionData, useNavigation } from "react-router";import { SignInForm, type SignInState } from "@sevigram/loom";
export default function SignIn() { const state = useActionData<SignInState>(); const pending = useNavigation().state !== "idle"; return <SignInForm as={Form} state={state} pending={pending} />;}SignInFormProps
Section titled “SignInFormProps”interface SignInFormProps { state?: SignInState; as?: ElementType; action?: string; pending?: boolean; resendAfterSeconds?: number; defaultEmail?: string; emailHint?: ReactNode; className?: string;}The props of SignInForm. as is the form component (React Router’s Form);
hiddenFields renders extra hidden inputs in both steps (for example { return_to: "/account" }).
emailHint renders under the email field, for example the demo email. Type only.
import { SignInForm, type SignInFormProps } from "@sevigram/loom";
export function DemoSignIn(props: SignInFormProps) {}SignInState
Section titled “SignInState”type SignInState = | { step: "email"; error?: string } | { step: "code"; email: string; demoCode?: string; error?: string };What your sign-in action returns to SignInForm. Type only.
import type { SignInState } from "@sevigram/loom";
SignOutButton
Section titled “SignOutButton”function SignOutButton(props: SignOutButtonProps): JSX.Element;A form (method="post", action default /account/sign-out) with one submit button, default
label “Sign out”. Your action destroys the cookie with destroyCustomerSession.
import { Form } from "react-router";import { SignOutButton } from "@sevigram/loom";
export const SignOut = () => <SignOutButton as={Form} className="link" />;SignOutButtonProps
Section titled “SignOutButtonProps”interface SignOutButtonProps extends ButtonHTMLAttributes<HTMLButtonElement> { as?: ElementType; action?: string;}The props of SignOutButton. Type only.
import { SignOutButton, type SignOutButtonProps } from "@sevigram/loom";
export const Leave = (props: SignOutButtonProps) => <SignOutButton {...props} action="/leave" />;useCustomer
Section titled “useCustomer”function useCustomer(): CustomerSummary | null;The customer your server gave StorefrontProvider, or null when signed out or outside a
provider (it does not throw). Loom does not depend on a router, so read the customer in your root
loader and pass it down.
import { useCustomer } from "@sevigram/loom";
export function Greeting() { const customer = useCustomer(); return <p>{customer ? `Hi ${customer.first_name}` : "Welcome"}</p>;}@sevigram/loom/server
Section titled “@sevigram/loom/server”Server only. This entry point holds the private token and must not be imported into client
code. Import it from server modules alone (in React Router, *.server.ts files, loaders and
actions). It throws @sevigram/loom/server must not run in the browser if it is loaded in one.
The customer session token is a bearer secret. Anyone holding it can read that customer’s orders, quotes, invoices and deliverables. It lives only in an HttpOnly cookie on your storefront’s own domain: never return it from a loader or action, never put it in a URL, browser storage or a log line, and never pass it to a component.
The helpers below keep it in the __Host-sevigram_customer cookie (HttpOnly; Secure; SameSite=Lax; Path=/, no Domain, expiring with the session). Pass your storefront’s own origin
(APP_ORIGIN) as { appOrigin } to every helper. Only when it is an http: loopback origin
(http://localhost:…, http://127.0.0.1:…, http://[::1]:…) is the cookie sevigram_customer
without Secure, so plain-HTTP dev servers work. In every other case, including a missing
appOrigin, the helpers use the __Host- cookie. The request’s Host header is never consulted,
so a reverse proxy that forwards to 127.0.0.1 cannot downgrade the cookie.
createServerClient
Section titled “createServerClient”function createServerClient(options: ServerClientOptions): StorefrontClient;A Storefront API client for one incoming request.
- With
privateToken(sfprv_…), it authenticates with the private token and sends the shopper’s IP asX-Sevigram-Buyer-IPwhentrustProxysays how to find it, so rate limits apply per shopper. - Without it, it uses
publicToken(sfpub_…) and sendsoriginas theOriginheader. That origin must be an allowed origin. Use this for development and the demo shop. - It throws when a token has the wrong prefix, when neither token is set, or when
publicTokenis used withoutorigin. Error messages never contain a token.
Create a new client per request, and never return the client, its options or the private token from a loader.
import { createServerClient } from "@sevigram/loom/server";
export function storefrontFor(request: Request) { return createServerClient({ request, signal: request.signal, privateToken: process.env.SEVIGRAM_STOREFRONT_PRIVATE_TOKEN, publicToken: process.env.SEVIGRAM_STOREFRONT_TOKEN, origin: process.env.APP_ORIGIN, trustProxy: Number(process.env.TRUST_PROXY ?? 0), });}
// app/routes/_index.tsxexport async function loader({ request }: { request: Request }) { const shop = await storefrontFor(request).getShop(); return { name: shop.name }; // Return data, never the client or a token.}
export default function Home({ loaderData }: { loaderData: { name: string } }) { return <h1>{loaderData.name}</h1>;}buyerIpFrom
Section titled “buyerIpFrom”function buyerIpFrom(request: Request, options?: BuyerIpOptions): string | undefined;The shopper’s IP address for a request, or undefined. createServerClient uses it. A Request
carries no socket address, so without trustProxy it returns undefined. With trustProxy: n
it reads the entry n places from the right of X-Forwarded-For (the address your outermost
trusted proxy saw), or clientIpHeader when set. Entries further left are set by the client
and never used. Invalid addresses give undefined. Server only.
import { buyerIpFrom } from "@sevigram/loom/server";
export async function loader({ request }: { request: Request }) { const ip = buyerIpFrom(request, { trustProxy: 1 }); return { fromProxy: ip !== undefined };}
export default function Debug({ loaderData }: { loaderData: { fromProxy: boolean } }) { return <p>{loaderData.fromProxy ? "Shopper IP found" : "No shopper IP"}</p>;}ServerClientOptions
Section titled “ServerClientOptions”type ServerClientOptions = { /** Private storefront token (sfprv_…). Read it from a server-only environment variable. */ privateToken?: string; /** Public token (sfpub_…) with origin. For development and the demo only. */ publicToken?: string; /** The incoming request; its forwarded IP is sent as the shopper's IP. */ request: Request; baseUrl?: string; trustProxy?: boolean | number; clientIpHeader?: string; /** Sent as Origin with the public token. Required without privateToken. */ origin?: string; /** Pass request.signal so a closed page request stops its API calls. */ signal?: AbortSignal; /** The signed-in customer's session token, usually getCustomerSession(request). */ customerSession?: string | null;};The options of createServerClient. Type only. Server only: an object
of this type may hold the private token and the customer’s session token, so never pass it to a
component. customerSession works with either token (the demo shop signs customers in with its
public token, still from the server). It is sent only on customer routes and POST /checkouts;
a value that is not a session token throws without echoing it.
import { createServerClient, type ServerClientOptions } from "@sevigram/loom/server";
function options(request: Request): ServerClientOptions { return { request, privateToken: process.env.SEVIGRAM_STOREFRONT_PRIVATE_TOKEN, publicToken: process.env.SEVIGRAM_STOREFRONT_TOKEN, origin: process.env.APP_ORIGIN, };}
export async function loader({ request }: { request: Request }) { const { items } = await createServerClient(options(request)).listProducts({ limit: 12 }); return { titles: items.map((item) => item.title) };}
export default function Products({ loaderData }: { loaderData: { titles: string[] } }) { return ( <ul> {loaderData.titles.map((t) => ( <li key={t}>{t}</li> ))} </ul> );}BuyerIpOptions
Section titled “BuyerIpOptions”type BuyerIpOptions = { /** * Number of proxies in front of this server that append to X-Forwarded-For (true means 1). * Never enable it when the server is reachable directly: the header could be forged. */ trustProxy?: boolean | number; /** Read the IP from this single-value header instead (e.g. cf-connecting-ip, fly-client-ip). */ clientIpHeader?: string;};The options of buyerIpFrom, also accepted by createServerClient. Type only.
import { buyerIpFrom, type BuyerIpOptions } from "@sevigram/loom/server";
const behindCloudflare: BuyerIpOptions = { trustProxy: 1, clientIpHeader: "cf-connecting-ip" };
export async function loader({ request }: { request: Request }) { return { known: buyerIpFrom(request, behindCloudflare) !== undefined };}
export default function Page({ loaderData }: { loaderData: { known: boolean } }) { return <p>{loaderData.known ? "Per-shopper rate limits" : "Shared rate limit"}</p>;}CUSTOMER_COOKIE
Section titled “CUSTOMER_COOKIE”const CUSTOMER_COOKIE = "__Host-sevigram_customer";The production cookie name. You rarely need it: getCustomerSession, commitCustomerSession
and destroyCustomerSession pick the name for the request.
import { CUSTOMER_COOKIE } from "@sevigram/loom/server";
export const cookieNames = [CUSTOMER_COOKIE]; // for a CDN rule that must not cache itCUSTOMER_COOKIE_LOCAL
Section titled “CUSTOMER_COOKIE_LOCAL”const CUSTOMER_COOKIE_LOCAL = "sevigram_customer";The cookie name used only when appOrigin is an http: loopback origin.
import { CUSTOMER_COOKIE, CUSTOMER_COOKIE_LOCAL } from "@sevigram/loom/server";
export const allCookieNames = [CUSTOMER_COOKIE, CUSTOMER_COOKIE_LOCAL];getCustomerSession
Section titled “getCustomerSession”function getCustomerSession(request: Request, options?: CustomerSessionOptions): string | null;The session token from the request’s cookie, or null. Only the __Host- cookie is read unless
appOrigin is an http: loopback origin. A value that is not a session token (control
characters, quotes, spaces, over 512 characters) is treated as no session, and so is a malformed
first cookie of that name. Pass the result to createServerClient as customerSession; never
return it.
import { createServerClient, getCustomerSession } from "@sevigram/loom/server";
export const sessionOptions = { appOrigin: process.env.APP_ORIGIN };
export function storefrontFor(request: Request) { return createServerClient({ request, signal: request.signal, privateToken: process.env.SEVIGRAM_STOREFRONT_PRIVATE_TOKEN, customerSession: getCustomerSession(request, sessionOptions), });}commitCustomerSession
Section titled “commitCustomerSession”function commitCustomerSession( token: string, expiresAt: string, request: Request, options?: CustomerSessionOptions,): string;A Set-Cookie header value that stores token until expiresAt (the session_token and
expires_at from verifyCustomerCode). It throws on an empty token, a token with characters
outside A-Z a-z 0-9 . _ ~ - (so nothing can be injected into the header) or an expiresAt
that is not an RFC 3339 date-time (2026-12-24T10:00:00Z). A past expiresAt is accepted and
gives a cookie the browser drops at once. Errors never contain the token.
import { redirect } from "react-router";import { commitCustomerSession } from "@sevigram/loom/server";import { sessionOptions, storefrontFor } from "~/lib/storefront.server";
export async function action({ request }: { request: Request }) { const form = await request.formData(); const { session_token, expires_at } = await storefrontFor(request).verifyCustomerCode( String(form.get("email")), String(form.get("code")), ); return redirect("/account", { headers: { "Set-Cookie": commitCustomerSession(session_token, expires_at, request, sessionOptions), }, });}destroyCustomerSession
Section titled “destroyCustomerSession”function destroyCustomerSession(request: Request, options?: CustomerSessionOptions): string;A Set-Cookie header value that removes the session cookie (Max-Age=0, expired). Send it on
sign-out, and whenever the API answers 401 customer_session_invalid.
import { redirect } from "react-router";import { destroyCustomerSession } from "@sevigram/loom/server";import { sessionOptions, storefrontFor } from "~/lib/storefront.server";
export async function action({ request }: { request: Request }) { await storefrontFor(request) .signOutCustomer() .catch(() => undefined); // Clear the cookie even if the API is down. return redirect("/", { headers: { "Set-Cookie": destroyCustomerSession(request, sessionOptions) }, });}readCustomer
Section titled “readCustomer”function readCustomer( client: StorefrontClient, request: Request, options?: CustomerSessionOptions,): Promise<{ customer: CustomerSummary | null; setCookie: string | null }>;The signed-in customer (first_name, email) for a request. Create client with
customerSession: getCustomerSession(request, options) and the same options. Without a session
cookie it makes no API call.
On 401 customer_session_invalid it returns customer: null and a setCookie that clears the
cookie: send it with your response. Any other error (an outage, a rate limit) returns
customer: null and keeps the cookie.
import { data } from "react-router";import { readCustomer } from "@sevigram/loom/server";import { sessionOptions, storefrontFor } from "~/lib/storefront.server";
export async function loader({ request }: { request: Request }) { const { customer, setCookie } = await readCustomer( storefrontFor(request), request, sessionOptions, ); // Return the customer's name only: never the session token. return data( { firstName: customer?.first_name ?? null }, setCookie ? { headers: { "Set-Cookie": setCookie } } : undefined, );}
export default function Header({ loaderData }: { loaderData: { firstName: string | null } }) { return <p>{loaderData.firstName ? `Hi, ${loaderData.firstName}` : "Sign in"}</p>;}assertSameOrigin
Section titled “assertSameOrigin”function assertSameOrigin(request: Request, options: CustomerSessionOptions): void;Blocks login CSRF: SameSite=Lax does not stop another site from posting a form that signs the
visitor in to the attacker’s account, signs them out or sends sign-in emails. Call it first in
every action that sets or clears the session cookie or sends email. It throws a 403 Response
unless the Origin header equals the origin of options.appOrigin; when Origin is absent, only
Sec-Fetch-Site: same-origin passes. It fails closed: with no valid appOrigin, or neither
header, it throws.
import { assertSameOrigin } from "@sevigram/loom/server";
export async function action({ request }: { request: Request }) { assertSameOrigin(request, sessionOptions); // ...}CustomerSessionOptions
Section titled “CustomerSessionOptions”type CustomerSessionOptions = { /** The storefront's own origin, for example process.env.APP_ORIGIN. */ appOrigin?: string;};The last argument of getCustomerSession, commitCustomerSession, destroyCustomerSession and
readCustomer. Type only. Only an http: loopback appOrigin selects the plain-HTTP dev cookie;
an https: origin, any other host, an unparsable value or no value uses the __Host- cookie.
Behind a reverse proxy nothing depends on the Host header, so set APP_ORIGIN to the public
origin (https://shop.example) in production.
import { getCustomerSession, type CustomerSessionOptions } from "@sevigram/loom/server";
const options: CustomerSessionOptions = { appOrigin: process.env.APP_ORIGIN };
export function hasSession(request: Request): boolean { return getCustomerSession(request, options) !== null;}