Semua artikel

Building a Fast‑Updating Blog CMS with Next.js 14, Prisma, Drafts, ISR, and revalidatePath

Introduction I’m Kaleb, a web developer based in Pompano Beach, Florida. For my own site...

the bomber (Open-Source)6 min read0 kali dilihat
Building a Fast‑Updating Blog CMS with Next.js 14, Prisma, Drafts, ISR, and revalidatePath

Introduction

I’m Kaleb, a web developer based in Pompano Beach, Florida. For my own site at Dream Futures Tech I needed a simple blog that lets me write drafts, preview them instantly, and publish without waiting for a full rebuild. Next.js 14’s new routing and ISR (Incremental Static Regeneration) combined with Prisma give exactly that. Below is a step‑by‑step walk‑through of the pieces I wired together, the pitfalls I hit, and the final workflow that lets me push a post live with a single API call.

1. Project scaffolding

# Create a fresh Next.js 14 app (app router enabled by default)
npx create-next-app@latest my-blog --ts
cd my-blog

# Add Prisma and the SQLite driver (you can swap for Postgres later)
pm i prisma @prisma/client
npx prisma init --datasource-provider sqlite

I keep the SQLite file in the project root (dev.db) because the blog runs on a small VPS at home. For production I switch the datasource URL to a managed Postgres instance.

2. Defining the data model

Edit prisma/schema.prisma:

model Post {
  id          Int      @id @default(autoincrement())
  slug        String   @unique
  title       String
  content     String
  publishedAt DateTime?
  createdAt   DateTime @default(now())
  updatedAt   DateTime @updatedAt

  // Drafts are just posts without a publishedAt timestamp
}

Run the migration:

npx prisma migrate dev --name init

Now we have a Post table where a null publishedAt signals a draft.

3. API routes for CRUD

Next.js 14 lets us colocate route handlers in the app directory. I created app/api/posts/route.ts:

import { NextResponse } from 'next/server';
import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();

export async function GET() {
  const posts = await prisma.post.findMany({
    where: { publishedAt: { not: null } },
    orderBy: { publishedAt: 'desc' },
    select: { id: true, slug: true, title: true, publishedAt: true },
  });
  return NextResponse.json(posts);
}

export async function POST(req: Request) {
  const { title, slug, content, publish } = await req.json();
  const data: any = { title, slug, content };
  if (publish) data.publishedAt = new Date();
  const post = await prisma.post.create({ data });
  // If we just published, trigger ISR revalidation
  if (publish) await revalidatePost(post.slug);
  return NextResponse.json(post);
}

async function revalidatePost(slug: string) {
  // Vercel/Next.js edge runtime revalidatePath
  await fetch(`${process.env.NEXT_PUBLIC_SITE_URL}/api/revalidate`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ slug }),
  });
}

The revalidatePost helper calls a separate route that performs the actual revalidatePath – keeping the API surface clean.

4. Revalidation endpoint

Create app/api/revalidate/route.ts (protected by a simple token for my own use):

import { NextResponse } from 'next/server';

export async function POST(req: Request) {
  const { slug } = await req.json();
  const token = req.headers.get('authorization');
  if (token !== `Bearer ${process.env.REVALIDATE_TOKEN}`) {
    return new NextResponse('Unauthorized', { status: 401 });
  }
  // Path matches the dynamic route we’ll use for posts
  await fetch(`${process.env.NEXT_PUBLIC_SITE_URL}/_next/webpack-hmr`);
  // Next.js 14 API
  await (global as any).res?.revalidate(`/blog/${slug}`);
  return NextResponse.json({ revalidated: true, slug });
}

On Vercel the res.revalidate method is available; on a self‑hosted Node server I expose the same via next/server. The token lives in .env.local and never hits version control.

5. Draft editing UI

In the app/admin folder I built a minimal React form (no UI library, just Tailwind). The key point is that the form POSTs to /api/posts with publish: false while the user is drafting. Because the route returns the created record immediately, I can store the draft ID in local state and later issue a PATCH request to toggle publish.

