BTST

Blog Plugin

Content management, editor, drafts, publishing, SEO and more

Full-stackReleased · Preview

Best for

React teams that need editorial workflows and public, indexable content without adopting a separate hosted CMS.

Publish and manage a content section inside the React application you already run.

Real BTST Blog page with three published product-update posts in the generated Next.js application.
Blog is the canonical full-stack proof: one plugin supplies routes, backend behavior, client UI, and a visible published result.

BTST supplies

  • Post and tag data models with typed CRUD APIs and lifecycle hooks
  • SSR-aware list, draft, editor, tag, and post routes
  • Published-page metadata and sitemap entries
  • Customizable Blog pages, hooks, and editor UI

You supply

  • A BTST database adapter
  • An image upload implementation when editor uploads are enabled
  • An authorization policy when protected authoring operations are enabled
  • The application shell, public origin, and deployment

You own and customize

Posts stay in your database, routes run in your application, and ejected Blog views become editable application code.

Compatibility and dependencies

Maintained: Next.js 15+ App Router, React Router v7, TanStack Start.

Requires: A BTST database adapter.

External services: None required.

From registration to result

A semantic workflow, not a setup shortcut

  1. 1Register

    Add the Blog backend and client halves to the existing stack.

  2. 2Write

    Create and edit drafts with the supplied authoring routes.

  3. 3Store

    Persist posts and tags through your selected database adapter.

  4. 4Publish

    Serve the SSR-aware post route with metadata and sitemap output.

Post list requests accept a validated limit from 1 to 201. The Search provider can opt into one 201-candidate request with batchSize: 201; request authorization and publication checks still apply. For text queries without editorial activation, the adapter filters ID-only matches before loading the requested page. Editorial searches continue matching approved live revisions. The (published, createdAt) baseline index is part of the Blog schema; regenerate and migrate existing databases to install it.

Installation

Ensure you followed the general framework installation guide first.

Install the Blog package alongside Core 6:

pnpm add @btst/stack@6.2.0 @btst/plugin-blog@1.1.0

Blog supports Core >=6.2.0 <6.3.0. Newsletter, AI Chat and the standalone @btst/components package are optional. Blog uses Core's page-context hooks and owns its editor implementation. Keep the registration key blog.

Follow these steps to add the Blog plugin to your BTST setup.

1. Add Plugin to Backend API

Import and register the blog backend plugin in your stack.ts file:

lib/stack.ts
import { createBackendStack } from "@btst/stack/api"
import { blogBackendPlugin } from "@btst/plugin-blog/api"
// ... your adapter imports

const { handler, dbSchema } = createBackendStack({
  basePath: "/api/data",
  plugins: {
    blog: blogBackendPlugin()
  },
  adapter: (db) => createPrismaAdapter(prisma, db, { 
    provider: "postgresql" 
  })
})

export { handler, dbSchema }

The blogBackendPlugin() accepts optional post-authorization lifecycle hooks for domain invariants, logging, and side effects.

2. Add Plugin to Client

Register the blog client plugin in your stack-client.tsx file:

lib/stack-client.tsx
import { createClientStack } from "@btst/stack/client"
import { blogClientPlugin } from "@btst/plugin-blog/client"
import { QueryClient } from "@tanstack/react-query"

const getBaseURL = () =>
  typeof window !== "undefined"
    ? window.location.origin
    : process.env.BASE_URL || "http://localhost:3000"

export const getStackClient = (
  queryClient: QueryClient,
  options?: { headers?: HeadersInit },
) => {
  const baseURL = getBaseURL()
  return createClientStack({
    api: {
      baseURL,
      basePath: "/api/data",
      headers: options?.headers,
    },
    site: { baseURL, basePath: "/pages" },
    queryClient,
    plugins: {
      blog: blogClientPlugin({
        seo: {
          siteName: "My Blog",
          author: "Your Name",
          twitterHandle: "@yourhandle",
          locale: "en_US",
          defaultImage: `${baseURL}/og-image.png`,
        },
      })
    }
  })
}

Shared API, site, query-client, and per-request header values belong on createClientStack(). blogClientPlugin() accepts only Blog-specific SEO, loader hooks, and page component choices.

Migrating to v3: move apiBaseURL, apiBasePath, siteBaseURL, siteBasePath, queryClient, and headers out of blogClientPlugin() and into the top-level client stack fields shown above. Rename the old onLoadError loader hook to onErrorLoad.

3. Import Plugin CSS

Add the blog plugin CSS to your global stylesheet:

app/globals.css
@import "@btst/plugin-blog/css";

This includes all necessary styles for the blog components, markdown rendering, and editor.

4. Add the Context Provider

Pass the resolved client stack to StackProvider, add the framework router, and keep only Blog-specific values in overrides:

Create the provider stack inside the browser layout without request headers. SSR page factories create a separate request stack with their request QueryClient and headers; never serialize that function-bearing server object through a Client Component prop.

app/pages/client-layout.tsx
"use client"

import { useMemo } from "react"
import { QueryClientProvider } from "@tanstack/react-query"
import { StackProvider } from "@btst/stack/context"
import { nextRouter } from "@btst/stack/next"
import { getStackClient, type StackClientOptions } from "@/lib/stack-client"
import { getOrCreateQueryClient } from "@/lib/query-client"

export default function Layout({ children, clientOrigins }: {
  children: React.ReactNode
  clientOrigins: StackClientOptions
}) {
  const queryClient = getOrCreateQueryClient()
  const clientStack = useMemo(
    () => getStackClient(queryClient, clientOrigins),
    [clientOrigins.apiOrigin, clientOrigins.siteOrigin, queryClient],
  )
  
  return (
    <QueryClientProvider client={queryClient}>
      <StackProvider
        stack={clientStack}
        router={nextRouter()}
        overrides={{
          blog: {
            uploadImage: async (file) => {
              // Implement your image upload logic
              // Return the URL of the uploaded image
              return "https://example.com/uploads/image.jpg"
            },
          }
        }}
      >
        {children}
      </StackProvider>
    </QueryClientProvider>
  )
}
app/routes/pages/_layout.tsx
import { useMemo, useState } from "react"
import { Outlet } from "react-router"
import { QueryClientProvider } from "@tanstack/react-query"
import { StackProvider } from "@btst/stack/context"
import { reactRouter } from "@btst/stack/react-router"
import { getStackClient } from "~/lib/stack-client"
import { getOrCreateQueryClient } from "~/lib/query-client"

