The Next.js block that renders this blog
Build a Next.js blog on a headless CMS with one block: a server loader, the delivery API and custom sorting. The same block runs our blog.
The grid of posts you clicked through to get here, at cmssy.com/blog, is one block. It is called blog-posts, it lives in the repo of our Next.js marketing site, and this article showed up in it when we published a page under /blog. Nobody touched the code to add it. This tutorial builds the same block for your Next.js blog on a headless CMS.
The real block, as our CMS sees it
Our marketing site's repo is private, so we can't paste its components. We can show you what the CMS knows about the block, because that comes from our own workspace. Here is the blog-posts schema as list_block_types returns it for the cmssy.com workspace (trimmed to the field types):
{
"type": "blog-posts",
"category": "Blog",
"schema": {
"badge": { "type": "text" },
"heading": { "type": "text" },
"description": { "type": "textarea" },
"parentPage": { "type": "pageSelector", "multiple": false },
"postsPerPage": { "type": "select", "options": ["3", "6", "9", "12"] },
"sortPageType": { "type": "text" },
"sortField": { "type": "text" },
"showSearch": { "type": "boolean" },
"layout": { "type": "select", "options": ["grid", "list"], "tab": "style" },
"columns": { "type": "select", "options": ["2", "3"], "tab": "style" },
"searchPlaceholder":{ "type": "text" },
"loadingText": { "type": "text" },
"noResultsText": { "type": "text" }
}
}
And the values our /blog page stores in it: parentPage is /blog, postsPerPage is "9", sortPageType is post, sortField is publish_date, search is on, the layout is a three-column grid. The text fields are filled in five languages, so the Polish blog index says "Szukaj postów..." without a second page.
Everything in that schema came from a defineBlock call in our repo. Editors never define block types in the admin; they fill in the fields the code declared.


