> For the complete Lynkow documentation index in agent-friendly format, see [llms.txt](/llms.txt).

# SEO & Analytics

**Publié le** : 2026-11-30
**Catégorie** : Media & SEO

> **Reference** - This guide is a tutorial. For exhaustive, always-current signatures and field lists, see the auto-generated reference:
> 
> - SDK: [`SeoService`](/docs/sdk/services/sdk-seo-service), [`AnalyticsService`](/docs/sdk/services/sdk-analytics-service), [`ConsentService`](/docs/sdk/services/sdk-consent-service)
> - Types: [SDK Types](/docs/sdk/types)
> - API: [Storefront: SEO](/docs/storefront-api/storefront-seo), [Storefront: Analytics](/docs/storefront-api/storefront-analytics)

## Prerequisites

- A client in `lib/lynkow.ts` ([Add Lynkow to an existing project](/docs/sdk/getting-started/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.

```typescript
// 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](/docs/sdk/features/commerce-products#seo-metadata-and-structured-data).

---

## 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:

```typescript
// 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:

```typescript
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](/docs/sdk/features/i18n#fallback-contract)).

The `@lynkow/next` metadata builders apply these rules. With the `lib/config.ts` and `lib/server.ts` of [Guide 6](/docs/sdk/features/i18n#4-generate-hreflang-tags):

```typescript
// 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](/docs/sdk/features/i18n#without-the-adapter) shows.

---

## 4. Structured data

Articles, pages and commerce records carry a resolved JSON-LD graph in `structuredData.graph`. [Guide 16](/docs/sdk/features/json-ld-cascade) shows how to render it and how to configure it.

---

## 5. XML sitemap

```typescript
// 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 `path` the 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 `hreflang` link to each version and to `x-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 | `/sitemap-1.xml` to `/sitemap-N.xml`, then the external sitemaps enabled in the dashboard |
| One file is enough, and an external sitemap is enabled | `/sitemap-content.xml`, then the external sitemaps |


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:

```typescript
// 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
```

```typescript
// 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](/docs/sdk/features/i18n#6-locale-routing-with-the-nextjs-proxy)).

---

## 6. robots.txt

`seo.robots()` returns the robots.txt built from the site's SEO settings, with the `Sitemap:` line when it is enabled.

```typescript
// 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.

```typescript
// 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](/docs/sdk/advanced/llm-ready-content) 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:

```typescript
// 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:

```typescript
// 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.

```typescript
// 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 |
| --- | --- | --- |
| `opt-in` | No tracker script is requested, and your `trackEvent()` calls send nothing | Nothing is loaded |
| `opt-out` | Tracking runs | Tracking stops |
| `notice-only` | Tracking runs, and the banner offers no refusal | Tracking runs |
| Banner disabled | Tracking runs, with no consent gate | Tracking runs, even after `consent.rejectAll()` |


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()`:

```typescript
// 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.

```typescript
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:

```typescript
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:

```typescript
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](/docs/sdk/features/json-ld-cascade) - render and configure the schema.org graph.
- [Guide 14: LLM-Ready Content](/docs/sdk/advanced/llm-ready-content) - llms.txt, Markdown pages and content negotiation.
- [Guide 6: Multi-language](/docs/sdk/features/i18n) - locales, fallbacks and hreflang.