export default function Layout() {
  const [queryClient] = useState(() => getOrCreateQueryClient())
  const clientStack = useMemo(
    () => getStackClient(queryClient),
    [queryClient],
  )
  
  return (
    <QueryClientProvider client={queryClient}>
      <StackProvider
        stack={clientStack}
        router={reactRouter()}
        overrides={{
          blog: {
            uploadImage: async (file) => {
              // Implement your image upload logic
              return "https://example.com/uploads/image.jpg"
            },
          }
        }}
      >
        <Outlet />
      </StackProvider>
    </QueryClientProvider>
  )
}
src/routes/pages/route.tsx
import { useMemo } from "react"
import { QueryClientProvider } from "@tanstack/react-query"
import { StackProvider } from "@btst/stack/context"
import { tanstackRouter } from "@btst/stack/tanstack"
import { getStackClient } from "@/lib/stack-client"
import { Outlet } from "@tanstack/react-router"

function Layout() {
  const { queryClient } = Route.useRouteContext()
  const clientStack = useMemo(
    () => getStackClient(queryClient),
    [queryClient],
  )

  return (
    <QueryClientProvider client={queryClient}>
      <StackProvider
        stack={clientStack}
        router={tanstackRouter()}
        overrides={{
          blog: {
            uploadImage: async (file) => {
              // Implement your image upload logic
              return "https://example.com/uploads/image.jpg"
            },
          }
        }}
      >
        <Outlet />
      </StackProvider>
    </QueryClientProvider>
  )
}

Required overrides:

  • uploadImage: Function to upload images and return their URL

Optional overrides:

  • localization: Custom localization strings
  • showAttribution: Whether to show BTST attribution

5. Generate Database Schema

After adding the plugin, generate your database schema using the CLI:

npx @btst/cli generate --orm prisma --config lib/stack.ts  --output prisma/schema.prisma

This will create the necessary database tables for posts and tags. Run migrations as needed for your ORM.

For more details on the CLI and all available options, see the CLI documentation.

Congratulations, You're Done! 🎉

Your blog plugin is now fully configured and ready to use! Here's a quick reference of what's available:

API Endpoints

The blog plugin provides the following API endpoints (mounted at the resolved Blog API path):

  • GET /posts - List posts with optional filtering (published status, tag, search query)
  • POST /posts - Create a new post
  • PUT /posts/:id - Update an existing post
  • GET /posts/editorial?slug=... - Read the authorized working copy and review status
  • POST /posts/:id/submit - Submit the current immutable revision
  • POST /posts/:id/request-changes - Return a submitted revision for changes
  • POST /posts/:id/approve - Approve the submitted revision
  • POST /posts/:id/publish - Publish the approved revision, or unpublish
  • GET /posts/:id/revisions - Read authorized, paginated revision history
  • POST /posts/:id/revisions/:revisionId/restore - Restore content with an expected version
  • DELETE /posts/:id - Delete a post
  • GET /posts/next-previous - Get previous and next posts relative to a date
  • GET /tags - List all tags

Page Routes

The blog plugin automatically creates the following pages (mounted under the top-level site path):

  • /blog - Blog homepage with published posts
  • /blog/drafts - Draft posts page
  • /blog/new - Create new post page
  • /blog/:slug - Individual post page
  • /blog/:slug/edit - Edit post page
  • /blog/tag/:tagSlug - Posts filtered by tag

Built-in cards for unpublished posts open the editor when the current user has blog.post.update permission. Published posts and read-only draft cards retain their post URL. Applications can keep published post routes static without sending draft authors to a public page that cannot render their private post.

Page Component Overrides

For a different post card on an otherwise built-in page, use StackProvider.overrides.blog.pageOverrides.

You can replace any built-in page with your own React component using the optional pageComponents field in blogClientPlugin(config). The built-in component is used as the fallback whenever an override is not provided. Overrides for parameterized routes receive the route context ({ params }) as props.

blogClientPlugin({
  // ... other config
  pageComponents: {
    // Replace the published posts list page
    posts: MyCustomPostsPage,
    // Replace the single post page — receives the route context as props
    post: ({ params }) => <MyCustomPostPage slug={params.slug} />,
    // Replace the edit post page — receives the route context as props
    editPost: ({ params }) => <MyCustomEditPage slug={params.slug} />,
    // Replace the tag page — receives the route context as props
    tag: ({ params }) => <MyCustomTagPage tagSlug={params.tagSlug} />,
    // Replace the drafts list page
    drafts: MyCustomDraftsPage,
    // Replace the new post page
    newPost: MyCustomNewPostPage,
  },
})

Adding Authorization

The Blog plugin publishes a browser-safe, schema-backed catalog at @btst/plugin-blog/permissions. It covers published, draft, and individual post reads; draft and published creation; content and publish-state updates; deletion; and tag reads. Built-in Blog routes and controls pass these exact descriptors to StackProvider.auth—they do not use resource/action strings.

lib/authorization.ts
import { defineAuthorization } from "@btst/stack/authorization";
import { blogPermissions } from "@btst/plugin-blog/permissions";
import { z } from "zod";

export const authorization = defineAuthorization({
  identity: z.object({
    id: z.string(),
    role: z.enum(["user", "admin"]),
  }),
  permissions: [blogPermissions] as const,
  rules: ({ blog }) => [
    blog.post.read.when(({ identity, facts }) => {
      if (facts.scope === "published") return true;
      if (facts.scope === "post" && (!facts.exists || facts.published)) return true;
      return identity?.role === "admin" ||
        (facts.scope === "post" && identity?.id === facts.authorId);
    }),
    blog.post.create.when(({ identity, facts }) =>
      identity !== null &&
      (facts.publish === "draft" || identity.role === "admin")
    ),
    blog.post.update.when(({ identity, facts }) =>
      identity !== null &&
      (identity.role === "admin" ||
        (identity.id === facts.authorId && facts.publish === "unchanged"))
    ),
    blog.post.delete.when(({ identity, facts }) =>
      identity !== null &&
      (identity.role === "admin" || identity.id === facts.authorId)
    ),
    blog.tag.read.allow(),
  ],
});