The plan in four lines
- Our block is
blog-posts; the public copy you'll build from isblog-indexincmssy-io/examples/simple-blog. Same pattern, fewer options; we add custom sorting at the end. - A blog post is a page with a
postpage type, published as a child of/blog. - The listing is a block with a server
loader. The loader asks the delivery API for the children of a parent page, and the result arrives in the component asdata, already in the HTML. - Mount the block-data route, or the block freezes in the editor.
What you need to follow along
| Tool | Version | Source |
|---|---|---|
| Node.js | 22.13 or newer, below 23 | engines in examples/simple-blog/package.json |
| Next.js (App Router) | 16.3.1 | same file |
| React | 19.2.8 | same file |
@cmssy/react, @cmssy/next, @cmssy/core |
19.33 or newer (19.36.1 current) | same file; cmssy-sdk/packages/*/package.json |
| pnpm | 11.1.2, or npm | packageManager in the same file |
git clone https://github.com/cmssy-io/examples
cd examples/simple-blog
pnpm install
cp .env.example .env.local
pnpm dev
That renders the public demo workspace at http://localhost:3000/blog with no account.
1. Model posts as pages
There is no separate "posts" collection. Each post is a page:
- In the admin, create a page type called
postwith the custom fields your cards need. Ours hascover_image(media),authorandpublish_date. - Create a page at
/blog. That's the parent. - Create each post as a child page of
/blogwith theposttype, and publish it.
Our posts are built from two blocks of their own, a blog-post-hero and a docs-article. A post can use any blocks you register; those two are just ours.
2. Write the query
The SDK client is a GraphQL client, not a wrapper with a method per resource, so the query is yours. Published pages are under public.page.byType. This is posts-query.ts from the example:
// blocks/blog-index/posts-query.ts
// The delivery API exposes published pages under `public.page.byType`.
// `queryScoped` injects `$workspaceId` for you (see load-posts.ts).
export const PUBLIC_PAGES_BY_TYPE = `query PublicPagesByType(
$workspaceId: String!
$parentSlug: String
$limit: Int
$offset: Int
) {
public {
page {
byType(
workspaceId: $workspaceId
parentSlug: $parentSlug
limit: $limit
offset: $offset
) {
items {
id
slug
fullSlug
publishedAt
displayName
seoTitle
seoDescription
}
hasMore
}
}
}
}`;
Translatable fields such as displayName come back keyed by language ({ "en": "...", "pl": "..." }). The component picks one; the query doesn't.
3. Keep the fetch on the server
load-posts.ts creates the client and runs the query. It is only ever imported dynamically from inside the loader, so neither this module nor the GraphQL client lands in the browser bundle. The window check makes a mistake loud instead of silent:
// blocks/blog-index/load-posts.ts
import { createCmssyClient } from "@cmssy/react";
import { cmssy } from "@/cmssy.config";
import { retryMode } from "@/lib/retry-mode";
import { PUBLIC_PAGES_BY_TYPE } from "./posts-query";
const client = createCmssyClient(cmssy);
export type Localized = string | Record<string, string> | null | undefined;
export type Post = {
id: string;
slug: string;
fullSlug: string;
publishedAt?: string | null;
displayName?: Localized;
seoTitle?: Localized;
seoDescription?: Localized;
};
export type PostsResult = { items: Post[]; hasMore: boolean };
export async function loadPosts(vars: {
parentSlug: string;
limit: number;
}): Promise<PostsResult | null> {
if (typeof window !== "undefined") {
throw new Error("loadPosts is server-only");
}
const data = await client.queryScoped<{
public?: {
page?: { byType?: { items?: Post[]; hasMore?: boolean } | null } | null;
} | null;
}>(PUBLIC_PAGES_BY_TYPE, { ...vars, offset: 0 }, { retry: retryMode() });
const r = data?.public?.page?.byType;
return r ? { items: r.items ?? [], hasMore: !!r.hasMore } : null;
}
queryScoped resolves the workspace id from your config and injects $workspaceId, so you never hardcode it.
4. Define the block with a loader
The loader runs during server rendering. Whatever it returns becomes the component's data prop, so the first page of posts is in the HTML the crawler sees, not fetched after hydration:
// blocks/blog-index/block.ts
import { defineBlock } from "@cmssy/react";
import BlogIndex, { blogIndexProps } from "./BlogIndex";
export const blogIndexBlock = defineBlock({
type: "blog-index",
label: "Blog index",
component: BlogIndex,
props: blogIndexProps,
loader: async ({ content }) => {
const parentSlug = content.parentPage?.slug;
if (!parentSlug) return null;
const { loadPosts } = await import("./load-posts");
return loadPosts({
parentSlug,
limit: content.postsPerPage ?? 9,
});
},
});
The return value crosses from server to client, so keep it to plain objects, arrays and primitives.
5. Render the grid
The schema has two fields. parentPage is a page picker, and it is marked localized: false because a parent page has no language; Cmssy stores it once instead of once per locale. The component has no "use client", so in the App Router it stays a Server Component:
// blocks/blog-index/BlogIndex.tsx
import { LocaleLink } from "@/components/locale-link";
import { fields, type BlockProps, type CmssyBlockContext } from "@cmssy/react";
import type { Localized, Post, PostsResult } from "./load-posts";
import styles from "./BlogIndex.module.css";
export const blogIndexProps = {
parentPage: fields.pageSelector({
label: "Parent page",
multiple: false,
helperText: "Posts are the children of this page.",
localized: false,
}),
postsPerPage: fields.number({ label: "Posts per page", defaultValue: 9 }),
};
function pickLocale(
value: Localized,
locale?: CmssyBlockContext["locale"],
): string {
if (!value) return "";
if (typeof value === "string") return value;
if (!locale) return "";
return value[locale.current] ?? value[locale.default] ?? "";
}
export default function BlogIndex({
data,
context,
}: BlockProps<typeof blogIndexProps, PostsResult | null>) {
const items = data?.items ?? [];
const locale = context?.locale;
if (items.length === 0) {
return <div className={styles.empty}>No posts yet.</div>;
}
return (
<div className={styles.grid}>
{items.map((post: Post) => {
const title =
pickLocale(post.displayName, locale) ||
pickLocale(post.seoTitle, locale) ||
post.slug;
const excerpt = pickLocale(post.seoDescription, locale);
return (
<LocaleLink
key={post.id}
locale={locale}
href={`/${post.fullSlug.replace(/^\/+/, "")}`}
className={styles.card}
>
{post.publishedAt && (
<time dateTime={post.publishedAt} className={styles.date}>
{new Date(post.publishedAt).toLocaleDateString()}
</time>
)}
<h3 className={styles.title}>{title}</h3>
{excerpt && <p className={styles.excerpt}>{excerpt}</p>}
</LocaleLink>
);
})}
</div>
);
}
LocaleLink is a small helper in the example that turns /blog/my-post into /pl/blog/my-post for a Polish reader. The SDK stores canonical slugs; prefixing them per language is your app's job.
6. Mount the block-data route
Skip this route and the block freezes in the editor while you configure it. A loader never runs in the browser, so when an editor changes "Posts per page" in the side panel, the editor asks your app to run the loader again through one route:
// app/api/cmssy/block-data/route.ts
import { createCmssyBlockDataRoute } from "@cmssy/next/server";
import { cmssy } from "@/cmssy.config";
import { blocks } from "@/cmssy/blocks";
export const POST = createCmssyBlockDataRoute(cmssy, blocks);
Without it, a block that fetches stays frozen while you configure it, and a freshly added one has no data until the page is saved and the frame reloads. The route only answers requests that carry an edit token minted from your draft secret for that exact page.
7. Register the block and run it
// cmssy/blocks.ts
import { proseBlock } from "@/blocks/prose/block";
import { blogIndexBlock } from "@/blocks/blog-index/block";
export const blocks = [proseBlock, blogIndexBlock];
Point the app at your own workspace with npx @cmssy/cli@latest link --token cs_..., run pnpm dev, open your /blog page in the editor, add "Blog index", and pick /blog as the parent. Your published posts render in the frame.
8. Sort by your own date and add "Load more"
The example sorts by publishedAt, newest first, which is the API's default. Our block sorts by the publish_date custom field instead, because that's the date we print on the card and we want to control it. The same byType query takes a page type filter, a custom-field sort and an offset, and can return the custom fields themselves. The arguments are from the delivery schema (schema.graphql, PublicPageQueries.byType); the code in this step is ours, not in the example repo.
// blocks/blog-index/posts-query.ts, extended (ours)
export const SORTED_POSTS = `query SortedPosts(
$workspaceId: String!
$parentSlug: String
$pageType: String
$sortField: String!
$limit: Int
$offset: Int
) {
public {
page {
byType(
workspaceId: $workspaceId
parentSlug: $parentSlug
pageType: $pageType
customFieldSort: { fieldKey: $sortField, direction: desc }
limit: $limit
offset: $offset
) {
items { id slug fullSlug publishedAt displayName seoDescription customFields }
hasMore
}
}
}
}`;
customFields carries the cover image and author for each card. The API refuses an offset above 10,000.
Add a second helper next to loadPosts in load-posts.ts. It reuses the module's client and types:
// blocks/blog-index/load-posts.ts (ours): add the import at the top,
// next to PUBLIC_PAGES_BY_TYPE, and the function below loadPosts
import { PUBLIC_PAGES_BY_TYPE, SORTED_POSTS } from "./posts-query";
export async function loadSortedPosts(vars: {
parentSlug: string;
limit: number;
offset?: number;
}): Promise<PostsResult | null> {
if (typeof window !== "undefined") {
throw new Error("loadSortedPosts is server-only");
}
const data = await client.queryScoped<{
public?: {
page?: { byType?: { items?: Post[]; hasMore?: boolean } | null } | null;
} | null;
}>(
SORTED_POSTS,
{
parentSlug: vars.parentSlug,
pageType: "post",
sortField: "publish_date",
limit: vars.limit,
offset: vars.offset ?? 0,
},
{ retry: retryMode() },
);
const r = data?.public?.page?.byType;
return r ? { items: r.items ?? [], hasMore: !!r.hasMore } : null;
}
Point the block's loader at loadSortedPosts for page one. For "Load more", put the same helper behind a route handler, so the browser talks only to your app and never to the delivery API with your credentials:
// app/api/posts/route.ts (ours)
import { loadSortedPosts } from "@/blocks/blog-index/load-posts";
export async function GET(request: Request) {
const url = new URL(request.url);
const parentSlug = url.searchParams.get("parent");
if (!parentSlug) {
return Response.json({ error: "parent is required" }, { status: 400 });
}
const limit = Math.min(Number(url.searchParams.get("limit")) || 9, 24);
const offset = Math.max(Number(url.searchParams.get("offset")) || 0, 0);
const result = await loadSortedPosts({ parentSlug, limit, offset });
return Response.json(result ?? { items: [], hasMore: false });
}
The first page still comes from the loader in the HTML; the route only serves page two onward. A small client component with a button that calls /api/posts?parent=/blog&offset=9 and appends the cards finishes it.
9. Publish a post and watch it appear
Create a child page of /blog with the post type, fill in its fields and publish it. The new card shows on the next visit if your app expires its cache on publish, which the landing page tutorial sets up in one route and one webhook.
What it can't do (yet)
- Cmssy doesn't render the blog. Your app renders every card; Cmssy returns pages and fields over the API.
- No search in this version. Our live block has a search box; the delivery query takes a
searchargument too, but we haven't documented what it matches, so this tutorial leaves it out. - No RSS or sitemap out of the box. The example builds
sitemap.tsfrom published pages in your own code; an RSS route is yours to write the same way. - Editors can't add a field to the card. A new field on the card means a new field in the page type and a line in your component.
Where the code lives
- The full example:
simple-blogon GitHub. - Loaders, the block-data route and every field builder: Building blocks.
- Let an agent write and publish posts into this block: Connect Claude Code to your CMS.