browserOnly
function browserOnly(fn: () => T, fallback: T): TExecute a function only in browser environment Returns the fallback value in server environment
Parameter | Type | Description |
|---|---|---|
|
| Function to execute in browser |
|
| Value to return in server environment |
Returns: T
const visitorId = browserOnly(
() => localStorage.getItem('visitor_id'),
null
)browserOnlyAsync
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 |
|---|---|---|
|
| Async function to execute in browser |
|
| Value to return in server environment |
Returns: Promise<T>
const config = await browserOnlyAsync(
() => fetchConfig(),
defaultConfig
)createClient
function createClient(config: ClientConfig): ClientCreates 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 |
|---|---|---|
|
| Client options, see ClientConfig |
Returns: Client
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
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 }
import { createEventEmitter } from 'lynkow'
const events = createEventEmitter()
const unsubscribe = events.on('locale-changed', (locale) => {
refetchContent(locale)
})
events.emit('locale-changed', 'fr')
unsubscribe()createLynkowClient
function createLynkowClient(config: Omit<LynkowConfig, "serverKey" | "clientIp">): LynkowClientCreates 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 |
|---|---|---|
|
| Client options, without |
Returns: LynkowClient
// Use createClient() instead:
const lynkow = createClient({ siteId: 'your-site-uuid' })detectLocale
function detectLocale(enabledLocales: string[], defaultLocale: string, detection?: DetectionSettings): stringReturns 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 |
|---|---|---|
|
| The site's locales, e.g. |
|
| Returned when nothing matches |
|
| The site's |
Returns: string
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
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"
const theme = detectSiteTheme()generateSpamFields
function generateSpamFields(sessionStartTime: number): SpamFieldsBuilds 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 |
|---|---|---|
|
| When the visitor started the form, in Unix milliseconds. |
Returns: SpamFields
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
function getLocaleFromPath(enabledLocales: string[]): string | nullReturns 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 |
|---|---|---|
|
| The site's locales |
Returns: string | null
// window.location.pathname === '/fr/services'
getLocaleFromPath(['en', 'fr']) // 'fr'
// pathname === '/about'
getLocaleFromPath(['en', 'fr']) // nullgetStoredLocale
function getStoredLocale(): string | nullReturns 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
import { getStoredLocale } from 'lynkow'
const saved = getStoredLocale() // 'fr' | nullisCategoryResolve
function isCategoryResolve(response: ResolveResponse): responseReturns true when a paths.resolve() result is a category, narrowing it
to CategoryResolveResponse.
Parameter | Type | Description |
|---|---|---|
|
|
Returns: response
// 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
function isContentResolve(response: ResolveResponse): responseReturns true when a paths.resolve() result is an article, narrowing it
to ContentResolveResponse.
Parameter | Type | Description |
|---|---|---|
|
|
Returns: response
// 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
function isLynkowError(error: unknown): errorReturns true when error is a LynkowError, so a catch block can read
its code, apiCode, status and details.
Parameter | Type | Description |
|---|---|---|
|
| The caught value |
Returns: error
try {
await lynkow.contents.getBySlug('missing')
} catch (error) {
if (isLynkowError(error) && error.code === 'NOT_FOUND') notFound()
else throw error
}isRedirectResponse
function isRedirectResponse(response: Page | ResolveResponse): responseReturns 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 |
|---|---|---|
|
|
Returns: response
// 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 PageisValidLocale
function isValidLocale(locale: string, enabledLocales: string[]): booleanReturns true when enabledLocales contains locale exactly, case
included.
Parameter | Type | Description |
|---|---|---|
|
| Locale to check |
|
| The site's locales |
Returns: boolean
isValidLocale('fr', ['en', 'fr']) // true
isValidLocale('FR', ['en', 'fr']) // false (case sensitive)mergeIntoGraph
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 |
|---|---|---|
|
| The resolved graph, such as |
|
| Your nodes, each with |
Returns: object[]
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
function onSiteThemeChange(callback: (theme: "light" | "dark") => void): () => voidCalls 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 |
|---|---|---|
|
| Receives the new theme |
Returns: () => void
const stop = onSiteThemeChange((theme) => widget.setTheme(theme))
stop()removeStoredLocale
function removeStoredLocale(): voidRemoves the stored locale, so detectLocale detects it again. Does nothing on the server or when storage is blocked.
Returns: void
import { removeStoredLocale } from 'lynkow'
removeStoredLocale() // Next visit re-detects from URL / html langrenderJsonLdGraph
function renderJsonLdGraph(nodes: object[] | null | undefined): stringRenders 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 |
|---|---|---|
|
| The graph's nodes. |
Returns: string
// 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
function setStoredLocale(locale: string): voidStores 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 exactly as the site lists it, e.g. |
Returns: void
import { setStoredLocale } from 'lynkow'
setStoredLocale('fr') // Remembers 'fr' across page loads