The explicit published-post and tag rules make public access intentional; allow() is the unconditional tag rule. Once authorization is installed, a missing Blog rule denies access. Browser facts only improve presentation: each record-sensitive detail, update, and delete operation reloads authoritative post, author, and publish state before evaluation. List facts come from the validated query (and the matched post for a slug), create facts come from the validated publish intent, and the public navigation/tag operations declare their fixed facts explicitly.

Post-detail reads verify that any returned row still matches the authoritative existence, identity, author, and publish facts used for authorization. When an update includes published, the write atomically requires the publish state observed during authorization to still match. A concurrent security-relevant change returns HTTP 409 (POST_READ_STATE_CHANGED or POST_STATE_CHANGED) instead of using stale facts; retry the operation against the current post.

Image upload is not a Blog backend route. uploadImage is an app-supplied client override, so its upload endpoint must enforce the application's own authorization policy.

See the authorization guide to bind this definition to client and server identity adapters.

Revision history and restore

Blog records an immutable snapshot after every successful creation, update, and restore. It does not require CMS. The post write, tag changes, and revision append commit in one transaction; rejected validation, authorization, version checks, or database writes append nothing.

Snapshot and publication behavior

Each SerializedPostRevision includes id, postId, version, createdAt, optional actorId, title, Markdown content, excerpt, slug, optional image, tags, published, and optional publishedAt. Versions and timestamps come from the server. Authorized operations derive the actor from the resolved identity; trusted writes without an actor leave actorId unset.

Tags store the associated tag IDs together with their names and slugs at the time of the snapshot. Restore reconnects those IDs using the tags' current metadata. If a referenced tag has been deleted, restore fails rather than recreating it. The image is the saved URL string: revisions neither copy nor retain media files, so an image removed from its storage provider may no longer load.

Restore replaces title, content, excerpt, slug, image, and tag associations. It preserves the post's current published and publishedAt values. Snapshot publication metadata is for inspection, so restoring an older published revision cannot publish a current draft. In the default simple workflow, restoring a published post changes its live content immediately. With the optional editorial workflow below, restore changes only the working copy and requires review before publication. A conflicting slug or missing tag rejects the whole restore.

History permissions and concurrency

History uses blog.post.history; restore uses blog.post.restore. These are separate from public post reads and ordinary updates. Grant them explicitly in the authorization definition, for example:

blog.post.history.when(({ identity, facts }) =>
  identity !== null &&
  (identity.role === "admin" || identity.id === facts.authorId)
),
blog.post.restore.when(({ identity, facts }) =>
  identity !== null &&
  (identity.role === "admin" || identity.id === facts.authorId)
),

Both operations reload the post's authoritative facts. Public post endpoints return no revision snapshots or revision actors. Permission to read a published post does not grant access to its draft history.

GET /posts/:id/revisions?limit=20&offset=0 returns { items, total, limit, offset, currentVersion }, newest version first. Restore requires the version the editor inspected:

POST /posts/:id/revisions/:revisionId/restore
{ "expectedVersion": 3 }

The returned post includes its new revisionVersion. If another writer changed the post in the meantime, restore returns HTTP 409 without overwriting that change. Editors also submit their observed version when saving. Integrations that need the same protection should pass expectedVersion on updates.

The built-in editor offers Revision history, paginated versions, snapshot inspection, and an explicit restore confirmation. The confirmation warns that unsaved editor changes will be discarded and that publication state is preserved. Existing pageComponents, form components, and overrides remain available; custom editors can import usePostRevisions(postId, enabled?) and useRestorePostRevision() from @btst/plugin-blog/client/hooks. usePostRevisions exposes revisions, loading/error state, hasNextPage, fetchNextPage, and refetch. The restore mutation accepts { id, revisionId, expectedVersion } and returns the restored SerializedPost.

Private revision history is partitioned by the validated StackProvider identity and its authorization resolution. The hook clears older identity partitions and returns no history while identity lookup is pending or fails. Applications must refresh their client auth identity after login, logout, or permission changes. For request-time history hydration, pass the same identity snapshot as the second argument to the revision-list query key:

createBlogQueryKeys(client).postRevisions.list(postId, identity)

For anonymous request-time hydration, pass "anonymous" explicitly. Existing list(postId) calls retain their key shape, but browser hooks always use an explicit identity partition, including anonymous sessions. They discard legacy unscoped history instead of reading private data left by an earlier session.

Schema migration, baselines, and retention

Regenerate the database schema and review an additive migration before building database-backed static pages or deploying: add post.revisionVersion with a default of 0, and create postRevision with its post foreign key and unique revisionKey. Keep existing post and tag rows. The unique revision key must remain enforced by the database. Blog rejects all writes before changing posts, tags, or revisions if the adapter does not advertise native transaction support (ATOMIC_TRANSACTION_REQUIRED). Calling an adapter's transaction() method alone is insufficient: some adapters otherwise run the callback sequentially without rollback.

Enable transaction: true when configuring Prisma, Drizzle, or Kysely adapters. The database and driver must support real transactions with rollback and conditional writes. Adapters without native transaction support cannot perform Blog writes. The generated MongoDB configuration is unsupported. The memory adapter provides rollback and is supported for tests, but is not durable multi-process storage.

Existing posts start at version 0 with empty history. The first successful edit captures the previous content as baseline version 1 and the edited content as version 2, in the same transaction. A baseline has no actor, because its original editor is unknown; its timestamp records capture time, not the historical edit time. Reading history never writes a baseline. There is no automatic bulk backfill, and older content cannot be recovered if it was never recorded. Backfill jobs should preserve this baseline convention and run with the same transaction and uniqueness guarantees.

History has no automatic expiry or revision update/delete endpoint. All versions are retained while the post exists. Deleting a post deletes its revision rows; tags and external image files follow their existing independent lifecycles. Backups and any application-specific retention jobs remain the host's responsibility.

Restore runs the existing update lifecycle hooks after authorization: onBeforeUpdatePost, onAfterUpdatePost, and onErrorUpdatePost. The after hook runs after commit, including for restores, so existing cache invalidation still applies. The restore target, expected version, and snapshot are validated before this lifecycle starts; failures during that preparation do not invoke onErrorUpdatePost. Baseline capture does not emit a separate create or update hook. A failure in an after hook cannot roll back an already committed post or revision.

Optional editorial review

The default Blog workflow still lets authorized writers publish while saving. Enable editorial review on the backend and client to require approval of an immutable revision before publication:

