Reference - This guide is a tutorial. For exhaustive, always-current signatures and field lists, see the auto-generated reference:

Prerequisites

  • A Next.js App Router project with the SDK client in lib/lynkow.ts (Add Lynkow to an Existing Project).

  • A few published articles and categories in your Lynkow site.

  • The @tailwindcss/typography plugin if you want the prose styling used below (optional).

The blog has three routes:

app/blog/page.tsx                    # Article list, paginated, filterable by tag
app/blog/[slug]/page.tsx             # One article
app/blog/category/[slug]/page.tsx    # One category and its articles
components/article-card.tsx
components/pagination.tsx

Article card

contents.list() and categories.getBySlug() both return ContentSummary items, so one card serves every list:

tsx
// components/article-card.tsx
import Link from 'next/link'
import type { ContentSummary } from 'lynkow'

export function ArticleCard({ article }: { article: ContentSummary }) {
  // `card` is a pre-sized variant; it is absent when the article has no featured image
  const image = article.featuredImageVariants?.card ?? article.featuredImage

  return (
    <article>
      {image && (
        <img src={image} alt={article.featuredImageAlt ?? article.title} loading="lazy" />
      )}
      <time dateTime={article.publishedAt}>
        {new Date(article.publishedAt).toLocaleDateString('en-US', { dateStyle: 'long' })}
      </time>
      <h2>
        <Link href={`/blog/${article.slug}`}>{article.title}</Link>
      </h2>
      {article.excerpt && <p>{article.excerpt}</p>}
    </article>
  )
}

Image variants, srcset and transformations are covered in Media & Image Optimization.

Pagination

A list response carries meta.currentPage and meta.lastPage. The component only needs those two:

tsx
// components/pagination.tsx
import Link from 'next/link'

export function Pagination({
  currentPage,
  lastPage,
  basePath,
}: {
  currentPage: number
  lastPage: number
  basePath: string
}) {
  if (lastPage <= 1) return null

  return (
    <nav aria-label="Pagination">
      {currentPage > 1 && <Link href={`${basePath}?page=${currentPage - 1}`}>Previous</Link>}
      <span>
        Page {currentPage} of {lastPage}
      </span>
      {currentPage < lastPage && <Link href={`${basePath}?page=${currentPage + 1}`}>Next</Link>}
    </nav>
  )
}

Article list

tsx
// app/blog/page.tsx
import type { Metadata } from 'next'
import { lynkow } from '@/lib/lynkow'
import { ArticleCard } from '@/components/article-card'
import { Pagination } from '@/components/pagination'

export const metadata: Metadata = { title: 'Blog' }

export default async function BlogPage({
  searchParams,
}: {
  searchParams: Promise<{ page?: string; tag?: string }>
}) {
  const { page, tag } = await searchParams

  const { data: articles, meta } = await lynkow.contents.list({
    page: Number(page) || 1,
    limit: 10,
    sort: 'published_at',
    order: 'desc',
    tag, // a tag slug, or undefined for every article
  })

  return (
    <main>
      <h1>Blog</h1>
      {articles.length === 0 && <p>No articles found.</p>}
      {articles.map((article) => (
        <ArticleCard key={article.id} article={article} />
      ))}
      <Pagination currentPage={meta.currentPage} lastPage={meta.lastPage} basePath="/blog" />
    </main>
  )
}

limit accepts up to 100. tag and category filter by slug, so /blog?tag=tutorials lists the articles tagged tutorials. To build a tag menu, list the tags:

tsx
const { data: tags } = await lynkow.tags.list()

tags.map((tag) => (
  <Link key={tag.id} href={`/blog?tag=${tag.slug}`}>
    {tag.name}
  </Link>
))

Article page

contents.getBySlug() returns the article itself, without a data wrapper, and throws a LynkowError with code NOT_FOUND when no published article has that slug. The getArticle() helper turns that error into null and rethrows every other error. generateMetadata and the page both call it.

tsx
// app/blog/[slug]/page.tsx
import type { Metadata } from 'next'
import Link from 'next/link'
import { notFound } from 'next/navigation'
import { isLynkowError, renderJsonLdGraph } from 'lynkow'
import { lynkow } from '@/lib/lynkow'

type Params = Promise<{ slug: string }>

async function getArticle(slug: string) {
  try {
    return await lynkow.contents.getBySlug(slug)
  } catch (error) {
    if (isLynkowError(error) && error.code === 'NOT_FOUND') return null
    throw error
  }
}

// Pre-render every published article at build time
export async function generateStaticParams() {
  const { paths } = await lynkow.paths.list()

  return paths
    .filter((p) => p.type === 'content')
    // A content path ends with the article slug, whatever the blog URL mode
    .map((p) => ({ slug: p.path.split('/').filter(Boolean).pop()! }))
}

