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

# Getting Started

**Published**: 2026-11-30
**Category**: Services

## `browserOnly`

```typescript
function browserOnly(fn: () => T, fallback: T): T
```

Execute a function only in browser environment
Returns the fallback value in server environment

| Parameter | Type | Description |
| --- | --- | --- |
| `fn` | `() => T` | Function to execute in browser |
| `fallback` | `T` | Value to return in server environment |


Returns: `T`

```typescript
const visitorId = browserOnly(
  () => localStorage.getItem('visitor_id'),
  null
)
```

---

## `browserOnlyAsync`

```typescript
function browserOnlyAsync(fn: () => Promise<T>, fallback: T): Promise<T>
```

Execute an async function only in browser environment
Returns the fallback value in server environment

| Parameter | Type | Description |
| --- | --- | --- |
| `fn` | `() => Promise<T>` | Async function to execute in browser |
| `fallback` | `T` | Value to return in server environment |


Returns: `Promise<T>`

```typescript
const config = await browserOnlyAsync(
  () => fetchConfig(),
  defaultConfig
)
```

---

## `createClient`

```typescript
function createClient(config: ClientConfig): Client
```

Creates a Lynkow client. In the browser, it then starts the content
enhancements, loads the site config, detects the visitor's locale when none
is set, and starts analytics, the consent banner and the badge as the site
configures them. Throws when
`siteId` is empty, or when `serverKey` is set in a browser.

Any service call can reject with a `LynkowError`: a `NETWORK_ERROR` when the
API cannot be reached, or the `code` of the HTTP error (see
ErrorCode).

| Parameter | Type | Description |
| --- | --- | --- |
| `config` | `ClientConfig` | Client options, see ClientConfig |


Returns: `Client`

```typescript
const lynkow = createClient({
  siteId: process.env.NEXT_PUBLIC_LYNKOW_SITE_ID!,
  publishableKey: process.env.NEXT_PUBLIC_LYNKOW_PUBLISHABLE_KEY,
})
const { data } = await lynkow.contents.list()
```

---

## `createEventEmitter`

```typescript
function createEventEmitter(): { emit: (event: K, data: unknown) => void; off: (event: K, listener: EventListener<unknown>) => void; on: (event: K, listener: EventListener<unknown>) => () => void; once: (event: K, listener: EventListener<unknown>) => () => void; removeAllListeners: (event: keyof LynkowEvents) => void }
```

Creates a standalone event emitter typed by LynkowEvents, the kind
each client uses for `lynkow.on()`. Events never cross from one emitter to
another.

Returns: `{ emit: (event: K, data: unknown) => void; off: (event: K, listener: EventListener<unknown>) => void; on: (event: K, listener: EventListener<unknown>) => () => void; once: (event: K, listener: EventListener<unknown>) => () => void; removeAllListeners: (event: keyof LynkowEvents) => void }`

```typescript
import { createEventEmitter } from 'lynkow'

const events = createEventEmitter()
const unsubscribe = events.on('locale-changed', (locale) => {
  refetchContent(locale)
})
events.emit('locale-changed', 'fr')
unsubscribe()
```

---

## `createLynkowClient`

```typescript
function createLynkowClient(config: Omit<LynkowConfig, "serverKey" | "clientIp">): LynkowClient
```

Creates a client with the LynkowClient services only: no commerce
services, locale management, events, `media`, `clearCache()` or
`destroy()`, so its browser services cannot be stopped. Throws when
`siteId` is empty.

| Parameter | Type | Description |
| --- | --- | --- |
| `config` | `Omit<LynkowConfig, "serverKey" \| "clientIp">` | Client options, without `serverKey` and `clientIp` |


Returns: `LynkowClient`

```typescript
// Use createClient() instead:
const lynkow = createClient({ siteId: 'your-site-uuid' })
```

---

## `detectLocale`

```typescript
function detectLocale(enabledLocales: string[], defaultLocale: string, detection?: DetectionSettings): string
```

Returns the visitor's locale, one of `enabledLocales`, or `defaultLocale`
when nothing matches and on the server.

Without `detection`, it checks the stored choice (see
setStoredLocale), the URL path prefix (`/fr/...`), then
`<html lang>`. With `detection`, the path prefix comes first, then the
stored choice, then, when `detection.enabled` is `true`, the cookie and the
browser languages in `detection.order`, then `<html lang>`. A cookie,
browser or `lang` value also matches by its base language (`de-CH` gives
`de`).

| Parameter | Type | Description |
| --- | --- | --- |
| `enabledLocales` | `string[]` | The site's locales, e.g. `['en', 'fr']` |
| `defaultLocale` | `string` | Returned when nothing matches |
| `detection` | `DetectionSettings` | The site's `i18n.detection` from `site.getConfig()` |


Returns: `string`

```typescript
import { detectLocale } from 'lynkow'

const site = await lynkow.site.getConfig()
const locale = detectLocale(site.enabledLocales, site.defaultLocale, site.i18n.detection)
lynkow.setLocale(locale)
// '/fr/about' → 'fr', whatever the cookie or the browser says
// '/about' with a '_lkw_lang=de' cookie and order ['cookie', 'browser'] → 'de'
// '/about' with no cookie and navigator.languages ['es-MX'] → 'es'
```