// Backend registration
blog: blogBackendPlugin({ editorialWorkflow: true })

// Client registration
blog: blogClientPlugin({ editorialWorkflow: true })

The backend option enforces the workflow. Client configuration selects the editor that reads the private working copy and exposes permitted review actions. Hiding action buttons alone never grants or enforces permission.

Author and reviewer permissions

Add the new descriptors to the application's existing authorization rules. For example, authors submit their own posts and administrators review and publish:

blog.post.editorialRead.when(({ identity, facts }) =>
  identity !== null &&
  (identity.role === "admin" || identity.id === facts.authorId)
),
blog.post.submit.when(({ identity, facts }) =>
  identity !== null && identity.id === facts.authorId
),
blog.post.requestChanges.when(({ identity }) => identity?.role === "admin"),
blog.post.approve.when(({ identity }) => identity?.role === "admin"),
blog.post.publish.when(({ identity }) => identity?.role === "admin"),

Keep the existing post.create, post.update, post.history, and post.restore grants for the people who need them. editorialRead grants access to private working content and review metadata separately from public post.read. Applications choose their own roles; the plugin does not hard-code author or reviewer identity. A reviewer may also be an author if the application's rules permit it. Self-approval is therefore a host policy, not an implicit prohibition.

Operations reload authoritative facts before authorization. Transition permission facts include the post ID, author ID, content revisionVersion, editorialVersion, and review status; publish also includes the requested published state. Forging review state, revision IDs, actor IDs, or timestamps in a post save cannot approve or publish it. Ordinary create/update requests cannot bypass review using published: true.

Transitions, actors, and conflicts

ActionRequired stateResult
Save or restore contentAuthorized working copyNew immutable revision; review returns to draft
Submitdraft or changes-requestedsubmitted, bound to its current revision ID
Request changessubmitted or approvedchanges-requested, with optional reviewer comment
Approvesubmittedapproved, bound to the submitted revision ID
PublishCurrent revision is approvedThe approved revision becomes live
UnpublishPublish permissionRemove the live version from public reads

GET /posts/editorial?slug=... and the getEditorialPost operation return a SerializedEditorialPost: the working post plus editorial.enabled, status, version, current revisionId, submitted/approved/live revision IDs, live public liveSlug, and optional latest action actorId, updatedAt, and comment. Actors and times come from the server; trusted operations without an identity leave the actor unset. Content revision history remains immutable. Review status and actor metadata describe the latest action or content save rather than a separate review audit log.

Every transition requires both versions that the caller inspected:

POST /posts/:id/approve
{ "expectedVersion": 3, "expectedEditorialVersion": 2 }

Use the same body for /submit, /request-changes, and /publish. Request changes additionally accepts comment; publish accepts published: false to unpublish and defaults to true. The corresponding operations are submitPost, requestPostChanges, approvePost, and publishPost, with the post id alongside these fields.

A stale content or editorial version returns HTTP 409. A content edit racing an approval, or contradictory reviewer decisions, cannot silently overwrite the winning write. Save and restore invalidate approval, so approving revision 3 does not authorize publication of revision 4. Refresh the editor after a conflict and review the updated content before retrying.

Custom editors can import useSuspenseEditorialPost, useSubmitPost, useRequestPostChanges, useApprovePost, and usePublishPost from @btst/plugin-blog/client/hooks. Read working content with the editorial hook; public post hooks intentionally keep returning the live revision. The mutation hooks accept the post ID and both observed versions; request changes additionally accepts a comment and publish accepts the requested publication state. After a successful ordinary save or revision restore, custom editors should call the editorial hook's refetch() to refresh the private working copy; generic public post invalidation deliberately leaves identity-scoped editorial caches separate. The hook also returns scopeKey and isCurrentScope(): key local editor state by scopeKey and check the scope before applying late asynchronous results after navigation or identity changes. Its guarded refetch() can resolve undefined after a scope switch or unmount; discard that result instead of restoring stale content.

Built-in editorial saves, decisions, and revision restores refresh query data without an overlapping framework route refresh. Keep public server-page cache revalidation in the application's publication hooks.

Working copy and live publication

An author's edits to a published post stay private while the previous approved revision remains live. This includes title, body, excerpt, slug, image URL, and tag metadata. Public detail/list reads, metadata, sitemap, navigation, and search use that live revision. Searching or filtering for private edits cannot reveal them or change public counts. Public responses omit editorial state and actors. The existing image-reference limitation still applies: deleting an external file can break the image used by a saved live revision.

Publishing replaces the live revision after checking that the approved revision still matches the working copy. The old public slug remains available until that publication; a private slug change does not redirect or replace it early. Unpublishing is an explicit publication action rather than a side effect of saving a working draft. Saving with published: false preserves the existing live version; unpublish explicitly with publishPost({ published: false, ...versions }). Unpublishing retains the current review status. Publication is represented by the live revision pointer; approved describes review state and does not by itself mean a post is public.

Editorial public listings load stored posts and their live revisions before applying filters and pagination. Page size limits the response size, not the number of posts scanned. This path is intended for modest Blog collections; large installations should account for its database reads and memory use. Collections that have never activated editorial review retain the existing database-filtered list path, with activation checks around public reads. Once a protected write commits, the projection path remains active even if all protected posts are later deleted.

Server rendering and caches

Render editorial editors per request. Resolve identity through the same server auth adapter used by the provider layout, forward only the intended request headers, and pass the complete resolved identity as the Blog client option:

blog: blogClientPlugin({
  editorialWorkflow: true,
  identityPartition: requestIdentity ?? undefined,
})

Hydrate StackProvider.initialIdentity with that same identity snapshot. Private working-copy queries use a separate resource cache partitioned by identity and resolved API endpoint. This keeps their cache entries separate from public live posts and from another user's editor session. Do not derive the partition from untrusted browser input when rendering on the server.

The raw prefetchForRoute("editPost", ...) helper does not seed protected editorial editors: it has no request identity for that private cache. Use the request-aware route loader instead. Public SSG still projects the live revision; simple-mode editor prefetch retains its existing behavior. Never statically publish a private editor or serialize its working-copy cache into public output.

Migration and lifecycle events

