SDK reference

SDK, runtime, and UI

Core exports for Nimlio-generated React sites: API client, hooks, bilingual runtime, COP formatting, and connected components. The SDK ships inside your Nimlio code site; it is not installed from a public registry.

Recipes

Copy-paste starting points for the headless storefront hooks. Each one is exported by the SDK today; they show the code and do not run it.

Supported means the hook or class is exported by @nimlio/sdk on this version and the example uses only its real options and fields.

Create the client and provider

Supported

createClient accepts only a publishable key that starts with nk_pub_ and throws on anything else. baseUrl is optional: when you omit it the client uses the build-time or site-config value and otherwise the same-origin path /api/v1. NimlioProvider creates its own TanStack Query client unless you pass queryClient.

import { createClient } from "@nimlio/sdk";
import { NimlioProvider } from "@nimlio/sdk/react";

const client = createClient({ key: "nk_pub_xxxxxxxx" });

export function App({ children }) {
return <NimlioProvider client={client}>{children}</NimlioProvider>;
}

List products with pagination

Supported

page starts at 1 and pageSize goes from 1 to 100 (default 50); the SDK turns them into the API offset and limit. data.meta carries hasMore, nextCursor and limit. useProducts returns the first page as a flat array. Prices are priceAmount in COP centavos and can be null.

import { useProductsPage } from "@nimlio/sdk/react";
import { money } from "@nimlio/runtime";

export function Catalog({ page }: { page: number }) {
const { data, isPending, error } = useProductsPage({ page, pageSize: 24 });
if (isPending) return <p>Cargando…</p>;
if (error) return <p>{error.code}</p>;
return (
<>
<ul>
{data.data.map((p) => (
<li key={p.id}>
{p.name} {p.priceAmount != null ? money(p.priceAmount) : null}
</li>
))}
</ul>
{data.meta.hasMore ? <a href={`?page=${page + 1}`}>Siguiente</a> : null}
</>
);
}
Related

Product detail and reviews

Supported

useProduct loads one product by id and also emits the view_content analytics event once per product id. useProductReviews takes the same page and pageSize options and returns the reviews plus meta with count and average.

import { useProduct, useProductReviews } from "@nimlio/sdk/react";

export function ProductPage({ id }: { id: string }) {
const product = useProduct(id);
const reviews = useProductReviews(id, { page: 1, pageSize: 10 });
// product.data.name, reviews.data?.data (list), reviews.data?.meta.average
return null;
}

Collection product grid

Supported

useCollections lists the published collections and useCollectionProducts loads the products of one collection by its handle. Collections without a handle are skipped, and an empty handle keeps the products query disabled until the list arrives. Prices are COP centavos; money() formats them. This is the file docs/examples/collection-grid.tsx in the Nimlio repository, with its CSS Module collection-grid.module.css next to it.

import { useState } from "react";
import { money } from "@nimlio/runtime";
import { useCollectionProducts, useCollections } from "@nimlio/sdk/react";
import styles from "./collection-grid.module.css";

export function CollectionGrid() {
const collections = useCollections();
const [chosen, setChosen] = useState<string | null>(null);
const list = (collections.data ?? []).filter((c) => c.handle);
const handle = chosen ?? list[0]?.handle ?? "";
// An empty handle keeps the products query disabled until the list arrives.
const products = useCollectionProducts(handle);

if (collections.isPending) return <p>Cargando…</p>;
if (collections.error) return <p>{collections.error.code}</p>;

return (
<section className={styles.root}>
<nav className={styles.tabs}>
{list.map((c) => (
<button
key={c.id}
type="button"
className={c.handle === handle ? styles.tabActive : styles.tab}
aria-pressed={c.handle === handle}
onClick={() => setChosen(c.handle ?? null)}
>
{c.title}
</button>
))}
</nav>
{products.error ? <p>{products.error.code}</p> : null}
<ul className={styles.grid}>
{(products.data ?? []).map((p) => {
const price = p.effectivePriceAmount ?? p.priceAmount;
return (
<li key={p.id} className={styles.card}>
{p.imageUrl ? <img className={styles.image} src={p.imageUrl} alt={p.name} loading="lazy" /> : null}
<h3 className={styles.name}>{p.name}</h3>
{price != null ? <p className={styles.price}>{money(price)}</p> : null}
</li>
);
})}
</ul>
</section>
);
}

