Reference - This guide is a tutorial. For exhaustive, always-current signatures and field lists, see the auto-generated reference:
SDK:
SiteService,ContentsService,PagesService,PathsServiceTypes: SDK Types
Prerequisites
A client in
lib/lynkow.ts(Add Lynkow to an Existing Project)A site with more than one language enabled in Lynkow
Next.js 16 with the App Router, for sections 3 to 9
1. Setup
Give the client a default locale with the locale option:
// lib/lynkow.ts
import { createClient } from 'lynkow'
export const lynkow = createClient({
siteId: process.env.NEXT_PUBLIC_LYNKOW_SITE_ID!,
locale: 'en',
})Without locale, a read carries no locale and the API answers in the site's default locale. Read the site's languages from its configuration, on the server as in the browser:
const { enabledLocales, defaultLocale } = await lynkow.site.getConfig()
// enabledLocales: ['en', 'fr', 'de'], defaultLocale: 'en'lynkow.availableLocales holds the same list once a site.getConfig() call has loaded it, and is empty before. A browser client makes that call by itself on startup, so server code reads site.getConfig() instead.
Browser auto-detection
In the browser, a client created without locale detects the visitor's locale on startup. Run the same detection yourself with detectLocale():
import { detectLocale } from 'lynkow'
const { enabledLocales, defaultLocale, i18n } = await lynkow.site.getConfig()
lynkow.setLocale(detectLocale(enabledLocales, defaultLocale, i18n.detection))It returns the first match, in this order:
The first segment of the URL path, e.g.
/fr/...localStorage, from a previoussetLocale()callWhen
i18n.detection.enabledistrue: the language cookie_lkw_lang, then the browser's preferred languagesThe
langattribute of<html>The site's default locale
A cookie or browser value matches an enabled locale by its whole tag first, then by its base language (de-CH matches de). Only enabled is set per site: the order, the cookie name and its 365-day lifetime are the same for every site. Without its third argument, detectLocale() skips step 3. During server rendering it returns the default locale.
Detection in the proxy
A site built with @lynkow/next also detects the locale on the server, in its proxy (section 6). Detection runs only when:
detection.enabledistrue,the path is
/, the home page,the request carries no language cookie, which the proxy sets on its first answer,
the user agent is not a robot (it contains
bot,crawl,spider,slurp,previeworheadless, or is missing), so crawlers index each page under its own URL.
The proxy matches the Accept-Language header against the site's locales. A match other than the default locale answers a 307 to that locale's home page, /fr. Otherwise the home page is served in the default locale.
2. Per-request locale
Pass request options as the last argument of a read, or as the only one for reads that take no other, such as paths.list() and site.getConfig():
// French for this call only
const { data: articles } = await lynkow.contents.list({}, { locale: 'fr' })
// German, or a 404 when no German translation exists
const post = await lynkow.contents.getBySlug('hello-world', { locale: 'de', fallback: false })localereplaces the client's locale for this call.fallback: falserefuses a record served in another language: see the Fallback contract.
contents.list({ locale: 'fr' }) also works. When both are given, the locale option wins over the filter.
To change the client's locale, for example when a visitor picks a language in the browser:
lynkow.setLocale('fr')Once the client has loaded the site configuration, setLocale() accepts only one of the site's enabled locales, spelled as the site lists it. Any other value logs a warning and changes nothing. Before that, it accepts any well-formed language tag.
On the server, use the per-request option. One client serves concurrent requests, and setLocale() changes the locale of all of them.
Server components with locale from params
// app/[locale]/blog/page.tsx
import { lynkow } from '@/lib/lynkow'
export default async function BlogPage({ params }: { params: Promise<{ locale: string }> }) {
const { locale } = await params
const { data: posts } = await lynkow.contents.list({}, { locale })
return (
<ul>
{posts.map((post) => (
<li key={post.id}>
{/* '/blog/hello-world' in the default locale, '/fr/blog/bonjour' in French */}
<a href={post.path}>{post.title}</a>
</li>
))}
</ul>
)
}Link with post.path. Building /${locale}/... by hand gives the default locale a prefix it does not have. This route assumes a proxy that rewrites an unprefixed URL such as /blog to the default locale's route, as the one of section 6 does.
Fallback contract
When a read asks for a locale and a record has no translation in it, the storefront API serves the closest translation it has, in this order: the requested locale, its base language (fr for fr-CA), the site's default locale, then the language the record was written in. A locale the site does not enable counts as a missing translation.
The answer is a 200 that names the locale it served, in a Content-Language header and in three fields on each record:
locale: the locale servedrequestedLocale: the locale asked forisFallback:truewhen the two differ
const post = await lynkow.contents.getBySlug('pricing', { locale: 'de' })
if (post.isFallback) {
// No German translation yet: served in post.locale, for example 'en'
}The three fields are present only when the read carries a locale, from the locale option or from the client.
A fallback record on your site:
keeps a URL in the requested locale: its
pathis under that locale's prefix with its source slug,/fr/blog/hello-world,has the default locale's URL as its canonical.
canonicalUrlholds it when no editor set one and the site has a domain in Lynkow,has an empty
alternatesarray, so it gets no hreflang (section 4),gets no entry in the Lynkow sitemap.
A product the merchant hid in a locale is not a missing translation: it stays a 404 there.
Refusing a fallback: fallback: false
import { isLynkowError } from 'lynkow'
try {
await lynkow.contents.getBySlug('pricing', { locale: 'de', fallback: false })
} catch (error) {
if (isLynkowError(error) && error.status === 404) {
// No German translation: render your own "not translated yet" page
}
}
// Only the articles that have a German translation
const { data: german } = await lynkow.contents.list({}, { locale: 'de', fallback: false })A detail read answers 404 and a list drops the items served in another locale. On a single-language site, lists ignore the option. To keep the page instead, test isFallback and show a notice such as "This article is not available in your language yet".
The fallback applies to the storefront API, which the SDK reads. The /v1 API stays strict, except its search endpoint, which accepts fallback and keeps it off by default.
3. Locale switcher component
Pages and contents carry an alternates array: page.alternates and content.alternates. Each entry is { locale, path, current }, where path is the site-relative URL of that language version: /about in the default locale, /fr/a-propos in French. A content with no translation has an empty array.
// components/locale-switcher.tsx
import Link from 'next/link'
type Alternate = { locale: string; path: string; current: boolean }
export function LocaleSwitcher({ alternates }: { alternates: Alternate[] }) {
if (alternates.length === 0) return null
return (
<nav aria-label="Language">
{alternates.map((alt) =>
alt.current ? (
<span key={alt.locale} aria-current="page">{alt.locale}</span>
) : (
<Link key={alt.locale} href={alt.path} hrefLang={alt.locale}>
{alt.locale}
</Link>
)
)}
</nav>
)
}Pass it content.alternates ?? [] for an article, or page.alternates for a page read with pages.getByPath() (Guide 3).
4. Generate hreflang tags
Hreflang tags list the language versions of a page, plus x-default: the URL offered to a visitor whose language matches none of them. Point x-default at the default locale's URL.
With @lynkow/next
The adapter's metadata builders build the whole set. Create them once, next to the configuration of section 6:
// lib/server.ts
import { cached, REVALIDATE, TAGS } from '@lynkow/next'
import { createLynkowServer } from '@lynkow/next/server'
import { config, lynkow, siteLocales } from './config'
export const server = createLynkowServer({
config,
client: (locale) => lynkow(locale),
siteLocales,
// The site's domain in Lynkow, from which the API builds absolute URLs
getSiteDomain: async (locale) => {
const site = await lynkow(locale).blocks.siteConfig(cached([TAGS.site], REVALIDATE.site))
return site.data.site.domain
},
})// app/[locale]/blog/[slug]/page.tsx
import type { Metadata } from 'next'
import { lynkow } from '@/lib/config'
import { pageLocale } from '@/lib/locale'
import { server } from '@/lib/server'
export async function generateMetadata({
params,
}: {
params: Promise<{ locale: string; slug: string }>
}): Promise<Metadata> {
const { locale: segment, slug } = await params
// Loads the site's locales, which the builders read (section 9)
const locale = await pageLocale(segment)
const content = await lynkow(locale).contents.getBySlug(slug)
return server.articleMetadata(content)
}server.articleMetadata(content) returns:
alternates.canonical: the article'scanonicalUrlwhen set, else its URL on your site.alternates.languages: one URL per entry ofcontent.alternates, plusx-defaultwhen one of them is in the default locale. A single-language site gets none.openGraph.localeandopenGraph.alternateLocale: the served locale and the others, in thell_CCform Open Graph uses (frbecomesfr_FR,enbecomesen_US).
A fallback record gets no languages and no alternateLocale, and its canonical is the default locale's URL, so the site needs a domain in Lynkow.
The other builders follow the same rules: server.pageMetadata(page, locale, path) for a Lynkow page, server.routeMetadata(locale, path, title, description) for a route your application owns in every locale, and server.productMetadata(product), server.productCollectionMetadata(collection) and server.productCategoryMetadata(category) for commerce records. They are synchronous: call them after await siteLocales.get().
On an English-default site, an article translated into French produces:
<link rel="canonical" href="https://example.com/blog/hello-world" />
<link rel="alternate" hreflang="en" href="https://example.com/blog/hello-world" />
<link rel="alternate" hreflang="fr" href="https://example.com/fr/blog/bonjour-le-monde" />
<link rel="alternate" hreflang="x-default" href="https://example.com/blog/hello-world" />
<meta property="og:locale" content="en_US" />
<meta property="og:locale:alternate" content="fr_FR" />Without the adapter
With the single client of section 1, build the set from the same data:
// app/[locale]/blog/[slug]/page.tsx
import type { Metadata } from 'next'
import { lynkow } from '@/lib/lynkow'
const BASE_URL = 'https://example.com'
export async function generateMetadata({
params,
}: {
params: Promise<{ locale: string; slug: string }>
}): Promise<Metadata> {
const { locale, slug } = await params
const [content, site] = await Promise.all([
lynkow.contents.getBySlug(slug, { locale }),
lynkow.site.getConfig(),
])
// `path` is already in the site's URL form: '/blog/hello-world', '/fr/blog/bonjour-le-monde'
const languages: Record<string, string> = {}
for (const alt of content.alternates ?? []) languages[alt.locale] = `${BASE_URL}${alt.path}`
if (languages[site.defaultLocale]) languages['x-default'] = languages[site.defaultLocale]
return {
title: content.metaTitle || content.title,
alternates: {
canonical: content.canonicalUrl || `${BASE_URL}${content.path}`,
// A fallback record has no alternates, so it advertises no language versions
languages: Object.keys(languages).length > 0 ? languages : undefined,
},
}
}5. Static generation per locale
paths.list() lists the article and category paths of one locale, so call it once per locale. This sample uses the @lynkow/next setup of section 6:
// app/[locale]/[...slug]/page.tsx
import { lynkow, paths, siteLocales } from '@/lib/config'
export async function generateStaticParams() {
const { locales } = await siteLocales.get()
const params: Array<{ locale: string; slug: string[] }> = []
for (const locale of locales) {
const { paths: list } = await lynkow(locale).paths.list()
// The locale's prefix: '' for the default locale, '/fr' for French
const prefix = paths.localePath(locale, '/').replace(/\/$/, '')
for (const p of list) {
// Drop the prefix: the [locale] segment of the route carries it
const slug = paths.fromApiPath(p.path, locale).slice(prefix.length).split('/').filter(Boolean)
if (slug.length > 0) params.push({ locale: locale.toLowerCase(), slug })
}
}
return params
}Guide 9 adds the commerce paths and skips the fallback entries.
Languages are read at runtime
The proxy, the paths helpers and the metadata builders read the site's languages from siteLocales while the site runs. A language you enable in Lynkow needs no rebuild: Next.js renders its pages on their first request, unless you set dynamicParams to false.
siteLocales keeps what it read for 60 seconds. To pick up a change at once, pass it to the revalidation handler (Guide 11), which marks it stale on a site.updated event:
// app/api/revalidate/route.ts
import { createRevalidateHandler } from '@lynkow/next/server'
import { siteLocales } from '@/lib/config'
export const runtime = 'nodejs'
export const POST = createRevalidateHandler({
secret: process.env.LYNKOW_WEBHOOK_SECRET,
siteLocales,
})Only the server instance that receives the webhook is told. Other instances read the new languages once their copy is older than 60 seconds.
6. Locale routing with the Next.js proxy
@lynkow/next routes every request by locale in your proxy.ts, the file Next.js 16 runs before a page renders. It serves the default locale without a prefix (/about) and every other locale under its own (/fr/a-propos).
npm install @lynkow/next lynkowConfiguration
// lib/config.ts
import { createClients, createLocalePaths, createSiteLocales, resolveConfig } from '@lynkow/next'
export const config = resolveConfig({
siteId: process.env.NEXT_PUBLIC_LYNKOW_SITE_ID,
siteUrl: process.env.NEXT_PUBLIC_SITE_URL,
defaultLocale: process.env.NEXT_PUBLIC_LYNKOW_DEFAULT_LOCALE,
})
// The closure reads the clients only when called, so the two wire without a cycle
export const siteLocales = createSiteLocales({ client: (locale) => lynkow(locale) })
export const lynkow = createClients(config, { siteLocales })
export const paths = createLocalePaths(config, siteLocales)siteLocalesreads the site's enabled locales, default locale, writing directions and detection settings from Lynkow, and keeps them for 60 seconds.defaultLocaleis the locale it reads the site in before its first load.lynkow(locale)returns that locale's client, created on first use and reused.lynkow()is the default locale's. It replaces the single client of section 1.paths.localePath('fr', '/blog')gives/fr/blog, andpaths.localePath('en', '/blog')gives/blogon an English-default site. Thepathshelpers are synchronous and throw until the site's locales have loaded: callawait siteLocales.get()first.
The proxy
// proxy.ts
import { createLynkowProxy } from '@lynkow/next/proxy'
import { config as site, lynkow, siteLocales } from './lib/config'
export default createLynkowProxy({
config: site,
// Passed as is: the proxy asks it for a client that does not retry
client: lynkow,
siteLocales,
// The account pages the account emails link to. `/account` by default.
accountPagesPath: '/account',
})
// Next.js requires a literal matcher in proxy.ts: every page, no internals, API routes or files
export const config = {
matcher: ['/((?!_next/|api/|.*\\.[\\w]+$).*)'],
}The site configuration is imported as site because Next.js reads the proxy's own config export. On every page request, the proxy:
Serves redirects from the Lynkow redirect lookup, your own rules first. A path under the default locale's prefix answers a 301 to its unprefixed URL:
/en/aboutto/abouton an English-default site. Guide 9 covers the redirects.Detects the language on a first visit to the home page, as in Detection in the proxy.
Routes by locale. An unprefixed path is the default locale's page: the proxy rewrites it to your
app/[locale]/...route under the same URL, so/aboutrendersapp/[locale]/[...slug]/page.tsxwithlocaleset toen. A path under another locale is served as it is. Written in another case,/FR/a-proposanswers a 308 to/fr/a-propos.
Accept-Language never changes the locale of an unprefixed path. The language cookie changes it on a few pages only: the payment return and cancel pages (/checkout/payment/return, /checkout/payment/cancel), and accountPagesPath with its /activate/<token>, /reset-password/<token> and /verify-email/<token> pages. Those are served in the cookie's locale when the site has it, so a buyer back from paying keeps their language.
The language cookie
Every response the proxy routes sets the _lkw_lang cookie to the locale it serves: 365 days, Path=/, SameSite=Lax, and readable by JavaScript so the SDK's browser detection sees it. The payment and account pages above read it and never write it. The cookie only remembers the visitor's language, so it is strictly necessary: the proxy sets it whatever the visitor's consent state.
If the site's languages cannot be read from Lynkow and your configuration has no static locales list, the proxy lets the request through unchanged and logs an error.
7. URL patterns
On a site whose default locale is English:
Route type | Default locale | Another locale |
|---|---|---|
Home page |
|
|
Blog listing |
|
|
Blog post |
|
|
Page |
|
|
Category |
|
|
Product |
|
|
Product category |
|
|
Collection |
|
|
Locale prefixes are lowercase. Slugs can differ between locales, so read a version's URL from alternates and build every other localized URL with paths.localePath(locale, path). A path under the default locale's prefix, such as /en/blog, is a 301 to /blog.
To render any of these paths from one route, see Guide 9: Catch-all Routes.
Commerce pages and other locales
Products, product categories and collections (Guide 18) have their own text, slug and base segments per locale. The default segments are products, product-categories and collections, and a site can set its own per locale: the French segments in the table above are examples of a merchant's own.
Not yet translated. The entity is served under the locale's prefix and segment with its source slug, in a fallback language:
/fr/produits/linen-shirt. Itsalternatesarray is empty.Hidden in a locale. The page is a 404 there, and
alternateshas no entry for that locale.Translated slug. Once the entity has its own slug in a locale, its source-slug URL answers a 301 to the translated one:
/fr/produits/linen-shirtto/fr/produits/chemise-lin. The proxy of section 6 serves it, and a redirect rule you created for the same path wins.
The Lynkow sitemap lists a commerce entity once per locale it is translated in, with its hreflang alternates.
8. Cache behavior
The SDK's own response cache is off by default, and that is the recommended setup for server rendering (Guide 11). With cache: true on the client:
Every cached read is keyed by its locale and by
fallback: false. One client serves every locale from its cache, and a per-request locale clears nothing.setLocale()with a new locale clears this client's cache.
createClients of @lynkow/next creates every client with the SDK cache off, so the Next.js data cache is the only one. Its tags name a resource, not a locale: a webhook revalidates every locale of that resource.
9. Complete i18n layout example
A Next.js App Router site with @lynkow/next: the default locale without a prefix, the site's locales read at runtime, and a locale switcher.
app/
[locale]/
layout.tsx
blog/[slug]/page.tsx
[...slug]/page.tsx # Guide 9
components/
locale-switcher.tsx # section 3
lib/
config.ts # section 6
locale.ts
server.ts # section 4
proxy.ts # section 6Every route sits under app/[locale]: the proxy rewrites an unprefixed URL to the default locale's route, so /about and /fr/a-propos both reach it.
Page locale helper
// lib/locale.ts
import { notFound } from 'next/navigation'
import { paths, siteLocales } from '@/lib/config'
/** The site locale a `[locale]` segment names, or a 404. */
export async function pageLocale(segment: string): Promise<string> {
// The `paths` helpers throw until the site's locales have loaded
await siteLocales.get()
const locale = paths.toLocale(segment)
if (!locale) notFound()
return locale
}The URL segment is lowercase (pt-br), and paths.toLocale() returns the locale as the site spells it (pt-BR).
Root layout
// app/[locale]/layout.tsx
import type { ReactNode } from 'react'
import { paths, siteLocales } from '@/lib/config'
import { pageLocale } from '@/lib/locale'
import { LocaleSwitcher } from '@/components/locale-switcher'
export async function generateStaticParams() {
const { locales } = await siteLocales.get()
return locales.map((locale) => ({ locale: locale.toLowerCase() }))
}
export default async function LocaleLayout({
children,
params,
}: {
children: ReactNode
params: Promise<{ locale: string }>
}) {
const locale = await pageLocale((await params).locale)
const { locales, directions } = siteLocales.current()
return (
<html lang={locale} dir={directions[locale] ?? 'ltr'}>
<body>
<header>
<a href={paths.localePath(locale, '/blog')}>Blog</a>
<LocaleSwitcher
alternates={locales.map((loc) => ({
locale: loc,
path: paths.localePath(loc, '/'),
current: loc === locale,
}))}
/>
</header>
<main>{children}</main>
</body>
</html>
)
}Blog post page
// app/[locale]/blog/[slug]/page.tsx
import { notFound } from 'next/navigation'
import { isLynkowError } from 'lynkow'
import { lynkow } from '@/lib/config'
import { pageLocale } from '@/lib/locale'
import { LocaleSwitcher } from '@/components/locale-switcher'
// generateMetadata: section 4
export default async function BlogPostPage({
params,
}: {
params: Promise<{ locale: string; slug: string }>
}) {
const { locale: segment, slug } = await params
const locale = await pageLocale(segment)
let content
try {
content = await lynkow(locale).contents.getBySlug(slug)
} catch (error) {
// Only a missing article is a 404: rethrow anything else
if (isLynkowError(error) && error.status === 404) notFound()
throw error
}
return (
<article>
<LocaleSwitcher alternates={content.alternates ?? []} />
<h1>{content.title}</h1>
<div dangerouslySetInnerHTML={{ __html: content.body }} />
</article>
)
}generateMetadata should map a 404 the same way and rethrow other errors (Guide 12).
Next Steps
Catch-all Routes & Path Resolution - resolve every path of a localized site from one route
Guide 7: SEO & Analytics - canonical URLs and meta tags per locale
Guide 11: Webhooks & Cache Revalidation - revalidate every locale on publish