---

## `detectSiteTheme`

```typescript
function detectSiteTheme(): "light" | "dark"
```

Returns the page's current theme, read in this order: a `data-theme`,
`data-mode` or `data-color-scheme` attribute on `<html>` or `<body>`, a
`dark` class on either, the CSS `color-scheme` of `<html>`, the brightness
of the `<body>` background, then the OS preference. Returns `'light'` on the
server.

Returns: `"light" | "dark"`

```typescript
const theme = detectSiteTheme()
```

---

## `generateSpamFields`

```typescript
function generateSpamFields(sessionStartTime: number): SpamFields
```

Builds the honeypot and timestamp fields for a storefront submission.
`forms.submit()` and `reviews.submit()` add them already: use this only when
you send the request yourself. Spread the result at the root of the body.
Outside the site's window, the API answers 429 with `apiCode`
`RATE_SUBMISSION_TOO_FAST` or 400 with `RATE_SUBMISSION_EXPIRED`.

| Parameter | Type | Description |
| --- | --- | --- |
| `sessionStartTime` | `number` | When the visitor started the form, in Unix milliseconds. |


Returns: `SpamFields`

```typescript
import { generateSpamFields } from 'lynkow'

const startedAt = Date.now() // when the form is shown
// At submit time, spread the fields at the root of the body:
const body = { data: answers, ...generateSpamFields(startedAt) }
```

---

## `getLocaleFromPath`

```typescript
function getLocaleFromPath(enabledLocales: string[]): string | null
```

Returns the locale in the first segment of the current URL path, as written
in `enabledLocales` (`/EN/about` gives `'en'`). Returns `null` on the server
or when the first segment is not one of them.

| Parameter | Type | Description |
| --- | --- | --- |
| `enabledLocales` | `string[]` | The site's locales |


Returns: `string | null`

```typescript
// window.location.pathname === '/fr/services'
getLocaleFromPath(['en', 'fr']) // 'fr'
// pathname === '/about'
getLocaleFromPath(['en', 'fr']) // null
```

---

## `getStoredLocale`

```typescript
function getStoredLocale(): string | null
```

Returns the locale stored by setStoredLocale, as written, or `null`
when none is stored, on the server, or when `localStorage` is blocked.
Check it against the site's locales before use.

Returns: `string | null`

```typescript
import { getStoredLocale } from 'lynkow'
const saved = getStoredLocale() // 'fr' | null
```

---

## `isCategoryResolve`

```typescript
function isCategoryResolve(response: ResolveResponse): response
```

Returns `true` when a `paths.resolve()` result is a category, narrowing it
to CategoryResolveResponse.

| Parameter | Type | Description |
| --- | --- | --- |
| `response` | `ResolveResponse` |  |


Returns: `response`

```typescript
// Resolve a URL path and render the appropriate template
const resolved = await lynkow.paths.resolve('/blog/tutorials')
if (isCategoryResolve(resolved)) {
  renderCategoryPage(resolved.category) // TypeScript narrows to CategoryResolveResponse
}
```

---

## `isContentResolve`

```typescript
function isContentResolve(response: ResolveResponse): response
```

Returns `true` when a `paths.resolve()` result is an article, narrowing it
to ContentResolveResponse.

| Parameter | Type | Description |
| --- | --- | --- |
| `response` | `ResolveResponse` |  |


Returns: `response`

```typescript
// Resolve a URL path and render the appropriate template
const resolved = await lynkow.paths.resolve('/blog/my-article')
if (isContentResolve(resolved)) {
  renderArticle(resolved.content) // TypeScript narrows to ContentResolveResponse
}
```

---

## `isLynkowError`

```typescript
function isLynkowError(error: unknown): error
```

Returns `true` when `error` is a `LynkowError`, so a `catch` block can read
its `code`, `apiCode`, `status` and `details`.

| Parameter | Type | Description |
| --- | --- | --- |
| `error` | `unknown` | The caught value |


Returns: `error`

```typescript
try {
  await lynkow.contents.getBySlug('missing')
} catch (error) {
  if (isLynkowError(error) && error.code === 'NOT_FOUND') notFound()
  else throw error
}
```

---

## `isRedirectResponse`

```typescript
function isRedirectResponse(response: Page | ResolveResponse): response
```

Returns `true` when a `paths.resolve()` or `pages.getByPath()` result is a
redirect: nothing lives at the path, but a redirect covers it. In the
`false` branch, a `pages.getByPath()` result narrows to `Page`.

| Parameter | Type | Description |
| --- | --- | --- |
| `response` | `Page \| ResolveResponse` |  |


Returns: `response`

```typescript
// Follow the redirect before rendering anything
const page = await lynkow.pages.getByPath('/en/about')
if (isRedirectResponse(page)) {
  // TypeScript narrows to ResolveRedirectResponse
  const { target, statusCode, preserveQueryString } = page.redirect
  return sendRedirect(target, statusCode, preserveQueryString)
}
renderPage(page.data) // TypeScript narrows to Page
```

