Blog with Next.js
This example builds a blog on the Next.js App Router: a post model in Plenary, an index page at /blog, and a page per post at /blog/{slug} with title, date, cover image, and rich text body. Pages are generated at build time with generateStaticParams. To update them the moment an editor publishes, add Instant revalidation afterwards.
Prerequisites
Section titled “Prerequisites”- A Plenary instance, cloud or self-hosted, and a console account that can create models (the Admin role can).
- Node.js 20.9 or later.
- Next.js 16 (the steps use
create-next-app@latest). The code also runs on Next.js 15. @plenary/client1.0.x.
Create the post model
Section titled “Create the post model”The model has five fields. Every entry also has a built-in URL Slug, which the blog uses for its URLs, so you do not add a slug field.
| Field key | Name | Type | Settings |
|---|---|---|---|
title |
Title | Text | Required. Set as the model’s Title field. |
excerpt |
Excerpt | Text | Textarea control. |
cover |
Cover Image | Image | Two variants: card (800 wide, WebP) and hero (1600 wide, WebP). |
body |
Body | Rich text | |
published_date |
Published Date | Date | Required. |
In the console: go to Content Management → Content, choose New model, set the key to post and the kind to collection, and add the fields above with Add field. Add the two image variants in the Cover Image field’s settings. Choose Save model. See Content models for the editor in detail.
Or as code: save this file and push it with the CLI. This needs a credential that may create models: npx plenary login, or a private API key with content:models:* grants in PLENARY_CLI_API_KEY. Keep it out of PLENARY_API_KEY, which holds the site’s public key.
key: postkind: collectionname_singular: Postname_plural: Postsdescription: Blog posts, listed at /blog and served at /blog/{slug}.title_field: titleis_active: truefields: - key: title name: Title type: text required: true - key: excerpt name: Excerpt type: text ui: control: textarea - key: cover name: Cover Image type: image settings: variants: - { key: card, width: 800, format: webp } - { key: hero, width: 1600, format: webp } - key: body name: Body type: rich_text - key: published_date name: Published Date type: date required: truenpm install --save-dev @plenary/cliPLENARY_BASE_URL=https://your-instance.plenarycms.io PLENARY_SITE_KEY=default npx plenary metadata pushThe file has no site_key, because the push applies it to the configured site. Replace default in PLENARY_SITE_KEY with your site key if it differs. See Models as code.
Write a few posts
Section titled “Write a few posts”In the console, go to Content Management → Content, choose Open entries on the Posts card, and add two or three posts. Give each a URL slug, a title, a published date, and some body text, and upload a cover image to at least one. Choose Save and Publish. A public API key only reads published entries, so drafts will not appear on the site.
Create a public API key
Section titled “Create a public API key”Go to Access Management → API Keys, create a key of type Public, and select your site under Site. Copy the pln_pub_… value. A public key reads published content only and is safe to use in a website. See API keys.
Create the Next.js app
Section titled “Create the Next.js app”npx create-next-app@latest my-blog --ts --app --no-tailwind --no-src-dir --import-alias "@/*" --use-npm --no-cache-components --yescd my-blognpm install @plenary/client--no-cache-components keeps Next.js’s default caching model, which this example and @plenary/next are written for. If your project already has cacheComponents: true in next.config.ts, see Cache Components at the end.
Create .env.local in the project root:
PLENARY_BASE_URL=https://your-instance.plenarycms.ioPLENARY_API_KEY=pln_pub_your_public_keyPLENARY_SITE_KEY=defaultPLENARY_LOCALE=en-us| Variable | Value |
|---|---|
PLENARY_BASE_URL |
Your instance’s origin, without /api/v1. The console is at this origin plus /cms. |
PLENARY_API_KEY |
The public key you created. |
PLENARY_SITE_KEY |
Your site key, shown under Admin Settings → Site Management. |
PLENARY_LOCALE |
The locale your posts are written in, lowercase. New sites default to en-us. |
None of these use the NEXT_PUBLIC_ prefix, so they stay on the server. All data fetching in this example happens in server components.
The Plenary client
Section titled “The Plenary client”One shared client, the type of a post’s data, and two small helpers.
import { createClient } from "@plenary/client";
const baseUrl = process.env.PLENARY_BASE_URL;const apiKey = process.env.PLENARY_API_KEY;if (!baseUrl || !apiKey) { throw new Error("Set PLENARY_BASE_URL and PLENARY_API_KEY in .env.local");}
export const plenary = createClient({ baseUrl, apiKey, siteKey: process.env.PLENARY_SITE_KEY ?? "default", locale: process.env.PLENARY_LOCALE ?? "en-us",});
/** The stored value of an `image` field, as the Content API returns it. */export interface ImageValue { media_id: string; alt?: string; caption?: string; /** One entry per variant declared on the field, keyed by variant key. */ variants?: Record<string, { url: string }>; /** True when the media asset behind this value was deleted. */ missing?: boolean;}
/** The `data` of a `post` entry. */export interface PostData { title: string; excerpt?: string; cover?: ImageValue; body?: string; published_date: string;}
/** Media URLs are paths on the Plenary instance; make them absolute. */export function mediaUrl(path: string | undefined): string | undefined { return path ? new URL(path, baseUrl).toString() : undefined;}
/** A `date` field is a bare YYYY-MM-DD; format it in UTC so it never shifts a day. */export function formatDate(date: string): string { return new Date(`${date}T00:00:00Z`).toLocaleDateString("en-US", { year: "numeric", month: "long", day: "numeric", timeZone: "UTC", });}The PostData interface mirrors the model’s fields. The SDK does not generate types; keep this interface in step with the model.
The index page
Section titled “The index page”The index lists posts newest first. It leaves out data.body, which the index does not show, to keep the response small.
import Link from "next/link";import type { Metadata } from "next";import { plenary, mediaUrl, formatDate, type PostData } from "@/lib/plenary";
export const metadata: Metadata = { title: "Blog" };
export default async function BlogIndex() { const { items } = await plenary.listEntries<PostData>("post", { sort: { "data.published_date": "desc" }, exclude: ["data.body"], limit: 50, });
return ( <main> <h1>Blog</h1> {items.map((post) => { const cover = post.data.cover; const src = cover && !cover.missing ? mediaUrl(cover.variants?.card?.url) : undefined; return ( <article key={post.id} style={{ marginBottom: 40 }}> {src && <img src={src} alt={cover?.alt ?? ""} width={800} style={{ width: "100%", height: "auto" }} />} <h2> <Link href={`/blog/${post.slug}`}>{post.data.title}</Link> </h2> <p> <time dateTime={post.data.published_date}>{formatDate(post.data.published_date)}</time> </p> {post.data.excerpt && <p>{post.data.excerpt}</p>} </article> ); })} </main> );}listEntries returns at most 50 posts here. For more, paginate with limit, offset, and count: true; see Pagination.
The post page
Section titled “The post page”The post page pre-renders every published slug at build time, generates the page title and description from the entry, and returns a 404 for an unknown slug.
import type { Metadata } from "next";import { notFound } from "next/navigation";import { PlenaryNotFoundError } from "@plenary/client";import { plenary, mediaUrl, formatDate, type PostData } from "@/lib/plenary";
type Props = { params: Promise<{ slug: string }> };
async function getPost(slug: string) { try { return await plenary.getEntry<PostData>("post", slug); } catch (err) { if (err instanceof PlenaryNotFoundError) notFound(); throw err; }}
export async function generateStaticParams() { const { items } = await plenary.listEntries<PostData>("post", { include: ["slug"], limit: 500, }); return items.flatMap((post) => (post.slug ? [{ slug: post.slug }] : []));}
export async function generateMetadata({ params }: Props): Promise<Metadata> { const { slug } = await params; const post = await getPost(slug); const image = mediaUrl(post.data.cover?.variants?.hero?.url); return { title: post.data.title, description: post.data.excerpt, openGraph: image ? { images: [image] } : undefined, };}
export default async function PostPage({ params }: Props) { const { slug } = await params; const post = await getPost(slug); const { title, cover, body, published_date } = post.data; const src = cover && !cover.missing ? mediaUrl(cover.variants?.hero?.url) : undefined;
return ( <main> <article> <h1>{title}</h1> <p> <time dateTime={published_date}>{formatDate(published_date)}</time> </p> {src && ( <figure> <img src={src} alt={cover?.alt ?? ""} width={1600} style={{ width: "100%", height: "auto" }} /> {cover?.caption && <figcaption>{cover.caption}</figcaption>} </figure> )} {body && <div dangerouslySetInnerHTML={{ __html: body }} />} </article> </main> );}generateStaticParams asks only for slug with include, so the build does not download every post body twice. A slug published after the build still works: Next.js renders it on first request.
Run it
Section titled “Run it”npm run devOpen http://localhost:3000/blog. Then build for production:
npm run buildThe build output lists /blog as static and each post under /blog/[slug] as prerendered with generateStaticParams:
Route (app)┌ ○ /├ ○ /_not-found├ ○ /blog└ /blog/[slug] ├ ● /blog/getting-started ├ ● /blog/second-post └ ● /blog/hello-plenaryThe build calls your Plenary instance, so the environment variables must be set wherever you build (for example in your hosting provider’s project settings).
How the content maps to the page
Section titled “How the content maps to the page”Slug and URL. post.slug is the entry’s built-in URL slug, which editors set in the entry editor. The route /blog/[slug] passes it to getEntry("post", slug), which matches it in the client’s locale.
Rich text. The console’s rich text editor stores HTML, so data.body is an HTML string such as <p>Welcome to the <strong>new blog</strong>.</p>. The page renders it with dangerouslySetInnerHTML. Plenary does not sanitize it on save; it is as trustworthy as the people who can edit posts. If untrusted users can edit content, sanitize the HTML before rendering (for example with sanitize-html).
Images. An image field’s value carries a variants map with one URL per variant declared on the field:
"cover": { "media_id": "ce221afb-0ef2-4fc6-94d6-8c3da0cc391e", "alt": "A blue gradient", "variants": { "card": { "url": "/media/ce221afb-0ef2-4fc6-94d6-8c3da0cc391e/8f3a10a3c8b42f06.webp" }, "hero": { "url": "/media/ce221afb-0ef2-4fc6-94d6-8c3da0cc391e/87bc3720185cb993.webp" } }}The URLs are paths on your instance, so mediaUrl prefixes them with PLENARY_BASE_URL. Variants are generated in the background after an editor saves, so a URL can fail for a few seconds after a new image is added. The example uses a plain <img>; the variants are already resized and in WebP. To use next/image instead, add your instance’s host to images.remotePatterns in next.config.ts.
Dates. A date field is a bare YYYY-MM-DD string with no time zone. formatDate formats it in UTC so it shows the same day everywhere.
Keep pages up to date
Section titled “Keep pages up to date”These pages are static: an edit in Plenary does not show until the next build. Two ways to fix that:
- On demand (recommended): add a webhook that calls a revalidation route whenever a post changes. See Instant revalidation; it adds one file to this project.
- On a timer: add
export const revalidate = 300;to both page files to re-render at most every five minutes.
Cache Components
Section titled “Cache Components”create-next-app 16.4 and later turns on Cache Components (cacheComponents: true in next.config.ts) unless you pass --no-cache-components. With it on, the pages above fail the build with a “blocking prerender” error, because uncached fetches must be inside <Suspense> or a "use cache" function.
To keep Cache Components, move the reads into cached functions and call those from the pages instead of calling plenary directly:
import { cacheLife, cacheTag } from "next/cache";import { modelTag, modelEntriesTag, entryTag } from "@plenary/next";import { plenary, type PostData } from "@/lib/plenary";
export async function listPosts() { "use cache"; cacheLife("max"); cacheTag(modelTag("post")); const { items } = await plenary.listEntries<PostData>("post", { sort: { "data.published_date": "desc" }, exclude: ["data.body"], limit: 50, }); return items;}
/** Returns null when no published post has this slug. */export async function findPost(slug: string) { "use cache"; cacheLife("max"); cacheTag(modelEntriesTag("post"), entryTag(slug)); try { return await plenary.getEntry<PostData>("post", slug); } catch { return null; }}This needs npm install @plenary/next for the tag helpers. In the pages, replace the listEntries call with await listPosts() and getPost(slug) with await findPost(slug) followed by if (!post) notFound();. The tags match the ones @plenary/next revalidates, so a webhook with tags: true refreshes these functions.
Related
Section titled “Related”- Instant revalidation: refresh these pages from a webhook.
- @plenary/client: every method and option used here.
- Content API: filtering, sorting, and pagination.
- Field types: value shapes for other field types.