Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
107 changes: 99 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,10 +1,101 @@
# cms-contentful

[Vercel's Next.js Blog with Draft Mode (Contentful)](https://github.com/vercel/next.js/tree/canary/examples/cms-contentful) on
**Cloudflare Workers**, deployed by [Orun](https://github.com/sourceplane/orun) to stage
and prod on every merge, and then packaged as an Orun baseline.

This commit is the repository's frame: `intent.yaml` (with the placeholder
workspace `ws_CHANGE_ME`, so CI plans nothing until it is linked), the Orun
CI workflow, the shared TypeScript and ESLint configuration, and the spec
index. The work is tracked as an epic under [`specs/epics`](specs/epics/README.md).
Vercel's [Next.js Blog with Draft Mode (Contentful)](https://github.com/vercel/next.js/tree/canary/examples/cms-contentful)
— posts and authors in a Contentful space read over its GraphQL Content
API, the post body rich text rendered with Contentful's renderer, draft mode
that previews unpublished posts through the Content Preview API, and the
setup script that imports the content model — running on **Cloudflare
Workers + Static Assets** through
[`@opennextjs/cloudflare`](https://opennext.js.org/cloudflare), deployed by
[Orun](https://github.com/sourceplane/orun) to stage and prod on every merge.
Packaging it as an Orun baseline is the next milestone (CC2).
It goes live before its owner has a Contentful space at all.

The template's code is the code and Contentful stays the SaaS it is. What
the port adds is the Workers build, the monorepo wrapper, a test package and
the deploy contract; what it changes is what Workers force: the blog renders
on request against Contentful's API CDN instead of statically generating
its pages and revalidating them by tag, and the draft route checks its
preview secret itself instead of through Vercel's deployment-protection
bypass. What
makes it deployable with no Contentful space is the port's: an unconnected
build renders bundled sample posts under a visible "connect your Contentful
space" notice instead of failing. See [`specs/epics/cms-contentful`](specs/epics/cms-contentful/README.md)
for the design, the milestones and the as-built status.

## What is here (the site)

| Surface | Where |
|---|---|
| Home, `/posts/[slug]`, the unconnected notice | `apps/web/app` |
| Draft mode on (`/api/draft`) and off (`/api/disable-draft`), the revalidation webhook (`/api/revalidate`) | `apps/web/app/api` |
| The GraphQL reads, with the sample-mode fallback | `apps/web/lib/api.ts` |
| The rich-text renderer and the image loader | `apps/web/lib/markdown.tsx`, `apps/web/lib/contentful-image.tsx` |
| The sample posts an unconnected blog renders | `apps/web/lib/sample.ts`, `apps/web/public/sample` |
| The content model and its import (`pnpm run setup`) | `apps/web/lib/export.json`, `apps/web/lib/setup.js` |
| The blog's name (the rename's seam) | `apps/web/app/site.ts` |
| Workers build and deploy contract | `apps/web/next.config.ts`, `open-next.config.ts`, `wrangler.jsonc`, `component.yaml` |
| Tests | `tests/web` (vitest) |

## Getting started

```bash
pnpm install
pnpm typecheck
pnpm lint
pnpm test
pnpm build # next build + opennextjs-cloudflare build → apps/web/.open-next
pnpm --filter @app/web preview # wrangler dev over the built Worker: the sample posts, unconnected
```

That much needs no Contentful space: the baseline's own e2e tier
(`testing/e2e.test.sh`) runs exactly this on each landing before a tag, and
a blog's developers run it before a push — a blog's pull request builds and
dry-deploys it, and does not lint or run the tests. To see your own content:

```bash
CONTENTFUL_SPACE_ID=<id> CONTENTFUL_MANAGEMENT_TOKEN=<CFPAT-…> pnpm --filter @app/web run setup # the Author and Post types
cd apps/web
cp .env.example .env.local # CONTENTFUL_SPACE_ID, CONTENTFUL_ACCESS_TOKEN, the draft-mode values
cd ../..
pnpm --filter @app/web dev # http://localhost:3000
```

For the Worker locally, the space id and its delivery token are read at
build time and the draft-mode values are Worker secrets:

```bash
cd apps/web
cp .dev.vars.example .dev.vars # CONTENTFUL_PREVIEW_ACCESS_TOKEN, CONTENTFUL_PREVIEW_SECRET
CONTENTFUL_SPACE_ID=<id> CONTENTFUL_ACCESS_TOKEN=<token> pnpm build
pnpm preview # wrangler dev over the built Worker
```

| Variable | Where it is read | What it does |
|---|---|---|
| `CONTENTFUL_SPACE_ID` | build time (`next build` inlines it into the server bundle, never the browser's) | The space. A deployed build takes it from its environment's `CONTENTFUL_SPACE_ID` secret, best-effort. Unset, the blog is unconnected: the sample posts under a notice, draft mode refused with 401. |
| `CONTENTFUL_ACCESS_TOKEN` | build time, likewise | The space's Content Delivery API token (`CONTENTFUL_ACCESS_TOKEN`); needed with the space id to connect. |
| `CONTENTFUL_PREVIEW_ACCESS_TOKEN` | request time, in the Worker | The Content Preview API token draft mode reads drafts with. A Worker secret in stage/prod, `.dev.vars` locally, `.env.local` for `next dev`. Optional: without it draft mode answers 401 with the reason. |
| `CONTENTFUL_PREVIEW_SECRET` | request time, in the Worker | The secret Contentful's preview URL carries to `/api/draft`. Optional, likewise. |
| `CONTENTFUL_REVALIDATE_SECRET` | request time, in the Worker | The `x-vercel-reval-key` header `/api/revalidate` checks. Optional. |
| `CONTENTFUL_MANAGEMENT_TOKEN` | `pnpm run setup` only | Imports the content model; never stored. |

## How it maps to Vercel

| Vercel | Here |
|---|---|
| Next.js hosting (static pages, ISR, route handlers) | One Cloudflare Worker (`.open-next/worker.js`) + Static Assets; `/` and `/posts/[slug]` render on every request (`force-dynamic`, no `generateStaticParams`) |
| Project env vars in the dashboard (or the Vercel Contentful integration) | Build time: the space id and delivery token from optional Orun secrets, inlined by `next build` into the server bundle. Run time: the preview token and the preview and revalidate secrets as Worker secrets |
| A missing env var fails every route (and the build) | An unconnected blog: sample posts and a notice — deployable before a Contentful space exists |
| `fetch` cached under the `posts` tag, revalidated by Contentful's webhook (`/api/revalidate`) | Every read `cache: "no-store"` against Contentful's API CDN; the webhook route kept, with nothing cached to refresh |
| Draft mode through `@contentful/vercel-nextjs-toolkit` (Vercel's protection-bypass token) | `/api/draft` checks `CONTENTFUL_PREVIEW_SECRET`, looks the post up through the Content Preview API, enables draft mode and redirects — the upstream README's preview URL, unchanged |
| `next/image` through Contentful's Images API (custom loader) | Unchanged: the template's loader sizes each image at Contentful (`images.loader: "custom"`); the Worker optimises nothing |
| `npm run setup` (contentful-import) | Unchanged, run by a person with a management token: `pnpm --filter @app/web run setup` |
| Deploy on push | Orun deploys `<repo>-web-{stage,prod}` on merge to `main` and smoke-tests it (`apps/web/component.yaml`) |
| "Deploy with Vercel" (clone the template) | `orun new --blueprint repo-blueprint.yaml` — a new repository, branded, deployed |

## CI

| Workflow | What it runs | Ships to a blog |
|---|---|---|
| `ci.yml` | the Orun pipeline, and the only workflow a blog carries: `orun plan --changed`, then one job per lane. A pull request runs the verify lanes (the blog built and dry-deployed per environment; they do not lint or run the tests), except the bootstrap's own landings (`orun/BASE-*`), where `plan` alone is the check; a merge deploys stage → prod. It plans nothing while `intent.yaml` names the placeholder workspace `ws_CHANGE_ME`, as this repository does. A manual run (Orunbase's Deploy button, or Run workflow on `main`) plans the environment and components it names under the push-to-main trigger, so they deploy as a merge deploys them | yes |
11 changes: 11 additions & 0 deletions apps/web/.dev.vars.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# Local Worker secrets for `wrangler dev` / `opennextjs-cloudflare preview`.
# Copy to .dev.vars (git-ignored). In stage/prod each is a Worker secret, set
# once per environment with
# wrangler secret put CONTENTFUL_PREVIEW_ACCESS_TOKEN --name cms-contentful-web-<env>
# (README → Connecting Contentful); the deploy lane never sets or clears them.
# The space id and the delivery token are not here: they are inlined at build
# time (see .env.example). All optional: without the preview token and the
# preview secret, draft mode is refused with a 401.
CONTENTFUL_PREVIEW_ACCESS_TOKEN=
CONTENTFUL_PREVIEW_SECRET=
CONTENTFUL_REVALIDATE_SECRET=
14 changes: 14 additions & 0 deletions apps/web/.env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# https://github.com/vercel/next.js/tree/canary/examples/cms-contentful
# Copy to .env.local (git-ignored) for `next dev`. The space id and its
# Content Delivery API token are read at BUILD time and inlined into the
# server bundle (next.config.ts): a deployed build takes them from its
# environment's CONTENTFUL_SPACE_ID and CONTENTFUL_ACCESS_TOKEN Orun secrets
# (README → Connecting Contentful). Unset, the blog is unconnected: it renders
# its bundled sample posts under a "connect your Contentful space" notice.
CONTENTFUL_SPACE_ID=
CONTENTFUL_ACCESS_TOKEN=
# Draft mode and the revalidate webhook read these at request time: here for
# `next dev`; on stage and prod they are Worker secrets (see .dev.vars.example).
CONTENTFUL_PREVIEW_ACCESS_TOKEN=
CONTENTFUL_PREVIEW_SECRET=
CONTENTFUL_REVALIDATE_SECRET=
30 changes: 30 additions & 0 deletions apps/web/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# apps/web — the blog

A blog whose content lives in Contentful, from Vercel's
[Next.js Blog with Draft Mode (Contentful)](https://github.com/vercel/next.js/tree/canary/examples/cms-contentful)
(MIT), running on Cloudflare Workers + Static Assets:

- Posts and authors in a Contentful space, read over its GraphQL Content API
(`lib/api.ts`), the post body a rich-text field rendered with
`@contentful/rich-text-react-renderer` (`lib/markdown.tsx`)
- Draft mode: Contentful's preview URL (`/api/draft?secret=…&slug=…`) turns
it on, and drafts come from the Content Preview API; `/api/disable-draft`
turns it off
- Every page rendered on request by the Worker, from Contentful's API CDN
- Tailwind 3, Inter, images from Contentful's Images API sized by the
browser's request (`lib/contentful-image.tsx`)

With no space id and delivery token at build time the blog is
**unconnected**: it renders the sample posts in `lib/sample.ts` under a
notice that says how to connect. The blog's name is in `app/site.ts`.

```bash
pnpm dev # next dev on http://localhost:3000
pnpm build # next build + opennextjs-cloudflare build → .open-next/
pnpm preview # wrangler dev over the built Worker
CONTENTFUL_SPACE_ID=<id> CONTENTFUL_MANAGEMENT_TOKEN=<token> pnpm run setup # import the Author and Post content types
```

How it is connected to a Contentful space and deployed — per environment, on
merge to `main` — is the repository's README and `component.yaml` beside
this file.
6 changes: 6 additions & 0 deletions apps/web/app/api/disable-draft/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { draftMode } from "next/headers";

export async function GET(request: Request) {
(await draftMode()).disable();
return new Response("Draft mode is disabled");
}
47 changes: 47 additions & 0 deletions apps/web/app/api/draft/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { draftMode } from "next/headers";
import { redirect } from "next/navigation";

import { getPreviewPostBySlug, isContentfulConfigured, previewToken } from "@/lib/api";

/**
* Contentful's preview URL: /api/draft?secret=<CONTENTFUL_PREVIEW_SECRET>&slug=<slug>.
*
* Upstream re-exported @contentful/vercel-nextjs-toolkit's handler, which
* authorises the request with Vercel's deployment-protection bypass token — a
* Vercel feature with no Cloudflare equivalent. This is the check it stands
* for, written out: the preview secret (a Worker secret), then the post looked
* up through the Content Preview API, then draft mode and a redirect to it.
* Without a space, a preview token or a secret the request cannot be
* authorised, and it is refused with the reason (401), not a 500.
*/
export async function GET(request: Request) {
const { searchParams } = new URL(request.url);
const secret = searchParams.get("secret");
const slug = searchParams.get("slug");

if (!isContentfulConfigured()) {
return new Response("Draft mode is unavailable: this blog is not connected to a Contentful space yet.", {
status: 401,
});
}
const expected = process.env.CONTENTFUL_PREVIEW_SECRET?.trim();
if (!expected || !previewToken()) {
return new Response(
"Draft mode is unavailable: set the CONTENTFUL_PREVIEW_ACCESS_TOKEN and CONTENTFUL_PREVIEW_SECRET Worker secrets to preview drafts.",
{ status: 401 },
);
}
if (secret !== expected) {
return new Response("Invalid secret", { status: 401 });
}
if (!slug) {
return new Response("Missing slug", { status: 400 });
}
const post = await getPreviewPostBySlug(slug);
if (!post) {
return new Response("Invalid slug", { status: 401 });
}

(await draftMode()).enable();
redirect(`/posts/${post.slug}`);
}
21 changes: 21 additions & 0 deletions apps/web/app/api/revalidate/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { NextRequest, NextResponse } from "next/server";
import { revalidateTag } from "next/cache";

// Contentful's publish webhook, as upstream (the `x-vercel-reval-key` header
// carries CONTENTFUL_REVALIDATE_SECRET, a Worker secret). On Workers every
// page renders per request, so there is no cached page for the tag to
// refresh: the route still checks the secret and answers as upstream does,
// and a webhook pointed at it does no harm.

export async function POST(request: NextRequest) {
const requestHeaders = new Headers(request.headers);
const secret = requestHeaders.get("x-vercel-reval-key");

if (secret !== process.env.CONTENTFUL_REVALIDATE_SECRET) {
return NextResponse.json({ message: "Invalid secret" }, { status: 401 });
}

revalidateTag("posts", "max");

return NextResponse.json({ revalidated: true, now: Date.now() });
}
24 changes: 24 additions & 0 deletions apps/web/app/avatar.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import ContentfulImage from "@/lib/contentful-image";

export default function Avatar({
name,
picture,
}: {
name: string;
picture: any;
}) {
return (
<div className="flex items-center">
<div className="mr-4 w-12 h-12">
<ContentfulImage
alt={name}
className="object-cover h-full rounded-full"
height={48}
width={48}
src={picture.url}
/>
</div>
<div className="text-xl font-bold">{name}</div>
</div>
);
}
24 changes: 24 additions & 0 deletions apps/web/app/connect-contentful.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import Link from "next/link";

/**
* Shown above every page while the build has no Contentful space: the posts
* below it are the bundled samples (lib/sample.ts), and this says so, and where
* the steps to connect a space are. Gone once one is set.
*/
export default function ConnectContentfulNotice() {
return (
<div
role="status"
data-contentful-notice="unconnected"
className="border-b border-amber-200 bg-amber-50 text-amber-950"
>
<p className="container mx-auto px-5 py-3 text-center text-sm">
<strong>Sample content.</strong> This blog is not connected to a Contentful space yet.{" "}
<Link href="/posts/connect-your-contentful-space" className="font-semibold underline hover:text-amber-700">
Connect your Contentful space
</Link>{" "}
to publish your own posts.
</p>
</div>
);
}
41 changes: 41 additions & 0 deletions apps/web/app/cover-image.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import ContentfulImage from "../lib/contentful-image";
import Link from "next/link";

function cn(...classes: any[]) {
return classes.filter(Boolean).join(" ");
}

export default function CoverImage({
title,
url,
slug,
}: {
title: string;
url: string;
slug?: string;
}) {
const image = (
<ContentfulImage
alt={`Cover Image for ${title}`}
priority
width={2000}
height={1000}
className={cn("shadow-small", {
"hover:shadow-medium transition-shadow duration-200": slug,
})}
src={url}
/>
);

return (
<div className="sm:mx-0">
{slug ? (
<Link href={`/posts/${slug}`} aria-label={title}>
{image}
</Link>
) : (
image
)}
</div>
);
}
9 changes: 9 additions & 0 deletions apps/web/app/date.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { format } from "date-fns";

export default function DateComponent({ dateString }: { dateString: string }) {
return (
<time dateTime={dateString}>
{format(new Date(dateString), "LLLL d, yyyy")}
</time>
);
}
Binary file added apps/web/app/favicon.ico
Binary file not shown.
3 changes: 3 additions & 0 deletions apps/web/app/globals.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
Loading
Loading