Checkout: quote, create, poll

Supported

The storefront never sends prices. Items carry only an id, a type and a quantity (plus variantId when the product has options); the server resolves unit prices, discounts, gift credit and shipping from the published catalog when you quote and again when the order is created. A body that includes price, total, discount, currency or businessId is rejected with 400 client_order_fields_not_allowed.

import { useRef, useState } from "react";
import { useQuoteOrder, useCreateOrder, useOrderStatus } from "@nimlio/sdk/react";

export function Checkout({ discountCode, shippingRateId }: { discountCode?: string; shippingRateId?: string }) {
const quote = useQuoteOrder();
const create = useCreateOrder();
const [orderId, setOrderId] = useState("");
// Order creation requires an Idempotency-Key. The SDK sends one per call by default;
// keeping one key per checkout attempt makes a re-submit replay the same order.
// Mint a fresh key when the cart changes. Raw fetch must send the header itself.
const attemptKey = useRef(crypto.randomUUID());
// An empty id keeps the query disabled; polling stops on a terminal status.
const status = useOrderStatus(orderId, { poll: 3000 });

async function placeOrder() {
// Selections only: ids, quantities and codes, never prices.
const checkout = {
items: [{ id: "product-id", type: "product" as const, quantity: 2 }],
discountCode,
shippingRateId,
};

// 1. Ask the server what the cart costs.
await quote.mutateAsync({ ...checkout, customerCity: "Medellín" });
// quote.data.subtotal, .discount and .shippingOptions come from the published catalog.

// 2. Create the order with the same selections.
const order = await create.mutateAsync({
input: {
...checkout,
customer: { name: "Ana Pérez", phone: "+573001112233" },
paymentMethod: "online",
},
options: { idempotencyKey: attemptKey.current },
});
setOrderId(order.orderId);
}

return (
<button onClick={placeOrder} disabled={create.isPending}>
{status.data?.status ?? "Pay"}
</button>
);
}

useOrderStatus polls every 3000 ms with poll: true or the interval you pass, and stops by itself at a terminal status. Order creation requires an Idempotency-Key: useCreateOrder sends a generated key and the SDK retries transient failures with that same key (useQuoteOrder never retries); pass options.idempotencyKey, kept stable for the whole checkout attempt, so a re-submit replays the same order. Raw fetch must send the Idempotency-Key header or gets 400 idempotency_key_required. Format amounts with money(), which expects COP centavos.

Catch NimlioApiError

Supported

Failed requests throw NimlioApiError with status, code, reason, fieldErrors and requestId, and hooks expose the same error on their result. Mutations never retry on their own; reads retry once by default through the provider query client.

import { NimlioApiError } from "@nimlio/sdk";

try {
await create.mutateAsync(input);
} catch (e) {
if (e instanceof NimlioApiError) {
// e.status, e.code, e.reason, e.fieldErrors, e.requestId
if (e.code === "invalid_input") showFieldErrors(e.fieldErrors);
else if (e.code === "rate_limited") retryLater();
else report(e.requestId);
}
}

Reference

24 of 24 exports

@nimlio/sdk

functioncreateClient(options?: NimlioClientOptions): NimlioClient

Creates the typed Platform API client for browser-safe publishable keys.

Example

const nimlio = createClient({ key: config.key });
const site = await nimlio.site.get();
functionclass NimlioApiError

Typed SDK error surface.

Example

try { await nimlio.site.get(); } catch (error) {
  if (error instanceof NimlioApiError) console.log(error.code);
}

@nimlio/sdk/react

componentNimlioProvider(props: NimlioProviderProps): ReactNode

Provides the SDK client to React hooks inside generated tenant sites.

Example