Regenerate the adapter schema and apply the additive migration before deploying this plugin version, including installations that keep editorialWorkflow disabled. Public reads probe editorialActivation even in simple mode, so the new schema is required before upgrading the running code. Upgrade every serving and build instance with the workflow disabled before enabling review, because older binaries ignore the private/live markers during a rolling deployment. Keep the revision tables from the preceding section, and add the post.editorial* fields: enabled flag, editorial version/status, submitted, approved, and live revision IDs, live slug, latest actor/time, and comment. Preserve the unique live-slug constraint as well as revision uniqueness. The enabled flag defaults to false, editorial version to 0, and status to draft; existing content and publication remain intact. Also create the editorialActivation table with its activatedAt timestamp. The first protected write inserts an activation record in the same transaction. Retain activation records permanently, including after deleting every editorial post; public reads use this append-only signal to avoid racing the first protected write. Do not clear it in retention jobs or while disabling editorial configuration.

On the first protected write to an existing published post, Blog captures its previous public content as an immutable baseline and retains it as the live version. The new working copy requires review. Enabling review does not rewrite all posts or invent historical approvals. Protection persists on posts that have entered the workflow even if the configuration option is later disabled, so a configuration rollback does not expose their private working copies. Review and publication operations remain available for those protected posts. Previously simple posts require the option to enter the workflow.

Disabling the option in a version that understands editorial protection is safe. Downgrading to a plugin binary from before editorial support is different: that code ignores the protection fields and may serve a published post's private working content. Before such a downgrade, reconcile working content with the approved public version or unpublish every protected post using the current version. Verify public output before deploying the older binary. Do not delete activation records to force the simple read path.

Transitions use onBeforeEditorialTransition, onAfterEditorialTransition, and onErrorEditorialTransition. Their context includes the action, resolved identity, versioned input, and permission facts; the after context also includes the resulting editorial post. Schema validation, fact-loading, and authorization failures occur before these hooks and do not invoke the error hook. Persist review/audit events externally in an after hook if the application needs a full decision history. After hooks run after commit and cannot undo an already committed transition. Content saves/restores continue to use the existing update lifecycle. All writes retain the native transaction and conflict requirements documented for revisions above.

API Reference

Backend (@btst/plugin-blog/api)

blogBackendPlugin

Prop

Type

BlogBackendHooks

Customize backend behavior with optional lifecycle hooks. All Blog hooks run after input validation, trusted fact derivation, identity resolution, and the shared authorization rule. Use them for exceptional domain invariants, logging, and side effects—not ordinary role or ownership checks. Context identity, input, trusted facts, and result values are deeply readonly. The context object itself is frozen; Request and Headers remain standard platform objects.

Prop

Type

Blog lifecycle names use the action-first onBefore<Action><Entity>, onAfter<Action><Entity>, and onError<Action><Entity> grammar.

Removed nameCanonical name
onBeforeNextPreviousPostsonBeforeGetNextPreviousPosts
onPostsReadonAfterListPosts
onPostCreatedonAfterCreatePost
onPostUpdatedonAfterUpdatePost
onPostDeletedonAfterDeletePost
onNextPreviousPostsReadonAfterGetNextPreviousPosts
onListPostsErroronErrorListPosts
onNextPreviousPostsErroronErrorGetNextPreviousPosts
onCreatePostErroronErrorCreatePost
onUpdatePostErroronErrorUpdatePost
onDeletePostErroronErrorDeletePost

Example usage:

lib/stack.ts
import { blogBackendPlugin, type BlogBackendHooks } from "@btst/plugin-blog/api"

const blogHooks: BlogBackendHooks = {
  async onBeforeDeletePost(postId, context) {
    if (isProtectedPost(postId))
      throw new Error("Protected posts cannot be deleted")
    auditDeleteAttempt(context.identity?.id, context.facts)
  },
  async onAfterUpdatePost(post, context) {
    await auditPostChange({
      actorId: context.identity?.id,
      postId: post.id,
      publishTransition: context.facts.publish,
    })
  },
}

const { handler, dbSchema } = createBackendStack({
  plugins: {
    blog: blogBackendPlugin({ hooks: blogHooks })
  },
  // ...
})

Blog lifecycle contexts

Every Blog operation supplies validated input, server-derived facts, resolved identity, and request directly to its lifecycle hooks. The result is available after execution, and an error context is created only after authorization succeeds. Identity, input, facts, and results are plain lifecycle data that is deeply readonly and frozen before hooks can observe it. The context object is also frozen, while its Request and Headers references retain their normal platform behavior. Operation-specific interfaces preserve the exact facts and result types.

Migrating from the earlier v3 RC: Blog hooks now run after authorization and receive operation-specific readonly contexts. Result hooks receive JSON-safe serialized posts (including string timestamps), not mutable database Post values with Date instances. Create/update hook input timestamps are also normalized to ISO strings by their operation schemas instead of being passed as Date instances. Move ordinary role and ownership checks into the shared authorization rule.

Prop

Type

Prop

Type

Prop

Type

Prop

Type

Prop

Type

Prop

Type

Client (@btst/plugin-blog/client)

blogClientPlugin

Prop

Type

BlogClientConfig

The client plugin accepts optional Blog-specific SEO, loader hooks, and page components. Shared runtime configuration belongs on the client stack:

Prop

Type

Example usage:

lib/stack-client.tsx
createClientStack({
  api: { baseURL, basePath: "/api/data", headers: options?.headers },
  site: { baseURL, basePath: "/pages" },
  queryClient,
  plugins: {
    blog: blogClientPlugin({
      seo: {
        siteName: "My Awesome Blog",
        author: "John Doe",
        twitterHandle: "@johndoe",
        locale: "en_US",
        defaultImage: `${baseURL}/og-image.png`,
      },
    }),
  },
})

BlogClientHooks

Customize client-side behavior with lifecycle hooks. These hooks are called during data fetching (both SSR and CSR):

Prop

Type

Example usage:

lib/stack-client.tsx
blog: blogClientPlugin({
  hooks: {
    beforeLoadPosts: async (filter, context) => {
      performance.mark(`blog:list:${filter.published ? "published" : "drafts"}`)
    },
    afterLoadPost: async (post, slug, context) => {
      analytics.track("Blog post loaded", { slug, path: context.path })
    },
    onErrorLoad(error, context) {
      reportError(error, { path: context.path })
    },
  }
})

RouteContext

Prop

Type

LoaderContext

Prop

Type

BlogPluginOverrides

Configure Blog-specific components, slots, localization, and route lifecycle hooks. All lifecycle hooks are optional:

