List products, read one product, collection or category, and serve each at its public URL with its SEO fields and structured data. Previous: Guide 17 | Next: Guide 19
Reference - This guide is a tutorial. For exhaustive, always-current signatures and field lists, see the auto-generated reference:
Prerequisites
New to Lynkow commerce? Guide 25: Build a Shop lists what the site needs and the pages a shop needs.
A client in
lib/lynkow.tscreated with apublishableKey(Add Lynkow to an Existing Project). The key is under Settings > Developers > Storefront.Without the key, every catalog call throws a
LynkowErrorwith code'UNAUTHORIZED'. On a site where e-commerce is not enabled, it throws'NOT_FOUND'.
The catalog is read-only and returns published products only.
List products
import { lynkow } from '@/lib/lynkow'
// Each product (partial): { id, title, path, priceCents, currency, thumbnail }
const { data, meta } = await lynkow.products.list({ page: 1, limit: 12 })
for (const product of data) {
console.log(`${product.title}: ${(product.priceCents / 100).toFixed(2)} ${product.currency}`)
}
console.log(`Page ${meta.currentPage} of ${meta.lastPage}`)Every price is an integer in the currency's minor unit (cents), with currency its ISO 4217 code. thumbnail is the first image URL, or null.
Filter, search, and sort
const { data } = await lynkow.products.list({
category: 'shirts', // a slug or a pcat_... id, sub-categories included
search: 'linen', // matches the title and the slug
sortBy: 'price_cents', // 'title', 'price_cents' or 'created_at' (default, newest first)
sortOrder: 'asc',
limit: 20,
})collection takes a slug or a col_... id the same way. An unknown or hidden collection or category throws 'NOT_FOUND'. kind: 'bookable' keeps the reservation products, which a buyer books instead of buying (Guide 19).
Prices with and without VAT
Each price comes as a pair, without VAT (priceNetCents) and with VAT (priceGrossCents). priceCents equals priceGrossCents. priceDisplayMode is the merchant's choice for the whole site: 'inclusive' shows the gross price, 'exclusive' the net one.
import type { Product } from 'lynkow'
function Price({ product }: { product: Product }) {
const withVat = product.priceDisplayMode === 'inclusive'
const cents = withVat ? product.priceGrossCents : product.priceNetCents
const was = withVat ? product.compareAtPriceGrossCents : product.compareAtPriceNetCents
const format = (value: number) => `${(value / 100).toFixed(2)} ${product.currency}`
return (
<p>
{was !== null ? <s>{format(was)}</s> : null} {format(cents)}
<small>{withVat ? ' incl. VAT' : ' excl. VAT'}</small>
</p>
)
}The gross price uses the VAT rate of the merchant's country. Pass the buyer's country (ISO 3166-1 alpha-2) in the request options to price at their rate:
const { data } = await lynkow.products.list({ limit: 12 }, { country: 'DE' })
const product = await lynkow.products.getBySlug('linen-shirt', { country: 'DE' })An unusable country falls back to the merchant's country and never fails the call. A bookable product is always priced at the merchant country's rate. Each variant carries the same price fields. The cart computes its own figures from the delivery address (Guide 23).
Markets and the catalogue
A merchant can hide a product in a market. Pass the market's mkt_... id in the request options to read the catalog as a buyer of that market sees it:
// Market (partial): { id, countries }
const { data: markets } = await lynkow.markets.list()
const market = markets.find((m) => m.countries.includes('BE'))
const { data } = await lynkow.products.list({ limit: 12 }, { market: market?.id, country: 'BE' })A list leaves out the products hidden in that market, and getBySlug() throws 'NOT_FOUND' for one. An unknown market filters nothing. Your storefront picks the market, usually from the buyer's country (Guide 23). productCollections.getBySlug(), productCategories.getBySlug() and paths.resolve() take market too.
Get one product
products.getBySlug() takes a slug or a prod_... id.
// app/products/[slug]/page.tsx
import { notFound } from 'next/navigation'
import { isLynkowError, type Product } from 'lynkow'
import { lynkow } from '@/lib/lynkow'
export default async function ProductPage({ params }: { params: Promise<{ slug: string }> }) {
const { slug } = await params
let product: Product
try {
product = await lynkow.products.getBySlug(slug)
} catch (error) {
if (isLynkowError(error) && error.code === 'NOT_FOUND') notFound()
throw error
}
// Serve the product only at its own public URL
if (product.path !== `/products/${slug}`) notFound()
return (
<article>
<h1>{product.title}</h1>
{product.gallery.map((image) => (
<img key={image.url} src={image.url} alt={image.alt ?? product.title} />
))}
{product.description ? <p>{product.description}</p> : null}
</article>
)
}A draft, archived or unknown product throws 'NOT_FOUND'. The path check returns a 404 when the product lives at another URL, for example under its category (Public URLs and routes). gallery lists the images in order with their alt and caption, and is empty when there are none.
brand, gtin and mpn are null when the merchant set none. A variant carries its own gtin and mpn, null when not set, without inheriting the product's.
Variants
When a product has variants, each carries its own selling price. Otherwise variants is empty and the product's priceCents is the selling price.
// Each variant (partial): { id, title, priceCents, optionValues: [{ option, value }] }
for (const variant of product.variants) {
const label = variant.optionValues.map((ov) => ov.value).join(' / ')
console.log(`${label}: ${(variant.priceCents / 100).toFixed(2)} ${product.currency}`)
}Availability
availability is 'in_stock' or 'out_of_stock', never a quantity. A product whose stock is not tracked is in stock, and a product with variants is in stock when one variant is. A bookable product reads null: its availability is its slots (Guide 19). List rows carry it too, so a grid can show a "Sold out" badge.
Each variant has its own availability, which can be absent. Treat a missing value as unknown:
<select name="variantId">
{product.variants.map((variant) => (
<option key={variant.id} value={variant.id} disabled={variant.availability === 'out_of_stock'}>
{variant.title}
</option>
))}
</select>When stock runs out
On a site that refuses overselling, cart.addLine() and cart.updateLine() throw a LynkowError with code 'VALIDATION_ERROR' and apiCode 'OUT_OF_STOCK' when the quantity exceeds the stock left, and change nothing. Checkout refuses the order with the same apiCode. The cart is covered in Guide 24.
Collections
// Each collection (partial): { slug, path, title, image }
const { data: collections } = await lynkow.productCollections.list({ limit: 20 })
const { data: products } = await lynkow.products.list({ collection: collections[0]?.slug, limit: 12 })productCollections.getBySlug(slug) reads one collection for its page, with its structured data:
// app/collections/[slug]/page.tsx (excerpt)
const collection = await lynkow.productCollections.getBySlug(slug)
const { data: products } = await lynkow.products.list({ collection: collection.slug, limit: 12 })
return (
<>
<div dangerouslySetInnerHTML={{ __html: renderJsonLdGraph(collection.structuredData?.graph) }} />
<h1>{collection.title}</h1>
<ProductList products={products} />
</>
)It takes the slug only, never the col_... id, and throws 'NOT_FOUND' for an unknown slug. Catch it as the product page does.
Category tree
productCategories.tree() returns the visible categories as root nodes, each nesting its children:
import type { ProductCategoryTreeNode } from 'lynkow'
const roots = await lynkow.productCategories.tree()
function printBranch(node: ProductCategoryTreeNode, depth = 0) {
console.log(`${' '.repeat(depth)}${node.name} -> ${node.path}`)
for (const child of node.children) printBranch(child, depth + 1)
}
roots.forEach((root) => printBranch(root))productCategories.getBySlug(slug) reads one category for its page: the fields of a tree node without children, plus its structured data. It takes the slug only. It throws 'NOT_FOUND' for an unknown slug, for a category hidden on the storefront (inactive, internal, or under a hidden parent), and for the slug tree, which the SDK refuses because that path is the tree. List its products with products.list({ category: category.slug }).
SEO metadata and structured data
Products, collections and categories carry the SEO fields the merchant fills in the SEO section of their editor, on every read. Two names differ from an article's: seoTitle and seoDescription instead of metaTitle and metaDescription. The others are the same: keywords, canonicalUrl, ogTitle, ogDescription, ogImage, ogImageAlt, twitterCard, noIndex and noFollow.
With @lynkow/next, one builder per record type turns them into Next.js metadata, with the fallbacks to the record's title, description and image:
// app/products/[slug]/page.tsx (lib/server.ts as in Guide 6)
import { lynkow } from '@/lib/lynkow'
import { server } from '@/lib/server'
export async function generateMetadata({ params }: { params: Promise<{ slug: string }> }) {
const { slug } = await params
return server.productMetadata(await lynkow.products.getBySlug(slug))
}server.productCollectionMetadata() and server.productCategoryMetadata() do the same. Without the adapter, the canonical URL is canonicalUrl, else your origin plus canonicalPath ?? path. Guide 7 covers the tags themselves.
Structured data
The three single reads carry structuredData.graph, the page's JSON-LD graph. List rows and tree nodes do not. Render it with renderJsonLdGraph(), which escapes the merchant's text so no value can close the script:
import { renderJsonLdGraph } from 'lynkow'
<div dangerouslySetInnerHTML={{ __html: renderJsonLdGraph(product.structuredData?.graph) }} />A product's graph holds a Product node with its offer, brand, GTIN and MPN, and an aggregate rating when approved reviews are linked to it. A collection or category graph holds a CollectionPage listing its first products. Guide 16 details the nodes and how the merchant adds their own.
Public URLs and routes
Every product, category and collection carries its public URL in path. Link with it, never by joining a prefix and a slug: the merchant can change the prefixes, translate them, and nest products under their category.
import Link from 'next/link'
{products.map((product) => (
<Link key={product.id} href={product.path}>{product.title}</Link>
))}The prefixes are set in Settings > SEO > URLs:
Page | Default URL | Setting |
|---|---|---|
Product |
| Product prefix |
Product category |
| Product category prefix |
Collection |
| Collection prefix |
With Put products under their category in the URL on, a product moves to /product-categories/{category-slug}/{product-slug}. A product without a category, or whose category is hidden, keeps the flat URL. Category and collection URLs are always flat.
getBySlug() finds a product by its slug alone, so a route on its own would also answer a wrong category segment. Compare the requested path with product.path and return a 404 when they differ, as the product page above does.
Route folders mirror the prefixes, so a prefix change needs a deploy. A catch-all route with paths.resolve() follows the configured and translated prefixes with no deploy: see Guide 9.
On a multi-language site, each locale has its own slug and its own base segments, and the locale request option reads a record in that locale. Guide 6 covers commerce pages in other locales and the fallback when a record is not translated.
When a slug or a prefix changes, a nested product changes category, or nesting is turned on or off, Lynkow stores a permanent (301) redirect from the old URL. Unpublishing or deleting a record creates none. paths.matchRedirect() serves those redirects, and the @lynkow/next proxy checks every page request against them, caching each answer for a minute (Guide 9).
Next Steps
Guide 19: Reservations and Deposits - book a
bookableproduct.Guide 24: Cart and Checkout - add products to a cart and place an order.