export async function generateMetadata({ params }: { params: Params }): Promise<Metadata> {
  const article = await getArticle((await params).slug)
  if (!article) return { title: 'Article not found' }

  const description = article.metaDescription ?? article.excerpt ?? undefined
  const image = article.ogImage ?? article.featuredImage

  return {
    title: article.metaTitle ?? article.title,
    description,
    openGraph: {
      type: 'article',
      publishedTime: article.publishedAt,
      authors: article.author ? [article.author.fullName] : undefined,
      images: image ? [{ url: image }] : undefined,
    },
  }
}

export default async function ArticlePage({ params }: { params: Params }) {
  const article = await getArticle((await params).slug)
  if (!article) notFound()

  // The Article node and, when FAQ items are enabled, the FAQPage node
  const jsonLd = [article.structuredData?.article?.jsonLd, article.structuredData?.faq?.jsonLd]
    .filter((node): node is object => node != null)

  return (
    <main>
      {/* One escaped <script type="application/ld+json"> tag, or nothing */}
      <div dangerouslySetInnerHTML={{ __html: renderJsonLdGraph(jsonLd) }} />

      <article>
        {article.categories.map((category) => (
          <Link key={category.id} href={`/blog/category/${category.slug}`}>
            {category.name}
          </Link>
        ))}

        <h1>{article.title}</h1>
        {article.author && <p>By {article.author.fullName}</p>}

        {/* `body` is rendered HTML */}
        <div className="prose" dangerouslySetInnerHTML={{ __html: article.body }} />

        {article.tags.map((tag) => (
          <Link key={tag.id} href={`/blog?tag=${tag.slug}`}>
            {tag.name}
          </Link>
        ))}
      </article>
    </main>
  )
}
  • Use renderJsonLdGraph() to emit JSON-LD: it escapes the characters that would let a value typed in the CMS close the <script> tag. A plain JSON.stringify() does not.

  • The structuredData of getBySlug() holds the article's own nodes. The full graph, with your site and category nodes, comes from paths.resolve(): see JSON-LD Structured Data.

  • Canonical URLs, Twitter cards and robots flags are covered in SEO & Analytics.

Category page

categories.getBySlug() returns the category and one page of its published articles, as { category, contents: { data, meta } }:

tsx
// app/blog/category/[slug]/page.tsx
import type { Metadata } from 'next'
import { notFound } from 'next/navigation'
import { isLynkowError } from 'lynkow'
import { lynkow } from '@/lib/lynkow'
import { ArticleCard } from '@/components/article-card'
import { Pagination } from '@/components/pagination'

type Params = Promise<{ slug: string }>

async function getCategory(slug: string, page = 1) {
  try {
    return await lynkow.categories.getBySlug(slug, { page, limit: 10 })
  } catch (error) {
    if (isLynkowError(error) && error.code === 'NOT_FOUND') return null
    throw error
  }
}

export async function generateStaticParams() {
  const { categories } = await lynkow.categories.list()
  return categories.map((category) => ({ slug: category.slug }))
}

export async function generateMetadata({ params }: { params: Params }): Promise<Metadata> {
  const result = await getCategory((await params).slug)
  if (!result) return { title: 'Category not found' }

  return {
    title: result.category.name,
    description: result.category.description ?? undefined,
  }
}

export default async function CategoryPage({
  params,
  searchParams,
}: {
  params: Params
  searchParams: Promise<{ page?: string }>
}) {
  const { slug } = await params
  const result = await getCategory(slug, Number((await searchParams).page) || 1)
  if (!result) notFound()

  const { category, contents } = result

  return (
    <main>
      <h1>{category.name}</h1>
      {category.description && <p>{category.description}</p>}
      {contents.data.map((article) => (
        <ArticleCard key={article.id} article={article} />
      ))}
      <Pagination
        currentPage={contents.meta.currentPage}
        lastPage={contents.meta.lastPage}
        basePath={`/blog/category/${slug}`}
      />
    </main>
  )
}

Category menu

categories.list() returns every category with its contentCount:

tsx
// components/category-nav.tsx
import Link from 'next/link'
import { lynkow } from '@/lib/lynkow'

export async function CategoryNav() {
  const { categories } = await lynkow.categories.list()

  return (
    <ul>
      {categories.map((category) => (
        <li key={category.id}>
          <Link href={`/blog/category/${category.slug}`}>
            {category.name} ({category.contentCount})
          </Link>
        </li>
      ))}
    </ul>
  )
}

For nested categories, categories.tree() returns { tree }: the same items, each with a children array.

Freshness

The client of Add Lynkow to an Existing Project sets revalidate: 60 on every request, so a published article appears within a minute. Override it per route with export const revalidate = 30. To update the moment an editor publishes, add a webhook that revalidates the blog routes: see Webhooks & Cache Revalidation.

Next Steps