Prop

Type

Use classNames in StackProvider.overrides.blog to style built-in UI slots. Classes merge with the defaults; conflicting Tailwind utilities use your override. Omitting a slot preserves its default styling.

overrides={{
  blog: {
    classNames: { postTitle: "font-serif text-3xl", postCard: "shadow-lg" },
  },
}}

Example usage:

overrides={{
  blog: {
    uploadImage: async (file) => {
      // Implement your image upload logic
      return "https://example.com/uploads/image.jpg"
    },
    onRouteRender: (routeName, context) => {
      // Track page views
    },
  }
}}

Page-specific post cards

Set StackProvider.overrides.blog.pageOverrides to replace cards on individual built-in pages while keeping their loaders, pagination, loading/error handling, and route lifecycle. Each PostCard receives { post: SerializedPost }, the same props as the shared blog.PostCard override.

overrides={{
  blog: {
    PostCard: SharedPostCard,
    pageOverrides: {
      posts: { PostCard: PublishedPostCard },
      tag: { PostCard: TagPostCard },
      post: { PostCard: RecommendationCard },
    },
  },
}}
Page keyCards customized
postsPublished list at /blog
draftsDraft list at /blog/drafts
tagTag list at /blog/tag/:tagSlug
postKeep Reading recommendations at /blog/:slug

A page-specific card wins over blog.PostCard. If it is omitted, the shared card is used; if both are omitted, the built-in card is used. In the example, drafts still use SharedPostCard. Standalone discovery rendering is owned by the optional Search integration.

Choose the customization level that matches the change:

  • classNames styles the built-in elements.
  • Content slots add content at supported positions in the post body.
  • PostCard shares one card across lists and recommendations; pageOverrides chooses cards independently for the listed page contexts.
  • blogClientPlugin({ pageComponents }) replaces a whole page. Use ejected components when you need to own its composition.

Existing page replacements and content slots keep working. Ejected pages own their composition: an ejected PostsList can pass page="posts", page="drafts", or page="tag" to select that page's card; omitting page retains the shared-card fallback.

Slot overrides:

OverrideTypeDescription
postIntroductionSlot(post: SerializedPost) => ReactNodeRender content after the first top-level body paragraph; omitted when there is no paragraph. Reference links and footnotes remain part of one Markdown document.
postBottomSlot(post: SerializedPost) => ReactNodeRender additional content below each blog post — use to embed a CommentThread
import { CommentThread } from "@btst/plugin-comments/client/components"

overrides={{
  blog: {
    // ...
    postBottomSlot: (post) => (
      <CommentThread
        resourceId={post.slug}
        resourceType="blog-post"
      />
    ),
  }
}}

React Data Hooks and Types

You can import the hooks from "@btst/plugin-blog/client/hooks" to use in your components.

UsePostsOptions

Prop

Type

UsePostsResult

Prop

Type

UsePostResult

Prop

Type

UsePostSearchOptions

Prop

Type

UsePostSearchResult

Prop

Type

UseNextPreviousPostsOptions

Prop

Type

UseNextPreviousPostsResult

Prop

Type

UseRecentPostsOptions

Prop

Type

UseRecentPostsResult

Prop

Type

PostCreateInput

Prop

Type

PostUpdateInput

Prop

Type

Server-side Data Access

The Blog plugin exposes standalone lower-level getters and mutation primitives for build-time and administrative work. These raw functions bypass the operation and lifecycle pipeline entirely. Keep them to SSG, migrations, test setup, and seed scripts; use the operation API below for request-time application behavior.

Authorized operations

When createBackendStack() receives a one-rule server adapter, use the request-scoped API for user-facing Blog work. These calls run the same operations as the HTTP routes, including input validation, trusted fact derivation, authorization, and lifecycle hooks:

const blog = myStack.forRequest(request).operations.blog;

const published = await blog.listPosts({ published: true });
const post = await blog.createPost({
  title: "Operation-first Blog",
  content: "...",
  excerpt: "...",
  published: false,
  tags: [],
});
await blog.updatePost({
  id: post.id,
  data: { ...post, title: "Updated", tags: [] },
});
await blog.deletePost({ id: post.id });

Trusted server work can bypass user authorization explicitly while preserving validation, trusted facts, lifecycle hooks, and domain behavior:

await myStack.trusted.blog.updatePost({
  id: postId,
  data: update,
});

trusted skips identity resolution and user authorization only. It is the appropriate surface for a trusted job that still needs normal Blog behavior.

Trusted and lower-level data access

Use myStack.trusted.blog for trusted jobs that should keep normal validation, fact derivation, domain behavior, and hooks. Use myStack.forRequest(request).operations.blog for user-driven server work. myStack.raw.blog contains only prefetchForRoute.

Standalone getters and mutations from @btst/plugin-blog/api remain lower-level adapter primitives for plugin internals or migrations whose caller owns lifecycle composition.

Strict publisher snapshots

An existing Prisma publisher must select only the fields owned by its snapshot contract. Internal revision/editorial columns added by an upgrade should not enter a strict application parser. For example, this minimal content snapshot reads protection state separately from the fields it serializes:

import { z } from "zod"
import { db } from "@/lib/db"

const ContentSnapshot = z.strictObject({
  id: z.string(),
  title: z.string(),
  content: z.string(),
})

async function readContentSnapshot(postId: string) {
  const row = await db.post.findUniqueOrThrow({
    where: { id: postId },
    select: { id: true, title: true, content: true, editorialEnabled: true },
  })
  if (row.editorialEnabled) {
    throw new Error("Editorial protection requires the Blog operation workflow")
  }
  return ContentSnapshot.parse({ id: row.id, title: row.title, content: row.content })
}

This is a snapshot boundary, not a complete publisher. Keep strict validation and explicitly project every owned field and nested relation in a real backup contract. If the application enables editorial review for all posts, refuse raw publishing there too. A read-time flag check alone cannot protect a later write from concurrent editorial activation. Use Blog operations for protected writes; an unprotected raw publisher must enforce its guard and concurrency conditions atomically with the write, alongside its backup and recovery contract.

Direct Prisma/SQL writes and standalone mutation helpers do not compose Blog's operation lifecycle, revisions, or editorial transitions. Updating revisionVersion manually is not a substitute for immutable history. Revalidation after commit only refreshes output; it cannot repair omitted revisions or review. Prefer forRequest(request).operations.blog or trusted.blog so writes retain validation, transactions, lifecycle hooks, and revision rules.