---

## `isValidLocale`

```typescript
function isValidLocale(locale: string, enabledLocales: string[]): boolean
```

Returns `true` when `enabledLocales` contains `locale` exactly, case
included.

| Parameter | Type | Description |
| --- | --- | --- |
| `locale` | `string` | Locale to check |
| `enabledLocales` | `string[]` | The site's locales |


Returns: `boolean`

```typescript
isValidLocale('fr', ['en', 'fr']) // true
isValidLocale('FR', ['en', 'fr']) // false (case sensitive)
```

---

## `mergeIntoGraph`

```typescript
function mergeIntoGraph(server: object[] | null | undefined, custom: object[] | null | undefined): object[]
```

Appends your own JSON-LD nodes to a resolved graph, ready for renderJsonLdGraph.
`null` and `undefined` count as empty arrays. Logs a `console.warn` when one of your nodes
reuses an `@id` of the resolved graph, since search engines merge nodes that share an
`@id`. Prefix your ids with the page URL to keep them unique. Nothing is deduplicated,
reordered or rewritten.

| Parameter | Type | Description |
| --- | --- | --- |
| `server` | `object[] \| null \| undefined` | The resolved graph, such as `page.structuredData?.graph`. |
| `custom` | `object[] \| null \| undefined` | Your nodes, each with `@type` and a unique `@id`. |


Returns: `object[]`

```typescript
import { mergeIntoGraph, renderJsonLdGraph } from 'lynkow'
import { lynkow } from '@/lib/lynkow'

export default async function ReviewsPage() {
  const page = await lynkow.pages.getBySlug('reviews')
  const customNodes = [
    {
      '@context': 'https://schema.org',
      '@id': 'https://example.com/reviews#breadcrumb-extra',
      '@type': 'BreadcrumbList',
      'itemListElement': [ ],
    },
  ]
  const merged = mergeIntoGraph(page.structuredData?.graph, customNodes)
  return <div dangerouslySetInnerHTML={{ __html: renderJsonLdGraph(merged) }} />
}
```

---

## `onSiteThemeChange`

```typescript
function onSiteThemeChange(callback: (theme: "light" | "dark") => void): () => void
```

Calls `callback` each time the result of detectSiteTheme changes:
on a theme attribute, `class` or `style` change of `<html>` or `<body>`, or
on an OS preference change. Does nothing on the server.

| Parameter | Type | Description |
| --- | --- | --- |
| `callback` | `(theme: "light" \| "dark") => void` | Receives the new theme |


Returns: `() => void`

```typescript
const stop = onSiteThemeChange((theme) => widget.setTheme(theme))
stop()
```

---

## `removeStoredLocale`

```typescript
function removeStoredLocale(): void
```

Removes the stored locale, so detectLocale detects it again. Does
nothing on the server or when storage is blocked.

Returns: `void`

```typescript
import { removeStoredLocale } from 'lynkow'
removeStoredLocale() // Next visit re-detects from URL / html lang
```

---

## `renderJsonLdGraph`

```typescript
function renderJsonLdGraph(nodes: object[] | null | undefined): string
```

Renders a resolved JSON-LD graph, such as `content.structuredData.graph`, as one
`<script type="application/ld+json">` tag with a single top-level `@context`. Returns an
empty string for `null`, `undefined` or an empty array. `<`, `>`, `&`, U+2028 and U+2029
are written as their JSON escapes (`\u003c`, `\u003e`,
`\u0026`, `\u2028`, `\u2029`), so no value
can close the script early. That holds for the tag placed in HTML element content, never
inside an attribute value.

| Parameter | Type | Description |
| --- | --- | --- |
| `nodes` | `object[] \| null \| undefined` | The graph's nodes. `null`, `undefined` or an empty array renders nothing. |


Returns: `string`

```typescript
// Next.js App Router (server component)
import { createClient, renderJsonLdGraph } from 'lynkow'

const client = createClient({ siteId: process.env.LYNKOW_SITE_ID! })

export default async function ArticlePage({ params }: { params: { slug: string } }) {
  const article = await client.contents.getBySlug(params.slug)
  return (
    <>
      <div
        dangerouslySetInnerHTML={{
          __html: renderJsonLdGraph(article.structuredData?.graph),
        }}
      />
      <h1>{article.title}</h1>
      <article dangerouslySetInnerHTML={{ __html: article.body }} />
    </>
  )
}
```

---

## `setStoredLocale`

```typescript
function setStoredLocale(locale: string): void
```

Stores the visitor's locale in `localStorage`, for detectLocale on
later visits. `setLocale()` calls it for you. Does nothing on the server or
when storage is blocked.

| Parameter | Type | Description |
| --- | --- | --- |
| `locale` | `string` | Locale exactly as the site lists it, e.g. `'fr'` |


Returns: `void`

```typescript
import { setStoredLocale } from 'lynkow'
setStoredLocale('fr') // Remembers 'fr' across page loads
```