<NimlioProvider client={nimlio}><App /></NimlioProvider>
hookuseCreateAppointment(options?: NimlioWriteMutationOptions<{ manageUrl?: string; mode: "requested" | "booked"; price?: { code?: string; codeApplied?: boolean; deposit: number; di...

Creates booking intents; Nimlio recomputes availability server-side.

Example

createAppointment.mutate({ serviceId, startsAt, customerName, customerPhone });
hookuseServices(options?: NimlioQueryOptions<{ currency?: string; description?: string; durationMinutes?: number; id: string; imageUrl?: string; imageVariants?: { large?: { height: ...

React hook for Nimlio tenant code.

Example

const { data: services } = useServices();
hookuseSite(options?: NimlioQueryOptions<{ autoLocale: boolean; breakpoints?: Record<string, never>; business: { addressLine1?: string; city?: string; country?: string; description?...

React hook for Nimlio tenant code.

Example

const { data: site } = useSite();
hookuseSlots(params: { serviceId: string; staffId?: string; date: string; }, options?: NimlioQueryOptions<{ endsAt: string; staffId: string; startsAt: string; }[], readonly ["nimlio...

React hook for Nimlio tenant code.

Example

const { data: slots } = useSlots({ serviceId, staffId, date });

@nimlio/runtime

functiondefineConfig(config: NimlioRuntimeConfigInput): NimlioRuntimeConfig

Public Nimlio SDK export.

Example

export default defineConfig({ routes: [{ path: '/', component: HomePage }] });
componentLocaleProvider(props: { locale?: Locale; defaultLocale?: Locale; messages?: Partial<Record<Locale, LocaleMessages>>; children?: ReactNode; }): ReactElement<...>

React provider for Nimlio tenant code.

Example

<LocaleProvider defaultLocale="es"><App /></LocaleProvider>
functionmoney(copCentavos: number, locale?: Locale | "es-CO" | "en-US"): string

Formats integer COP centavos for es/en tenant copy.

Example

money(12500000, "es-CO") // "$ 125.000"
functionreadSiteConfig(overrides?: Partial<NimlioSiteConfig>): NimlioSiteConfig

Public Nimlio SDK export.

Example

const config = readSiteConfig();
componentSeo(props: SeoProps): null

Public Nimlio SDK type.

Example

<Seo title="Bookings" description="Schedule your visit online" />
componentSiteImage(props: SiteImageProps): ReactElement<unknown, string | JSXElementConstructor<any>>

Public Nimlio SDK type.

Example

{service.imageUrl ? <SiteImage src={service.imageUrl} alt={service.name} /> : null}
hookuseLocale(): LocaleContextValue

React hook for Nimlio tenant code.

Example

const { locale, setLocale } = useLocale();

@nimlio/ui

componentBookingWidget(props?: BookingWidgetProps): ReactElement<unknown, string | JSXElementConstructor<any>>

Themeable booking component wired to Nimlio services, staff, slots, and bookings.

Example

<BookingWidget locale="es" />
componentContactForm(props: ContactFormProps): ReactNode

Themeable form component for visitor leads and custom form submissions.

Example

<ContactForm formId="contact" locale="es" />
componentLocaleSwitcher(props: LocaleSwitcherProps): Element

Public Nimlio SDK type.

Example

<LocaleSwitcher locales={[{ key: "es", label: "Español" }, { key: "en", label: "English" }]} />
componentMenuList(props: MenuListProps): Element

Public Nimlio SDK type.

Example

<MenuList source="services" showDuration />
componentProductGrid(props: ProductGridProps): ReactNode

Public Nimlio SDK type.

Example

<ProductGrid products={products} columns={4} />
componentPropertyList(props: PropertyListProps): ReactNode

Public Nimlio SDK type.

Example

<PropertyList properties={properties} />
functionresolveVariant(options: readonly VariantPickerOption[], variants: readonly VariantPickerVariant[], value: Readonly<Record<string, string>>): VariantPickerVariant

Returns the active variant matching a complete option selection, or null.

Example

const variant = resolveVariant(product.options ?? [], product.variants ?? [], value);
componentVariantPicker(props: VariantPickerProps): ReactNode

Option chips for a product with variants; controlled by a selection map, themeable with --nimlio-variant-* CSS variables.

Example

const [value, setValue] = useState<Record<string, string>>({});
<VariantPicker options={product.options} variants={product.variants} value={value} onChange={setValue} />
componentWhatsAppButton(props: WhatsAppButtonProps): Element

Public Nimlio SDK type.

Example

<WhatsAppButton phone="+573001112233" label="Write us" />

Use these packages instead of secrets, custom server code, or unsupported external dependencies.