Static Site Generation (SSG)

route.loader() makes HTTP requests to the resolved top-level API endpoint, which silently fails during next build because no dev server is running. Use prefetchForRoute() instead — it reads directly from the database and pre-populates the React Query cache before rendering.

Apply the revision and editorial migrations to the database used by the build before generateStaticParams, metadata, or prefetching runs. Public reads can query editorialActivation even without review enabled. prisma generate alone cannot prevent a missing-table P2021.

prefetchForRoute() is a raw-data escape hatch. It does not resolve identity, evaluate authorization rules, or run Blog lifecycle hooks. Static artifacts are commonly public: use "drafts" or "editPost" only when your deployment applies equivalent access controls to the generated output. Never publish dehydrated protected data into a public page.

prefetchForRoute(routeKey, queryClient, params?)

Route keyParams requiredData prefetched
"posts"—Published posts list
"drafts"—Draft posts list
"post"{ slug: string }Single post detail
"tag"{ tagSlug: string }Tag + tagged posts
"newPost"—(nothing)
"editPost"{ slug: string }Post to edit

Rendering prefetched pages

Data prefetching fills the query cache; it does not download page JavaScript. The existing router API remains supported and lazy loads each page's content:

{route.PageComponent && <route.PageComponent />}

BTST memoizes provider context so unchanged BTST inputs do not trigger context updates during lazy page hydration. Keep the resolved stack and overrides references stable when their inputs have not changed; the generated layouts do this with useMemo. Existing integrations should memoize override objects and their callbacks with the dependencies they use. See provider configuration.

Actual identity, runtime, or override changes still take effect immediately. They can reveal a loading state while page code or data is unavailable, as can framework streaming or context updates from host providers above BTST. Provider memoization does not preload the page module. Secondary sections such as recent posts load independently.

For separate framework route files, these direct entries import the complete guarded page without the registry's inner lazy import or page-wide Suspense boundary:

Import pathComponentProps
@btst/plugin-blog/client/pages/postsPostListPagepublished?: boolean (defaults to true)
@btst/plugin-blog/client/pages/postPostPageslug: string
@btst/plugin-blog/client/pages/tagTagPagetagSlug: string
import { PostPage } from "@btst/plugin-blog/client/pages/post"

<PostPage slug={slug} />

Both approaches use the same permission checks, error boundaries, and route hooks. They require StackProvider, QueryClientProvider, and the corresponding hydrated data. Import each direct entry in its own route file so the framework can load that page and its shared dependencies. Direct imports render the built-in UI; pageComponents replacements apply through the router only.

The native static rendering fix requires Core 6.2.1 and Blog 1.1.1 or their matching Blog prerelease. Prefetch the matching route with myStack.raw.blog.prefetchForRoute() and hydrate its query cache before rendering a direct entry. Your framework owns loading boundaries for unavailable page code or data, such as Next.js loading.tsx or an application-owned Suspense. Direct entries keep permission loading states and error handling, but do not add their own page-wide Suspense. Wrapping an entire static page in Suspense can make React stream even completed large pages into hidden HTML that requires JavaScript to reveal it. Keep the prefetched article outside such a boundary when it must be visible without JavaScript.

Custom page wrappers can use ComposedRoute with suspense={false} for the same framework-owned loading behavior. Its default remains true for lazy registry pages. Disabling it retains permission checks, the error boundary, and route lifecycle hooks; any suspension reaches the nearest surrounding framework boundary. Client render errors still use the plugin's error UI. Server render failures, including denied access, propagate to the framework's error handling.

Application checks for static pages

Core 6.2.1 / Blog 1.1.1 make prefetched native list, article, and tag content visible before JavaScript. They do not configure the application's deployment, identity, metadata, theme, or cache invalidation. Check each boundary:

BoundaryApplication verification
Static outputPrefetch only published public data and hydrate the matching query cache. Fetch raw HTML and view it with JavaScript disabled; the article must be visibly rendered, not only serialized or hidden for streaming. Keep direct entries outside page-wide Suspense.
Anonymous hydrationUse the same anonymous identity snapshot in the static server tree and StackProvider.initialIdentity. Do not read cookies in the static layout; resolve signed-in controls after hydration or in a separate request-aware route group. Test delayed JavaScript for permission/loading flashes.
MetadataA separately imported PostPage does not export Next.js metadata. Implement generateMetadata with a published-only server read, canonical URL, title, description, and social images. Verify raw head output and missing/draft behavior.
ThemeThe host owns its theme provider, CSS variables, and initial theme behavior. Verify readable light/dark HTML, hydration, and a working theme control.
PublicationInvalidate article, list, tag, sitemap, social-image, and application dependency caches after commit. Renames, tag changes, and unpublishing require both old and new paths; capture old dependencies before the mutation.

For an application that retains stable article slugs, a minimal ordinary-write invalidation hook is:

import { blogBackendPlugin } from "@btst/plugin-blog/api"
import { revalidatePath } from "next/cache"

function invalidateArticle(slug: string) {
  revalidatePath(`/pages/blog/${encodeURIComponent(slug)}`)
  revalidatePath("/pages/blog")
  revalidatePath("/sitemap.xml")
}

blogBackendPlugin({
  hooks: {
    onAfterCreatePost: (post) => invalidateArticle(post.slug),
    onAfterUpdatePost: (post) => invalidateArticle(post.slug),
  },
})

Extend this for deletes, old slugs, tags, social images, and dependent CMS pages. Editorial publication/unpublication uses onAfterEditorialTransition; invalidate the previous and resulting live paths there as well. CMS policies provide onAfterPublishContent. Plain static hosting needs an application-triggered rebuild rather than Next.js ISR invalidation. External publishers need an authenticated, input-validated invalidation endpoint called after commit. Persist or retry failed invalidations: an after-hook error cannot roll back committed content, and a dispatcher need not replay the hook. Verify a published edit appears without a manual rebuild.

Next.js example

app/pages/blog/page.tsx
import { dehydrate, HydrationBoundary } from "@tanstack/react-query"
import { getOrCreateQueryClient } from "@/lib/query-client"
import { getStackClient } from "@/lib/stack-client"
import { myStack } from "@/lib/stack"
import { metaElementsToObject, normalizePath } from "@btst/stack/client"
import type { Metadata } from "next"