// app/admin/page.tsx (simplified)
'use client';
import { useState } from 'react';

export default function Admin() {
  const [title, setTitle] = useState('');
  const [slug, setSlug] = useState('');
  const [content, setContent] = useState('');
  const [draftId, setDraftId] = useState<number | null>(null);

  const saveDraft = async () => {
    const res = await fetch('/api/posts', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ title, slug, content, publish: false }),
    });
    const data = await res.json();
    setDraftId(data.id);
  };

  const publish = async () => {
    if (!draftId) return;
    await fetch(`/api/posts/${draftId}`, {
      method: 'PATCH',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ publish: true }),
    });
    // UI can now show a success toast – the page will revalidate automatically
  };

  return (
    <div className="p-4">
      <input placeholder="Title" value={title} onChange={e=>setTitle(e.target.value)} />
      <input placeholder="Slug" value={slug} onChange={e=>setSlug(e.target.value)} />
      <textarea placeholder="Content" value={content} onChange={e=>setContent(e.target.value)} />
      <button onClick={saveDraft}>Save Draft</button>
      <button onClick={publish} disabled={!draftId}>Publish</button>
    </div>
  );
}

Because the draft never gets a publishedAt, it isn’t part of the static generation list, so ISR never tries to render it.

6. ISR page for published posts

Create a dynamic route app/blog/[slug]/page.tsx:

import { notFound } from 'next/navigation';
import { PrismaClient } from '@prisma/client';

export const revalidate = 60; // fallback ISR interval

export default async function PostPage({ params }: { params: { slug: string } }) {
  const prisma = new PrismaClient();
  const post = await prisma.post.findUnique({
    where: { slug: params.slug, publishedAt: { not: null } },
  });
  if (!post) notFound();

  return (
    <article className="prose mx-auto">
      <h1>{post.title}</h1>
      <div dangerouslySetInnerHTML={{ __html: post.content }} />
    </article>
  );
}

The revalidate export tells Next.js to keep the page fresh for up to 60 seconds after the first request. When I publish a post, the revalidatePath call forces an immediate regeneration, so visitors see the new content instantly.

7. Wiring it together on Vercel (or my home server)

  • Environment – .env.local
DATABASE_URL="file:./dev.db"
NEXT_PUBLIC_SITE_URL="https://my-blog.vercel.app"
REVALIDATE_TOKEN="s3cr3t"
  • Deploy – vercel CLI picks up the api routes automatically. On my home server I run npm run build && npm start behind an Nginx reverse proxy; the same res.revalidate call works because I import next/server in a custom server file.
  • Testing – After a draft is saved, I can preview it by hitting /admin/preview?id=123 (a simple fetch that returns the raw markdown). Once published, I open /blog/my-first-post and see the page generated in < 200 ms.

8. Lessons learned

  1. Drafts vs. published – Keeping a single table simplifies queries. The publishedAt nullable field is enough to separate the two states.
  2. ISR + revalidatePath – Without the explicit revalidation call the new post would sit idle until the next scheduled ISR run. A single POST to my /api/revalidate endpoint makes the update instantaneous.
  3. Security – The revalidation endpoint is the only surface that needs protection. A static token works for my solo operation; for a larger client I’d swap in JWTs.
  4. Local development – Prisma’s SQLite DB is perfect for rapid iteration. When I move to production I only change the DATABASE_URL; the rest of the code stays the same.

9. Next steps

  • Add image handling via Cloudinary and store URLs in the Post model.
  • Implement tag support and a simple tag‑cloud page.
  • Hook the admin UI into a headless CMS like Sanity for richer editing experience.

I build sites and automations for small businesses at dreamfuturestech.com.


Sumber artikel open-source oleh the bomber di DEV Community — Baca artikel asli. Topik: #nextjs #prisma #cms #javascript

Sukai & bagikan artikel ini

Ditulis & Dikurasi Oleh

the bomber (Open-Source)

Software Engineer yang berfokus pada Next.js, TypeScript, arsitektur backend skalabel, Cloud, dan Applied AI.

Semua artikel

Komentar