Reference - This guide is a tutorial. For exhaustive, always-current signatures and field lists, see the auto-generated reference:
SDK:
PagesService,BlocksService,SiteServiceTypes: SDK Types
API: Storefront: Pages
Prerequisites
A Next.js App Router project with the SDK client in
lib/lynkow.ts(Add Lynkow to an Existing Project).At least one global block (a header, for example) and one page published in your Lynkow site.
Layout from global blocks
lynkow.globals.siteConfig() returns the site's name and favicon, and every published global block keyed by its slug, in one request. lynkow.globals and lynkow.blocks are the same service.
// app/layout.tsx
import { lynkow } from '@/lib/lynkow'
import { Header } from '@/components/header'
export default async function RootLayout({ children }: { children: React.ReactNode }) {
const { data } = await lynkow.globals.siteConfig()
const header = data.globals['header'] // the block whose slug is "header"
return (
<html lang={data.locale}>
<head>{data.site.favicon && <link rel="icon" href={data.site.favicon} />}</head>
<body>
{header && <Header data={header.data} siteName={data.site.name} />}
<main>{children}</main>
</body>
</html>
)
}A block's data follows the schema you gave the block in the admin. Type it for your own schema. This header reads a logo and a navigation list:
// components/header.tsx
import Link from 'next/link'
interface HeaderData {
logo?: { url: string; alt: string } | null
navigation?: Array<{ label: string; url: string }>
}
export function Header({ data, siteName }: { data: Record<string, unknown>; siteName: string }) {
const { logo, navigation } = data as unknown as HeaderData
return (
<header>
<Link href="/">{logo ? <img src={logo.url} alt={logo.alt || siteName} /> : siteName}</Link>
<nav>
{navigation?.map((item) => (
<Link key={item.url} href={item.url}>
{item.label}
</Link>
))}
</nav>
</header>
)
}A footer follows the same pattern with data.globals['footer']. To read one block outside the layout, call lynkow.globals.getBySlug('footer'), which answers { data: GlobalBlock }.
On a multi-language site
Pass the route's locale to siteConfig() to read the blocks in that language. data.site is not translated: take the localized name, description and logo from lynkow.site.getConfig().
const [{ data }, site] = await Promise.all([
lynkow.globals.siteConfig({ locale }),
lynkow.site.getConfig({ locale }),
])
// <Header data={data.globals['header'].data} siteName={site.name} />Locale routing and the fallback a missing translation gets are covered in Multi-language (i18n).
Render a page by URL
pages.getByPath() finds the page published at a URL path, nested paths included (/services/consulting). It returns one of two answers:
a
Page, with itsdata,seo,alternatesandstructuredData;a redirect answer, when a redirect covers the path and no page holds it. Narrow it with
isRedirectResponse()before reading a page field.
It throws a LynkowError with code NOT_FOUND when neither exists.
// app/[[...slug]]/page.tsx
import type { Metadata } from 'next'
import { notFound, permanentRedirect, redirect } from 'next/navigation'
import { isLynkowError, isRedirectResponse, renderJsonLdGraph } from 'lynkow'
import { lynkow } from '@/lib/lynkow'
import { PageRenderer } from '@/components/page-renderer'
type Params = Promise<{ slug?: string[] }>
const SITE_ORIGIN = new URL(process.env.NEXT_PUBLIC_SITE_URL!).origin
const pathOf = (url: string) => new URL(url, SITE_ORIGIN).pathname.replace(/\/+$/, '') || '/'
async function getPage(slug: string[] = []) {
const path = `/${slug.join('/')}`
try {
const page = await lynkow.pages.getByPath(path)
if (isRedirectResponse(page)) {
const { target, statusCode } = page.redirect
// A rule can point a path back at itself (`/*` to `/*`): answer 404 instead of looping
if (new URL(target, SITE_ORIGIN).origin === SITE_ORIGIN && pathOf(target) === pathOf(path)) notFound()
// Next.js answers 308 or 307; it cannot send 301 or 302 from a page
if (statusCode === 301 || statusCode === 308) permanentRedirect(target)
redirect(target)
}
return page
} catch (error) {
// redirect() throws too: anything that is not a LynkowError is rethrown
if (isLynkowError(error) && error.code === 'NOT_FOUND') notFound()
throw error
}
}
export async function generateStaticParams() {
const { data: pages } = await lynkow.pages.list()
return pages.map((page) => ({
// The home page ("/") takes no segment
slug: page.publicPath === '/' ? undefined : page.publicPath.split('/').filter(Boolean),
}))
}
export async function generateMetadata({ params }: { params: Params }): Promise<Metadata> {
const { seo } = await getPage((await params).slug)
if (!seo) return {}
return {
title: seo.metaTitle,
description: seo.metaDescription,
openGraph: { images: seo.ogImage ? [{ url: seo.ogImage.url }] : undefined },
alternates: { canonical: seo.canonicalUrl },
robots: seo.noIndex ? { index: false } : undefined,
}
}
export default async function Page({ params }: { params: Params }) {
const page = await getPage((await params).slug)
return (
<>
{/* The page's schema.org graph, as one escaped <script> tag */}
<div dangerouslySetInnerHTML={{ __html: renderJsonLdGraph(page.structuredData?.graph) }} />
<PageRenderer slug={page.slug} data={page.data} />
</>
)
}NEXT_PUBLIC_SITE_URLis your site's public URL. A redirect whose target leads back to the asked path on that origin answers 404 instead of looping.The redirect branch drops the query string and maps the status code. Serve redirects from the Next.js proxy instead, where the exact code and the query string are kept: see Redirect Handling in the Proxy. Keep the branch for the paths the proxy does not route.
publicPathis the URL to link to.generateStaticParamsabove suits a single-language site; for several languages, see Multi-language (i18n).hreflang tags and the canonical of a page served in a fallback language are built by
@lynkow/next: see Multi-language (i18n).To resolve articles, categories and pages from one catch-all route, use
paths.resolve()instead: see Catch-all Routes & Path Resolution.
When you know the page's slug rather than its URL, call lynkow.pages.getBySlug('homepage'). It returns the same Page and never a redirect answer.
Page data and data sources
page.data holds the values of the page's schema. A data source field (latest articles, approved reviews) arrives already resolved, as { items, meta: { totalCount, hasMore } }. Switch on the slug to pick a component per page:
// components/page-renderer.tsx
import { Homepage } from './pages/homepage'
import { GenericPage } from './pages/generic'
export function PageRenderer({ slug, data }: { slug: string; data: Record<string, unknown> }) {
switch (slug) {
case 'homepage':
return <Homepage data={data} />
default:
return <GenericPage data={data} />
}
}// components/pages/homepage.tsx
interface HomepageData {
hero: { title: string; subtitle: string }
// A reviews data source
testimonials?: { items: Array<{ id: string; authorName: string; rating: number; content: string }> }
}
export function Homepage({ data }: { data: Record<string, unknown> }) {
const { hero, testimonials } = data as unknown as HomepageData
return (
<>
<h1>{hero.title}</h1>
<p>{hero.subtitle}</p>
{testimonials?.items.map((review) => (
<blockquote key={review.id}>
<p>{review.content}</p>
<cite>
{review.authorName}, {review.rating}/5
</cite>
</blockquote>
))}
</>
)
}A data source that fails to resolve comes back empty, and the page then lists the reason in page._warnings. Read data source fields with optional chaining.
Navigation and legal pages
pages.list() returns every published page with its name and publicPath. The tag option keeps the pages carrying that tag in the admin:
// components/legal-links.tsx
import Link from 'next/link'
import { lynkow } from '@/lib/lynkow'
export async function LegalLinks() {
const { data: pages } = await lynkow.pages.list({ tag: 'legal' })
return (
<nav aria-label="Legal">
{pages.map((page) => (
<Link key={page.id} href={page.publicPath}>
{page.name}
</Link>
))}
</nav>
)
}Drop the tag option to list every page for a menu or a sitemap.
Not-found page
notFound() in the page route renders app/not-found.tsx:
// app/not-found.tsx
import Link from 'next/link'
export default function NotFound() {
return (
<main>
<h1>Page not found</h1>
<Link href="/">Back to the home page</Link>
</main>
)
}SDK cache
On top of the Next.js data cache, the SDK keeps pages for 5 minutes and single global blocks for 10 minutes in memory. globals.siteConfig() is never cached by the SDK. Call lynkow.pages.clearCache() or lynkow.globals.clearCache() to drop them, for example from a revalidation webhook (Webhooks & Cache Revalidation).
Next Steps
Guide 4: Dynamic Forms: render and submit the forms of your pages.
Catch-all Routes & Path Resolution: one route for articles, categories and pages.
JSON-LD Structured Data: what the page graph contains and how to extend it.