Reference - This guide is a tutorial. For exhaustive, always-current signatures and field lists, see the auto-generated reference:
Types: SDK Types
Prerequisites
A client in
lib/lynkow.ts(Add Lynkow to an existing project).A blog page that reads an article with
lynkow.contents.getBySlug().
1. Meta tags
Every article carries its SEO fields. metaTitle, metaDescription, keywords and canonicalUrl are null when the editor left them empty. noIndex and noFollow are always booleans.
// app/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<{ slug: string }>
}): Promise<Metadata> {
const { slug } = await params
const content = await lynkow.contents.getBySlug(slug)
return {
title: content.metaTitle || content.title,
description: content.metaDescription || undefined,
keywords: content.keywords || undefined,
// `path` is the article's public URL path, blog prefix included
alternates: { canonical: content.canonicalUrl || `${BASE_URL}${content.path}` },
robots: { index: !content.noIndex, follow: !content.noFollow },
}
}A noindexed article is left out of the sitemap and of the llms files.
Products, product collections and product categories name their fields seoTitle and seoDescription, with the same keywords, canonicalUrl, Open Graph and robots fields: see Guide 18.
2. Open Graph
Open Graph writes a locale as ll_CC (fr_FR, pt_BR), and Lynkow as a language tag (fr, pt-BR). This helper converts one into the other:
// lib/og-locale.ts
// 'fr' -> 'fr_FR', 'pt-BR' -> 'pt_BR', 'en' -> 'en_US'
export function ogLocale(tag: string): string {
const { language, region } = new Intl.Locale(tag).maximize()
return region ? `${language}_${region}` : language
}Add openGraph and twitter to the metadata of section 1:
import { ogLocale } from '@/lib/og-locale'
// Inside generateMetadata(), after reading `content`:
// the social fields are null when not set, so fall back to the meta fields.
const title = content.ogTitle || content.metaTitle || content.title
const description = content.ogDescription || content.metaDescription || undefined
// `ogImageVariants.og` is the 1200x630 crop. It is absent without an Open Graph image.
const image = content.ogImageVariants?.og
? { url: content.ogImageVariants.og, width: 1200, height: 630 }
: content.ogImage
? { url: content.ogImage }
: undefined
return {
// ...the fields of section 1
openGraph: {
type: 'article',
title,
description,
url: `${BASE_URL}${content.path}`,
// The locale the article was served in, which a fallback makes differ from the URL's
locale: ogLocale(content.locale),
images: image ? [image] : undefined,
publishedTime: content.publishedAt,
modifiedTime: content.updatedAt,
},
twitter: {
// 'app' and 'player' need a descriptor Lynkow does not store
card: content.twitterCard === 'summary' ? 'summary' : 'summary_large_image',
title,
description,
images: image ? [image.url] : undefined,
},
}3. Canonical and hreflang on a multi-language site
Each language version of an article has its own URL, its own canonical, and an hreflang set that lists every version plus x-default. A fallback (an article served in another locale because it has no translation in the one asked for) gets no hreflang set and points its canonical at the default locale's URL (Guide 6).
The @lynkow/next metadata builders apply these rules. With the lib/config.ts and lib/server.ts of Guide 6:
// app/[locale]/blog/[slug]/page.tsx
import type { Metadata } from 'next'
import { notFound } from 'next/navigation'
import { lynkow, paths, siteLocales } from '@/lib/config'
import { server } from '@/lib/server'
export async function generateMetadata({
params,
}: {
params: Promise<{ locale: string; slug: string }>
}): Promise<Metadata> {
const { locale: segment, slug } = await params
// The builders are synchronous and read the site's locales: load them first.
await siteLocales.get()
const locale = paths.toLocale(segment)
if (!locale) notFound()
const content = await lynkow(locale).contents.getBySlug(slug)
// Title, description, canonical, hreflang with x-default, Open Graph with og:locale
return server.articleMetadata(content)
}server.productMetadata(product), server.productCollectionMetadata(collection), server.productCategoryMetadata(category) and server.pageMetadata(page, locale, path) do the same for the other records. Without the adapter, build the hreflang set from content.alternates as Guide 6 shows.
4. Structured data
Articles, pages and commerce records carry a resolved JSON-LD graph in structuredData.graph. Guide 16 shows how to render it and how to configure it.
5. XML sitemap
// app/sitemap.xml/route.ts
import { lynkow } from '@/lib/lynkow'
export async function GET() {
const xml = await lynkow.seo.sitemap()
return new Response(xml, {
headers: {
'Content-Type': 'application/xml',
'Cache-Control': 'public, max-age=3600, s-maxage=3600',
},
})
}Lynkow rebuilds the sitemap within 5 minutes of a change, and within seconds for most edits.
What the sitemap lists
Each page type has its own switch under Settings > SEO > Sitemap: articles, article categories, pages, products, product categories and collections. A product category is listed when it is visible on the storefront and holds a published product, directly or in a sub-category. A collection is listed when it holds a published product.
An entry marked noindex is left out, whatever the switch of its type.
A commerce URL is the
paththe API returns for that record, so your routes and your sitemap agree.On a multi-language site, a record is listed once per locale it is written or translated in, at that locale's URL, with an
hreflanglink to each version and tox-default. A fallback URL is never listed.
Large sites and external sitemaps
seo.sitemap() returns a <sitemapindex> instead of a <urlset> in two cases:
Case | The index lists |
|---|---|
More than 50,000 URLs or 50 MB |
|
One file is enough, and an external sitemap is enabled |
|
Your site serves the files the index names. seo.sitemapPart(n) returns part n, counted from 1, and part 1 is also /sitemap-content.xml.
A Next.js folder named sitemap-[part].xml is not a dynamic segment, so rewrite the numbered names to a route handler:
// next.config.ts
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
async rewrites() {
return [{ source: '/sitemap\\-:part(\\d+)\\.xml', destination: '/sitemap-part/:part' }]
},
}
export default nextConfig// app/sitemap-part/[part]/route.ts
import { isLynkowError } from 'lynkow'
import { lynkow } from '@/lib/lynkow'
export async function GET(_request: Request, { params }: { params: Promise<{ part: string }> }) {
const { part } = await params
try {
const xml = await lynkow.seo.sitemapPart(Number(part))
return new Response(xml, { headers: { 'Content-Type': 'application/xml' } })
} catch (error) {
// A part above the count of parts is NOT_FOUND
if (isLynkowError(error) && error.code === 'NOT_FOUND') {
return new Response('Not found', { status: 404 })
}
throw error
}
}Serve app/sitemap-content.xml/route.ts the same way with lynkow.seo.sitemapPart(1). A Next.js proxy must leave these file names alone, as it does /sitemap.xml: the @lynkow/next proxy matcher already skips every path with a file extension (Guide 6).
6. robots.txt
seo.robots() returns the robots.txt built from the site's SEO settings, with the Sitemap: line when it is enabled.
// app/robots.txt/route.ts
import { lynkow } from '@/lib/lynkow'
export async function GET() {
const robotsTxt = await lynkow.seo.robots()
return new Response(robotsTxt, {
headers: {
'Content-Type': 'text/plain',
'Cache-Control': 'public, max-age=86400, s-maxage=86400',
},
})
}7. llms.txt
seo.llmsTxt() returns the summary index for AI assistants, and seo.llmsFullTxt() the full Markdown of every published article and page. Both take a locale option.
// app/llms.txt/route.ts
import { lynkow } from '@/lib/lynkow'
export async function GET() {
const llmsTxt = await lynkow.seo.llmsTxt()
return new Response(llmsTxt, {
headers: { 'Content-Type': 'text/plain; charset=utf-8' },
})
}Guide 14 covers llms-full.txt, per-locale files, one article as Markdown with seo.getMarkdown(), and content negotiation.
8. Analytics
In the browser, the client loads the Lynkow tracker as soon as it has read the site's cookie consent settings. The tracker records the first pageview, client-side navigations, Core Web Vitals, scroll depth and time on page. A client component that imports the client is enough to start it:
// components/analytics.tsx
'use client'
import { useEffect } from 'react'
import { lynkow } from '@/lib/lynkow'
export function Analytics() {
useEffect(() => {
// Idempotent: resolves once the tracker is loaded, or when consent blocks it
lynkow.analytics.init()
}, [])
return null
}Render it in the root layout, and set <html lang> to the locale the page is served in:
// app/[locale]/layout.tsx
import { Analytics } from '@/components/analytics'
export default async function RootLayout({
children,
params,
}: {
children: React.ReactNode
params: Promise<{ locale: string }>
}) {
const { locale } = await params
return (
<html lang={locale}>
<body>
{children}
<Analytics />
</body>
</html>
)
}Do not call trackPageview() on route changes: the tracker already records them, and the call would count each page twice. Call it only for a view that does not change the URL.
With @lynkow/next, LynkowTracker from @lynkow/next/client loads the tracker from a consent prop instead.
Content language
Each page view records the page's language, read from <html lang>, else from a first URL segment shaped like a language tag (/de/about). A value that is not a locale of the site is stored empty. A constant lang="en" on a multi-language site counts every page view as English.
The dashboard filters analytics by Content language. On the /v1 API, analytics reads such as /v1/analytics/overview accept a content_locale query parameter.
Custom events
trackEvent() takes a type from a closed list (click, outbound_link, form_start, form_submit and others, see AnalyticsEventType) and the collector's own snake_case keys. Lynkow drops any key the collector does not declare.
// components/cta-button.tsx
'use client'
import { lynkow } from '@/lib/lynkow'
export function CtaButton({ label, href }: { label: string; href: string }) {
return (
<a
href={href}
onClick={() =>
lynkow.analytics.trackEvent({
type: 'click',
click_element_text: label,
click_target_url: href,
})
}
>
{label}
</a>
)
}A form event names the form with form_name: trackEvent({ type: 'form_submit', form_name: 'contact' }).
lynkow.analytics.disable() turns your own trackEvent() and trackPageview() calls into no-ops, and enable() restores them. The tracker's automatic events follow the consent mode of section 9.
9. GDPR consent
In the browser, the client also shows the cookie consent banner configured in the dashboard to a visitor who has not answered yet. The tracker follows the site's consent mode:
Consent mode | Before the visitor answers | After a refusal |
|---|---|---|
| No tracker script is requested, and your | Nothing is loaded |
| Tracking runs | Tracking stops |
| Tracking runs, and the banner offers no refusal | Tracking runs |
Banner disabled | Tracking runs, with no consent gate | Tracking runs, even after |
When the consent settings cannot be read, the client applies opt-in. If your site needs consent before tracking, enable the banner.
Let visitors change their choice
consent.show() does nothing once the visitor has answered. A footer link reopens the preferences with showPreferences():
// components/manage-cookies-button.tsx
'use client'
import { lynkow } from '@/lib/lynkow'
export function ManageCookiesButton() {
return <button onClick={() => lynkow.consent.showPreferences()}>Manage cookie preferences</button>
}Your own consent UI
Record the visitor's answer with the consent methods. The tracker and the scripts configured per category in the dashboard follow it.
lynkow.consent.acceptAll()
lynkow.consent.rejectAll()
lynkow.consent.setCategories({ analytics: true, marketing: false })
lynkow.consent.hasConsented() // false until the visitor answers
lynkow.consent.getCategories() // { necessary: true, analytics: true, marketing: false, preferences: false }To act on a change in your own code, subscribe to consent-changed. on() returns the function that unsubscribes:
useEffect(() => {
return lynkow.on('consent-changed', (categories) => {
if (categories.analytics) lynkow.analytics.enable()
else lynkow.analytics.disable()
})
}, [])Consent collected by another tool
When another tool collects consent and never calls the methods above, hand each analytics answer to the tracker once it has loaded:
export function tellLynkowTracker(analyticsGranted: boolean) {
// No-op while the tracker is not loaded
window.LynkowAnalytics?.setConsent?.(analyticsGranted)
}true starts or resumes tracking. false withdraws the visitor cookie, and stops tracking on an opt-in or opt-out site.
Next Steps
Guide 16: JSON-LD Structured Data - render and configure the schema.org graph.
Guide 14: LLM-Ready Content - llms.txt, Markdown pages and content negotiation.
Guide 6: Multi-language - locales, fallbacks and hreflang.