Wire a cart and a checkout into a Next.js storefront: one buyer client per request, the cart token in an HttpOnly cookie, the terms box, online payment return pages and the guest order link. Previous: Guide 23 | Next: Guide 25
Reference - This guide is a tutorial. For exhaustive, always-current signatures and field lists, see the auto-generated reference:
Types: SDK Types
API: Storefront: Commerce
Prerequisites
A Next.js app set up with
@lynkow/nextand itsconfig(Guide 6), withpublishableKeypassed toresolveConfig()(Guide 18).A terms page chosen in Settings > E-commerce > Store (Terms page). Until one is set, or when the chosen page is no longer published, every checkout is refused with
TERMS_PAGE_NOT_CONFIGURED.For delivery orders: markets and shipping options (Guide 23).
The examples use the App Router: Server Components read, Server Actions write. All amounts are integers in the minor unit of the site's currency (cents for EUR).
One buyer client per request
The SDK keeps the guest cart token and the customer session on the client instance, so a client shared between requests hands one visitor's cart to the next. createBuyerClient() builds a client for one request from its cookies:
import { cookies } from 'next/headers'
import { createBuyerClient } from '@lynkow/next/server'
import { config } from '@/lib/config'
const client = createBuyerClient(config, await cookies(), { locale })Create it in a Server Component, Server Action or Route Handler, once per request. Never keep it in a module variable or a cache.
Its reads are sent uncached. Never wrap them in
cached()or a'use cache'function, and never use it on a route whosefetchCacheis'force-cache'or'only-cache'.Never use the shared
lynkow(locale)clients forcart,checkout,customersororderscalls.Every call reaches the API from your server, so without forwarding all buyers share your server's rate limits: 120 cart changes per minute, and 10 checkouts per 15 minutes. Set
LYNKOW_SERVER_KEYto the site's server key and, from@lynkow/next0.7.3, the client forwards each buyer's IP on its writes and on the guest order read. Other reads never read the request headers, so their pages stay static. See Server Key and Buyer IP.The cookies are
__Host-lynkow-cartand__Host-lynkow-customer(BUYER_COOKIE_NAMES).setCartCookie()andsetCustomerCookie()write themHttpOnly,Secure,SameSite=Lax, for 30 days at most.clearBuyerCookies()deletes both.__Host-cookies need HTTPS, or a browser that treatslocalhostas secure.Only a Server Action or a Route Handler can write a cookie. A Route Handler that changes state starts with
assertSameOrigin(request)and returns the 403 response it gives back. Next checks the origin of Server Actions itself.
The cart
Add a line
// app/actions/cart.ts
'use server'
import { cookies } from 'next/headers'
import type { Cart } from 'lynkow'
import { createBuyerClient, setCartCookie } from '@lynkow/next/server'
import { config } from '@/lib/config'
export async function addToCart(variantId: string, quantity: number, locale: string): Promise<Cart> {
// A Server Action is a public endpoint: check every argument.
if (!/^var_[A-Za-z0-9]+$/.test(variantId) || !Number.isInteger(quantity) || quantity < 1 || quantity > 999) {
throw new Error('Invalid line')
}
const store = await cookies()
const client = createBuyerClient(config, store, { locale })
const { cartToken, ...cart } = await client.cart.addLine({ variantId, quantity })
const token = client.cart.getCartToken()
if (token) setCartCookie(store, token)
return cart // never send the token to the browser
}A guest's first
addLine()creates the cart and returns its token once, incartToken. The client keeps it: store it withsetCartCookie(). When the cookie names a cart that expired or became an order,addLine()starts a new cart with a new token, which the same code stores.The token gives full access to its cart. Keep it out of every result, log and URL.
addLine()throwsNOT_FOUNDwhen the variant cannot be bought, andVALIDATION_ERRORwithapiCodeOUT_OF_STOCKorCART_LINES_LIMIT_REACHED.addLine()adds units to an existing line.updateLine({ variantId, quantity })sets the line to exactly that quantity, from 1 to 999.removeLine(variantId)removes the line; a quantity of 0 is refused. Both return the recomputed cart.
Read the cart
import { cookies } from 'next/headers'
import { isLynkowError, type Cart } from 'lynkow'
import { createBuyerClient, readBuyerTokens } from '@lynkow/next/server'
import { config } from '@/lib/config'
async function readCart(locale: string): Promise<Cart | null> {
const store = await cookies()
const { cartToken, customerToken } = readBuyerTokens(store)
if (!cartToken && !customerToken) return null // nothing added yet: no API call
try {
return await createBuyerClient(config, store, { locale }).cart.retrieve()
} catch (error) {
if (isLynkowError(error) && error.code === 'NOT_FOUND') return null
throw error
}
}NOT_FOUNDcovers a wrong, expired or completed cart, and a site with e-commerce disabled. Show an empty cart.cart.removedLineslists the lines this read removed because they can no longer be bought, each with areason. Tell the buyer, then rendercart.items.The cart has no item count: sum
items[].quantity.Reading cookies makes the page dynamic. Keep the cart page out of prerendered routes, and show a cart badge on a prerendered page from a client component that calls a Server Action.
When the buyer signs in
// Inside a Server Action, with store = await cookies()
const client = createBuyerClient(config, store, { locale }) // carries the guest cart token
const { token } = await client.customers.login({ email, password })
setCustomerCookie(store, token)
if (client.cart.getCartToken() !== null) {
await client.cart.claim().catch(() => {}) // the buyer is signed in either way
}claim() merges the guest lines into the account's cart and retires the guest token. Sign-in itself is covered in Guide 20.
Checkout
The terms box
// The terms page is the same for every visitor: the shared client is fine here.
const { data: termsPages } = await lynkow(locale).pages.list({ tag: 'terms' })
const terms = termsPages[0] ?? null
<label>
<input type="checkbox" name="acceptsTerms" required />
I accept the {terms ? <a href={terms.publicPath}>terms of sale</a> : 'terms of sale'}
</label>The merchant picks the terms page in Settings > E-commerce > Store, among the published pages with the Terms of Service category (tag terms). No storefront read names the chosen page, so list the pages carrying the tag. Send acceptsTerms: true only when the buyer ticked the box: checkout refuses an order without it (TERMS_NOT_ACCEPTED) and records the terms version the buyer accepted.
Delivery address and shipping
'use server'
// Imports as in addToCart, plus: import type { OrderAddress } from 'lynkow'
export async function setDelivery(address: OrderAddress, locale: string) {
const client = createBuyerClient(config, await cookies(), { locale })
return client.cart.update({ deliveryAddress: address })
}
export async function chooseShipping(shippingOptionId: string, locale: string) {
const client = createBuyerClient(config, await cookies(), { locale })
const cart = await client.cart.update({ shippingOptionId })
return { shippingOptionId: cart.shippingOptionId, totalCents: cart.totalCents }
}The country picker, the shipping options and the cart's figures are in Guide 23. On the checkout page, read
markets.list()andshippingOptions.list()through the buyer client too: a cached list can offer what checkout then refuses.Read
cart.shippingOptionIdfrom the result rather than the value you sent: a choice outside the delivery country's market is cleared.A
Cartfromupdate()carries no token and can go back to the browser as it is.Keep the
totalCentsthe summary displayed. It goes toplaceOrder()asexpectedTotalCents.
Place the order
// app/actions/checkout.ts
'use server'
import { cookies } from 'next/headers'
import { redirect } from 'next/navigation'
import { isLynkowError, type PlaceOrderInput, type PlaceOrderResult } from 'lynkow'
import { createBuyerClient, setCartCookie } from '@lynkow/next/server'
import { config } from '@/lib/config'
import { setPaymentCookie } from '@/lib/payment-cookie' // your own helper, below
interface CheckoutForm {
acceptsTerms: boolean
email?: string // required for a guest
paymentMethod: 'card' | 'on_site'
fulfillmentMode: 'delivery' | 'pickup'
expectedTotalCents: number
}
export async function placeOrder(form: CheckoutForm, locale: string) {
// A Server Action is a public endpoint: check every field.
const valid =
['card', 'on_site'].includes(form.paymentMethod) &&
['delivery', 'pickup'].includes(form.fulfillmentMode) &&
Number.isInteger(form.expectedTotalCents) && form.expectedTotalCents >= 0 &&
(form.email === undefined || (typeof form.email === 'string' && form.email.length <= 254))
if (!valid) return { ok: false, reason: 'invalid' }
if (form.acceptsTerms !== true) return { ok: false, reason: 'TERMS_NOT_ACCEPTED' }
const store = await cookies()
const client = createBuyerClient(config, store, { locale })
const input: PlaceOrderInput = {
acceptsTerms: true,
paymentMethod: form.paymentMethod,
fulfillmentMode: form.fulfillmentMode,
expectedTotalCents: form.expectedTotalCents,
...(form.email ? { email: form.email } : {}),
}
let order: PlaceOrderResult
try {
if (form.fulfillmentMode === 'delivery') {
const cart = await client.cart.retrieve()
if (!cart.deliveryAddress?.countryCode) return { ok: false, reason: 'DELIVERY_COUNTRY_REQUIRED' }
input.address = cart.deliveryAddress // checkout prices from this address, not from the cart
}
order = await client.checkout.placeOrder(input)
} catch (error) {
if (isLynkowError(error)) return { ok: false, reason: error.apiCode ?? error.code }
throw error
}
// The cart became the order: a past expiry deletes its cookie.
setCartCookie(store, 'placed', { expiresAt: 0 })
if (!order.payment) return { ok: true, orderNumber: order.orderNumber }
const checkoutUrl = new URL(order.payment.checkoutUrl)
if (checkoutUrl.protocol !== 'https:') throw new Error('Unexpected payment URL')
setPaymentCookie(store, order.payment.paymentId, order.payment.captureToken)
redirect(checkoutUrl.toString()) // outside the try: redirect() works by throwing
}A guest must send
email. A signed-in buyer is identified by the session.shippingOptionIddefaults to the cart's choice. A pickup order sends no address.Placing the order sends the confirmation email and fires the
order.placedwebhook.No storefront read lists the payment methods a shop accepts: offer the ones the merchant set up. When online payment is not available,
'card'is refused withPAYMENT_METHOD_UNAVAILABLEand the cart stays open for an offline method.On a site with reCAPTCHA, pass
{ recaptchaToken }as the second argument ofplaceOrder(), minted with thecheckoutaction.
Checkout refusals
A refusal creates no order and leaves the cart open. Branch on error.apiCode:
| Status | What to do |
|---|---|---|
| 422 | Nothing the buyer can fix: the merchant has to choose a terms page. |
| 422 | Ask the buyer to tick the terms box. |
| 422 | Send the buyer back to the catalogue. |
| 422 | Offer an offline method. |
| 422 | In-page payment is not set up: place the order again without |
| 403 | The site sells to signed-in buyers only: ask them to sign in. |
| 409 | The cart is already an order: drop the cart cookie. |
| 429 | Too many orders from one client in 15 minutes. When every buyer gets it, your server forwards no buyer IP: see Server Key and Buyer IP. |
The delivery, shipping, VAT, stock and TOTAL_CHANGED refusals are in Guide 23.
One failure happens after the order exists: when the online payment page cannot open, placeOrder() throws PAYMENT_CHECKOUT_UNAVAILABLE (503) and the unpaid order is cancelled.
Online payment
With paymentMethod: 'card', placeOrder() returns the order with a payment: the hosted payment page's checkoutUrl, the paymentId and a private captureToken. The order is placed, unpaid until the payment is captured. To show the payment form in your own page instead, see Pay in your page.
Keep the capture token on the server
The payment page sends the buyer back with the payment id only. A guest also needs the capture token to read the payment, so store both in a short-lived HttpOnly cookie before the redirect. This helper is your own code:
// lib/payment-cookie.ts
import type { BuyerCookieReader, BuyerCookieWriter } from '@lynkow/next/server'
const NAME = '__Host-shop-payment'
const attributes = (maxAge: number) =>
({ httpOnly: true, secure: true, sameSite: 'lax', path: '/', maxAge }) as const
export function setPaymentCookie(store: BuyerCookieWriter, paymentId: string, captureToken: string) {
const value = Buffer.from(JSON.stringify({ paymentId, captureToken })).toString('base64url')
store.set(NAME, value, attributes(60 * 60)) // one hour
}
export function readPaymentCookie(store: BuyerCookieReader): { paymentId: string; captureToken: string } | null {
const raw = store.get(NAME)?.value
if (!raw) return null
try {
const { paymentId, captureToken } = JSON.parse(Buffer.from(raw, 'base64url').toString('utf8'))
return typeof paymentId === 'string' && typeof captureToken === 'string' && captureToken
? { paymentId, captureToken }
: null
} catch {
return null
}
}
// A store's delete() writes no Secure attribute, and the browser then keeps a __Host- cookie.
export function clearPaymentCookie(store: BuyerCookieWriter) {
store.set(NAME, '', attributes(0))
}The return page
The buyer comes back to /checkout/payment/return?paymentId=... on the site's domain, or to /checkout/payment/cancel?orderId=... when they leave without paying. Both paths carry no locale prefix: the @lynkow/next proxy serves them in the buyer's language from the language cookie.
// app/[locale]/checkout/payment/return/page.tsx
import type { Metadata } from 'next'
import { cookies } from 'next/headers'
import { createBuyerClient } from '@lynkow/next/server'
import { config } from '@/lib/config'
import { clearPaymentCookie, readPaymentCookie } from '@/lib/payment-cookie'
import { PaymentOutcome } from './payment-outcome'
// The URL names a payment: keep it out of search engines and the Referer header.
export const metadata: Metadata = { robots: { index: false, follow: false }, referrer: 'no-referrer' }
const PAYMENT_ID = /^[A-Za-z0-9_-]{1,256}$/
async function clearPayment() {
'use server'
clearPaymentCookie(await cookies())
}
export default async function PaymentReturnPage({ params, searchParams }: {
params: Promise<{ locale: string }>
searchParams: Promise<{ paymentId?: string | string[] }>
}) {
const { locale } = await params
const { paymentId } = await searchParams
const store = await cookies()
const urlId = typeof paymentId === 'string' && PAYMENT_ID.test(paymentId) ? paymentId : null
const cookie = readPaymentCookie(store)
// The cookie can belong to an earlier payment: use it only for the payment the URL names.
const stored = cookie && (!urlId || cookie.paymentId === urlId) ? cookie : null
const id = stored?.paymentId ?? urlId
let message = 'We could not confirm your payment here. Check your email for the order confirmation.'
if (id) {
try {
const { status, orderStatus } = await createBuyerClient(config, store, { locale })
.checkout.refreshPayment(id, stored?.captureToken)
if (status === 'captured' && orderStatus !== 'cancelled') message = 'Payment received. Thank you for your order.'
else if (status === 'pending' || status === 'processing') message = 'Your payment is being confirmed.'
else if (status === 'failed' || status === 'expired') message = 'Your payment did not go through.'
} catch {
// Keep the message. Log the error code only: the request carried the capture token.
}
}
return <PaymentOutcome message={message} clear={stored ? clearPayment : null} />
}// app/[locale]/checkout/payment/return/payment-outcome.tsx
'use client'
import { useEffect, useRef, useState } from 'react'
export function PaymentOutcome({ message, clear }: { message: string; clear: (() => Promise<void>) | null }) {
const [shown] = useState(message) // the render after the clear has no cookie left
const cleared = useRef(false)
useEffect(() => {
if (clear && !cleared.current) {
cleared.current = true
void clear()
}
}, [clear])
return <p>{shown}</p>
}Only
status === 'captured'means paid, unlessorderStatusis'cancelled': the payment landed after the order was cancelled, and the merchant refunds it.refreshPayment()can also answer'ignored'or'mismatch': show the "check your email" message.refreshPayment()is idempotent, so a reload is safe.Without a cookie for that payment (another browser, an hour later, or a cookie left by an earlier payment), the page refreshes the id from the URL with no capture token. That works for the signed-in buyer who owns the payment. Anyone else gets
FORBIDDEN, and the page shows the "check your email" message.A page cannot write cookies, so the client component clears the payment cookie through a Server Action.
The URL of every
/checkout/payment/*page names a payment. Keep it out of logs and analytics, and load no third-party script on these routes.
The cancel page
/checkout/payment/cancel?orderId=... needs no API call: tell the buyer the payment did not go through, and give it the same metadata as the return page. Leave the payment cookie to expire: a buyer who goes Back from this page can still pay in the form the browser restores, and a guest's return page reads that payment only with the cookie.
Pay in your page
Send paymentFlow: 'embedded' with paymentMethod: 'card', and payment carries flow: 'embedded' with what mounts the payment provider's form in your checkout page: a clientSecret, the provider's providerPublishableKey and the merchant's providerAccountId. The card fields are the provider's own secure frames, so no card number reaches your site.
const order = await client.checkout.placeOrder({
email,
paymentMethod: 'card',
paymentFlow: 'embedded',
expectedTotalCents: cart.totalCents,
acceptsTerms: true,
})
if (order.payment) {
setPaymentCookie(store, order.payment.paymentId, order.payment.captureToken)
// Hand the browser these three only: the capture token stays in the cookie.
return {
clientSecret: order.payment.clientSecret,
publishableKey: order.payment.providerPublishableKey,
accountId: order.payment.providerAccountId,
}
}Load the provider's browser library with
providerPublishableKeyfor the accountproviderAccountId, and mount its checkout form withclientSecret. The starter'ssrc/modules/checkout/card-payment.tsxis a complete implementation.After paying, the buyer lands on the same
/checkout/payment/return?paymentId=...page, so the return page above works unchanged. Offer a link to the cancel page for a buyer who gives up.Apple Pay and Google Pay show in the form only on the site's domain as set in the admin, which Lynkow registers with the merchant's payment account.
Without in-page payment configured,
placeOrder()throwsPAYMENT_FLOW_UNAVAILABLEand creates no order.
The guest order link
The order emails sent to a guest link to /order/<token> on your site, under the locale prefix of the order's language. Read the order through a buyer client:
// app/[locale]/order/[token]/page.tsx (excerpt)
const order = await createBuyerClient(config, await cookies(), { locale }).orders.getGuest(token)NOT_FOUND and VALIDATION_ERROR both mean the link is not valid: show one page for both. The token is a secret, so give the page the same metadata as the return page and keep its URL out of logs and analytics. The full page is in Guide 20.
Next Steps
Guide 25: Build a Shop - the shop's page map, and the order webhooks that trigger fulfilment.
Guide 20: Customer Accounts - sign-in, order history and the guest order page.
Guide 23: Markets, Shipping and VAT - the country picker, shipping options and VAT figures.
Guide 12: Error Handling -
LynkowErrorand how to branch on it.