// Opt into SSG — Next.js generates this page at build time
export async function generateStaticParams() {
  return [{}]
}

// export const revalidate = 3600 // uncomment for ISR (1 hour)

export async function generateMetadata(): Promise<Metadata> {
  const queryClient = getOrCreateQueryClient()
  const stackClient = getStackClient(queryClient)
  const route = stackClient.router.getRoute(normalizePath(["blog"]))
  if (!route) return { title: "Blog" }
  await myStack.raw.blog.prefetchForRoute("posts", queryClient)
  return metaElementsToObject(route.meta?.() ?? []) satisfies Metadata
}

export default async function BlogListPage() {
  const queryClient = getOrCreateQueryClient()
  const route = getStackClient(queryClient).router.getRoute("/blog")
  // Reads directly from DB — works at build time, no HTTP server required
  await myStack.raw.blog.prefetchForRoute("posts", queryClient)
  return (
    <HydrationBoundary state={dehydrate(queryClient)}>
      {route?.PageComponent && <route.PageComponent />}
    </HydrationBoundary>
  )
}

For individual post pages, also generate the static params list:

app/pages/blog/[slug]/page.tsx
export async function generateStaticParams() {
  const { items } = await myStack.trusted.blog.listPosts({ published: true, limit: 1000 })
  return items.map((p) => ({ slug: p.slug }))
}

export default async function BlogPostPage({ params }: { params: Promise<{ slug: string }> }) {
  const { slug } = await params
  const queryClient = getOrCreateQueryClient()
  const route = getStackClient(queryClient).router.getRoute(`/blog/${slug}`)
  await myStack.raw.blog.prefetchForRoute("post", queryClient, { slug })
  return (
    <HydrationBoundary state={dehydrate(queryClient)}>
      {route?.PageComponent && <route.PageComponent />}
    </HydrationBoundary>
  )
}

ISR cache invalidation

If you use Incremental Static Regeneration, the static page cache must be purged whenever content changes. Wire up revalidatePath (or revalidateTag) inside the backend lifecycle hooks so Next.js regenerates the page on the next request:

lib/stack.ts
import { revalidatePath } from "next/cache"
import type { BlogBackendHooks } from "@btst/plugin-blog"

const blogHooks: BlogBackendHooks = {
  onAfterCreatePost: async (post) => {
    revalidatePath("/blog")
    revalidatePath(`/blog/${post.slug}`)
  },
  onAfterUpdatePost: async (post) => {
    revalidatePath("/blog")
    revalidatePath(`/blog/${post.slug}`)
  },
  onAfterDeletePost: async (postId) => {
    revalidatePath("/blog")
  },
}

revalidatePath / revalidateTag are Next.js APIs — import them from "next/cache". They are no-ops outside of a Next.js runtime, so this pattern is safe to use in the lib/stack.ts shared file without breaking other frameworks.

Query key consistency

prefetchForRoute uses the same query key shapes as createBlogQueryKeys (the HTTP client). The shared constants live in @btst/plugin-blog/api as BLOG_QUERY_KEYS and postsListDiscriminator, so the two paths can never drift silently.

Shadcn Registry

The Blog plugin UI layer is distributed as a shadcn registry block. Use the registry to eject and fully customize the page components while keeping all data-fetching and API logic from @btst/stack.

The registry installs only the view layer. Hooks and data-fetching continue to come from @btst/plugin-blog/client/hooks.

npx shadcn@latest add https://github.com/better-stack-ai/better-stack/blob/main/packages/stack/registry/btst-blog.json
pnpx shadcn@latest add https://github.com/better-stack-ai/better-stack/blob/main/packages/stack/registry/btst-blog.json
bunx shadcn@latest add https://github.com/better-stack-ai/better-stack/blob/main/packages/stack/registry/btst-blog.json

This copies the page components into src/components/btst/blog/client/ in your project. All relative imports remain valid and you can edit the files freely — the plugin's data layer stays intact.

Using ejected components

After installing, wire your custom components into the plugin via the pageComponents option in your client plugin config:

lib/stack-client.tsx
import { blogClientPlugin } from "@btst/plugin-blog/client"
// Import your ejected (and customized) page components
import { HomePageComponent } from "@/components/btst/blog/client/components/pages/home-page"
import { PostPageComponent } from "@/components/btst/blog/client/components/pages/post-page"

blogClientPlugin({
  pageComponents: {
    posts: HomePageComponent,       // replaces the published posts list page
    // Param routes receive the route context ({ params }) as props
    post: ({ params }) => <PostPageComponent slug={params.slug} />,
    // drafts, newPost, editPost, tag — omit to keep built-in defaults
  },
})

Any key you omit falls back to the built-in default, so you can override just the pages you want to change.

CommonJS editor bundling

The API supports native ESM and CommonJS. Browser CommonJS consumers of the Markdown editor need a bundler with the import resolution condition for Milkdown's import-only SDK subpaths. Resolve the BTST CommonJS files explicitly; do not substitute BTST's ESM entries:

import assert from "node:assert/strict";
import { createRequire } from "node:module";
const require = createRequire(import.meta.url);
const entries = ["client", "client/components", "client/pages/post", "permissions"];
const alias = entries.map((entry) => {
  const name = `@btst/plugin-blog/${entry}`;
  const replacement = require.resolve(name);
  assert.match(replacement, /\.cjs$/);
  return { find: new RegExp(`^${name}$`), replacement };
});
// Vite configuration
export default {
  resolve: { conditions: ["module", "browser", "production", "import"], alias },
};

Use the normal CSS import above. Native Node loading of editor components is unsupported because they import CSS and Milkdown's CommonJS build requires import-only SDK paths. The backend API does not load the editor.

Standalone discovery migration

Blog's standalone post-search dialog is provided by the optional Search plugin. Select both blog and search in the CLI, or register a Blog provider and pass search: <SearchInput sources={["blog"]} /> through BlogPluginOverrides. Import SearchInput from @btst/plugin-search/client/components.

Blog installed alone retains publishing, administration, its published/draft query operations, and usePostSearch. It renders no standalone discovery trigger unless the application supplies the optional search slot. The old internal shared/search-input, shared/search-modal, and shared/highlight-text modules have been removed. Other feature-local catalog, management, and selection controls do not require Search.