Skip to content

Latest commit

 

History

History
394 lines (294 loc) · 27.2 KB

routes-and-endpoints.md

File metadata and controls

394 lines (294 loc) · 27.2 KB
title Built-In Routes & HTTP Endpoints
id api-routes-and-endpoints
order 3
description Every route TanStack CMS adds to your app and the full HTTP API: the versioned operations API, error codes, authentication, CSRF, rate limits, OpenAPI, MCP, media, sitemap, robots, redirects, and signed webhooks.
keywords
tanstack cms
http api
rest api
openapi
api keys
createRoutes
route keys
webhooks
x-cms-signature
mcp endpoint
media endpoint

TanStack CMS adds pages, admin screens, and API endpoints to your app through createRoutes(definition, spec?) from @tanstack/cms-ui-react/virtual-routes. The API routes are thin wrappers over createCmsApiHandler(), which you can also mount on any server that speaks Web Request/Response.


Route table

createRoutes() returns the whole virtual route tree for the TanStack Router plugin. Every route has a route key. The keys are stable public API (CmsRouteKey, with the per-surface lists in CMS_ROUTE_KEYS from @tanstack/cms-core/definition): you name them to mount only some routes, drop one, or replace one with your own file. Renaming or removing a key is a breaking change.

Key Surface Path Package file What it is
index public / index.tsx Home page, rendered by theme.variant.
page public /p/$id p.$id.tsx Page by slug or id, with BlocksView.
post public /post/$id post.$id.tsx Post by slug or id.
preview public /preview/$collection/$id preview.$collection.$id.tsx Draft preview behind a preview token.
sitemap public /sitemap.xml sitemap.xml.ts Generated sitemap.
robots public /robots.txt robots.txt.ts Generated robots.txt.
notFound public /$ $.tsx Follows the redirects collection, else renders a 404.
content admin /content content.tsx Content list.
edit admin /edit/$collection/$id edit.$collection.$id.tsx Document editor.
agent admin /agent agent.tsx Content agent chat.
review admin /review review.tsx Review queue and audit log.
settings admin /settings settings.tsx API keys and other settings.
apiWebMcp api /api/cms api.cms.ts WebMCP tool endpoint.
apiV1 api /api/cms/v1/$ api.cms.v1.$.ts Versioned HTTP API and OpenAPI document.
apiMcp api /api/mcp api.mcp.ts MCP server (Streamable HTTP).
apiMedia api /api/media api.media.ts Media upload.
apiMediaFile api /api/media/$name api.media.$name.ts Media file serving and transforms.

Admin paths move under the definition's admin.basePath when one is set (for example /admin/content); public and API paths never move.

Collection routes

A collection with a publicPrefix also gets a catch-all route, {publicPrefix}/$ (package file collection.$.tsx). It reads the rest of the path as a locator, so /docs/guides/install serves the docs document whose locator is guides/install and /docs serves the one at /. A path no document has falls back to the redirects collection, then a 404. These routes are keyed by collection name, not by route key, and are set with the collections option below. A collection at the site root (publicPrefix: '/') mounts at /$ in place of notFound.

createRoutes() throws when a collection's catch-all path is already another route's, or when its prefix starts inside the admin or API routes. Any other route under a prefix wins over the catch-all, so a locator whose first segment is one of those routes could never be served: writes reject it with VALIDATION_FAILED, and a slug generated from the title steps to -2. The segments come from the routes createRoutes() built (the CMS, plugin, and custom routes, plus other collections' prefixes), which the tanstackCms() plugin passes to the build.

createRoutes(definition, spec?)

definition is the defineCmsDefinition result from src/cms.definition.ts, the only app module vite.config.ts imports. Everything derivable comes from it: the admin routes mount under its admin.basePath, and its plugins' routes and adminRoutes are attached after the CMS routes (adminRoutes under the admin base path too). Neither is repeated in the spec.

spec says what to mount. createRoutes(definition) mounts everything.

Option Type Default Description
public surface spec true The public routes.
admin surface spec true The admin routes.
api surface spec true The API routes.
collections collection spec true unless public is false The collection routes: true mounts one per collection with a publicPrefix, false none, ['docs'] only these, and { docs: false } / { docs: './docs.$.tsx' } drops or replaces one. Naming a collection without a publicPrefix throws.
custom Array<VirtualRouteNode> none Your app's own routes, built with route() / index() / physical() from @tanstack/virtual-file-routes, attached after the CMS and plugin routes.
rootFile string package __root.tsx Your own root route file.
renderers string none Your renderers module (export const renderers = defineRenderers({ blocks })), relative to the routes directory. The CMS routes render blocks with it. See Custom block renderers.

Each surface takes the same values:

Value Mounts
true, or leaving the surface out Every route of the surface.
false None of them.
['review'] Only these keys.
{ agent: false, edit: './edit.tsx' } Every route, except that false drops a key and a path replaces its file with yours.

A replacement path is relative to your routes directory (or absolute), and the file must call createFileRoute with the same path as the route it replaces. A key from another surface, or an unknown one, throws. So does an option of the route builder createRoutes() replaced (include, routes, adminBasePath, plugins, children, routesDirectory, generatedDirectory); the error names its replacement, and Upgrading shows the rewrite.

The routes directory and the location of the generated admin route copies are build settings, so they're options of the tanstackCms() Vite plugin. List it before tanstackStart():

tanstackCms() option Default Description
routesDirectory <cwd>/src/routes Your router's routesDirectory; package and replacement paths are resolved against it.
generatedDirectory inside @tanstack/cms-ui-react Where prefixed admin route files are generated when the definition sets admin.basePath.
import { defineConfig } from 'vite'
import { tanstackStart } from '@tanstack/react-start/plugin/vite'
import { physical, route } from '@tanstack/virtual-file-routes'
import { createRoutes } from '@tanstack/cms-ui-react/virtual-routes'
import { tanstackCms } from '@tanstack/cms-ui-react/vite'
import { definition } from './src/cms.definition'

export default defineConfig({
  plugins: [
    tanstackCms(),
    tanstackStart({
      router: {
        virtualRouteConfig: createRoutes(definition, {
          public: { post: 'blog-post.tsx' },
          admin: { agent: false },
          custom: [route('/pricing', 'pricing.tsx'), physical('/shop', 'shop')],
        }),
      },
    }),
  ],
})

Authentication

Every endpoint resolves the caller's session the same way, in this order:

  1. API key: Authorization: Bearer tscms_… or x-cms-api-key: tscms_…. Admins create keys on the admin Settings page (or with createApiKey). A key acts with its role and, optionally, only on its listed collections.
  2. App session: your auth.getUser(request) from defineCms({ auth }), usually reading a cookie.
  3. Development: with no auth configured, a local admin when NODE_ENV is development or test (or when dev: true). Otherwise the caller is anonymous.

Each operation declares the permission it needs. Anonymous callers get 401 UNAUTHORIZED; authenticated callers without the permission get 403 FORBIDDEN. Collection access rules and field access rules apply on top.

CSRF

Cookie-authenticated writes must be same-origin: non-GET requests whose Origin (or Sec-Fetch-Site) doesn't match the request host or security.allowedOrigins fail with 403 FORBIDDEN. Requests authenticated by a CMS API key (tscms_… in Authorization: Bearer or x-cms-api-key) or the shared MCP key are exempt, since browsers never attach those on their own. X-Forwarded-Host is honored only with security.trustForwardedHost. security.disableCsrfCheck turns the check off.

Caching

Operation responses (/api/cms/v1/ops/* and /api/cms) carry Cache-Control: private, no-store and Vary: Cookie, Authorization, because their content depends on the session (drafts, field access).

Rate limits

Limits count per API key, else per user, else per client IP (x-forwarded-for, x-real-ip, or cf-connecting-ip, or security.clientIp(request) when set).

Bucket Default Applies to
ai 30 per minute Operations that need agent.use, AI image generation.
upload 60 per minute Media uploads.
mcp 300 per minute /api/mcp and POST /api/cms.
auth 20 per minute Available to app auth endpoints through rateLimit('auth').
transform 120 per minute Uncached image transforms on GET /api/media/:id.

Change them with defineCms({ security: { rateLimits } }); plug in a shared counter store with security.rateLimitStore when running several instances. Over the limit, the response is 429 RATE_LIMITED with a retry-after header.

Event stream

GET /api/cms/v1/events[?collection=post] is a Server-Sent Events stream of document.created, document.updated, document.published, document.unpublished, and document.deleted events ({ event, collection, id, at }), used by createCmsCollectionOptions({ live: true }).

  • Access: it requires content.read, so anonymous callers get 401. A collection the session can't read gets 403, and an unknown one 404.
  • Filtering: events from collections the session can't read, and documents a read rule hides, are dropped. An update also invalidates a previously readable record that becomes hidden, using the same metadata-only frame.
  • Current access: the server resolves the session again before events and each 30-second heartbeat, closing streams when content-read access expires or is revoked.
  • Limits: each instance holds at most 1000 open streams and 10 per client (API key, user, or IP). Change these with security.eventStreams: { max, perClient }. Over either limit, the response is 429 RATE_LIMITED.

The counts are per process, and events come from the same process, so behind a load balancer a client only sees changes written by the instance it's connected to.


Responses and errors

Successful operation responses are JSON { "result": … }. The discovery routes are the exception: the catalog (GET /api/cms/v1), openapi.json, health, and GET /api/cms return their documents unwrapped. Responses under /api/cms/v1 carry x-cms-api-version: v1, and every response from createCmsApiHandler() carries an x-request-id (the caller's, when well-formed, else a generated UUID).

Errors share one envelope:

{
  "error": {
    "code": "FORBIDDEN",
    "message": "Forbidden: requires content.publish."
  }
}
Code Status When
BAD_REQUEST 400 Malformed JSON, or input that fails the operation's schema (details.issues lists the Zod issues).
UNAUTHORIZED 401 No valid session or key.
FORBIDDEN 403 Missing permission or collection access, or a blocked cross-site request.
NOT_FOUND 404 Unknown operation, document, media, or path.
METHOD_NOT_ALLOWED 405 A POST-only operation called with GET, or an unsupported method.
CONFLICT 409 Stale expectedRevision, a document that already exists, deleting something still referenced (details.references / details.usage), or approving a proposal whose document changed since it was staged (details.baseRevision / details.actualRevision).
PAYLOAD_TOO_LARGE 413 JSON body over security.maxJsonBytes (default 4 MiB) or an upload over uploads.maxBytes (default 10 MiB).
UNSUPPORTED_MEDIA_TYPE 415 An upload that isn't PNG, JPEG, GIF, WebP, AVIF, or (allowed) SVG.
VALIDATION_FAILED 422 A document fails field validate or unique rules, or a relation names a missing document (details names the fields).
RATE_LIMITED 429 Over a rate limit (details.retryAfterSeconds, plus retry-after).
NOT_CONFIGURED 501 A feature isn't configured, for example AI without an adapter.
INTERNAL 500 Anything else. The message is hidden in production; details.requestId matches the logged error.

Versioned HTTP API

Base path: /api/cms/v1.

GET /api/cms/v1

The operation catalog. No authentication required.

{
  "version": "v1",
  "ops": [
    { "name": "list", "description": "…", "method": "GET", "access": "public", "source": "builtin" }
  ]
}

Each op lists name, description, method, access, source (builtin, agent, or app), and agent for ops exposed as agent tools.

GET /api/cms/v1/health

No authentication. 200 { "ok": true, "schema": { "current": 7, "latest": 7 } } when storage answers a read and its schema is current (schema is absent for adapters that don't report one); 503 { "ok": false } otherwise, with the cause sent to defineCms({ logger }). Responses are cache-control: no-store. See Health checks and logging.

GET /api/cms/v1/openapi.json

An OpenAPI 3.1 document describing every operation, generated from the operation schemas, with the request origin as its server URL. Operations are tagged by permission area, carry x-cms-access, and declare the bearerAuth, x-cms-api-key, and session cookie security schemes. Load it into Swagger UI, Postman, or a client generator; build it yourself with buildOpenApiDocument().

POST /api/cms/v1/ops/:name

Runs any operation. Send the input as a JSON body with Content-Type: application/json (other content types are treated as empty input).

curl -X POST https://example.com/api/cms/v1/ops/save \
  -H "Authorization: Bearer $CMS_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"collection":"post","id":"hello","doc":{"title":"Hello"},"publish":true}'

GET /api/cms/v1/ops/:name

Runs a GET operation (and only those). Pass the input as JSON in ?input=, or as flat query parameters for string-only inputs.

curl 'https://example.com/api/cms/v1/ops/list?input={"collection":"post","limit":10}'
curl 'https://example.com/api/cms/v1/ops/get?collection=page&locator=about'

Operations

Every operation is also a TanStack Start server function in @tanstack/cms-api/start and a method of createCmsClient().op(). Access public means anonymous callers may run it.

Operation Method Access Input Result
getAuthSession GET public {} The caller's CmsSession plus ai: { text, image } capabilities.
get GET public { collection, id | locator, staged?, locale?, populate? } { id, locator, collection, doc, relations? } or null. The canonical read (getAs): published only, except for callers who may read drafts of the collection and don't ask for live; drafts are read with staged changes overlaid, unless staged is false. Relations are populated one level deep unless populate is false (or a list of paths).
list GET public { collection?, locale?, where?, sort?: { field, dir? }, limit? (1–500, default 100), offset?, cursor?, populate? } { items: [{ id, collection, doc, relations? }], total, nextCursor? }. The canonical list, with the same visibility and populate default as get.
save POST content.write { collection, id, doc, create?, publish?, expectedRevision?, expectedPendingVersion?, instruction? } { id, collection, doc, state: { label, published, revision, changeSet }, availableActions }. The canonical write (saveAs): doc is a patch merged onto the caller's working copy. It commits for publishers (a draft of a published document unless publish is set) and is submitted for review otherwise. CONFLICT for a stale expectedRevision / expectedPendingVersion, or create on an existing id.
act POST content.read { collection, id, action, publishAt?: string | null, reason?, expectedVersion? } As save, with doc null once the document is gone. Runs an action the document's strategy offers the caller (FORBIDDEN otherwise); edit, submit, draft and import are save's (BAD_REQUEST).
listDocumentSummaries GET content.read { collection, search?, status?: 'all' | 'published' | 'draft' | 'scheduled', locale?, ids? (≤ 500), sort?: { field, dir? }, limit? (1–500, default 50), offset?, columns? (≤ 20) } { items: DocSummary[], total }
getDocument GET content.read { collection, id } { doc, isPending, pendingId?, pendingSource?, livePublished }, including any staged change.
resolveRedirect GET public { path } { to, status } or null
getPublicDocument GET public { slugOrId, preferred?: string[] } { collection, id, doc } or null. Deprecated, removed in the next alpha: use get, once per collection. Published only, except for callers with content.read. A lookup by id, then locator, across collections, trying preferred first.
getDocEditorMeta GET content.read { collection, id } { state, availableActions, revisions, translations, references }. state and availableActions are the caller's, as save returns them.
restoreDocRevision POST content.publish { collection, id, revisionId } { ok, doc }
discardDraft POST content.write { collection, id } { ok }. Also needs publish rights.
deleteDoc POST content.delete { collection, id, force? } { ok }
bulkDocuments POST content.write { collection, ids (1–100), action: 'publish' | 'unpublish' | 'delete' } { ok, results: [{ id, ok, error?: { code, message } }] }. delete also needs content.delete; publish and unpublish need publish rights. One failed item doesn't stop the rest.
reviewSnapshot GET content.read {} { pending, audit }. Each pending change carries review: { label, actions, stranded? } from its strategy, for the caller. Drafts are excluded unless stranded.
approveChange POST review.decide { id, publish?, force? } The approved pending change. A reviewer without content.publish moves it to Approved for a publisher to publish. CONFLICT when the document changed since the proposal was staged, unless force is set.
rejectChange POST review.decide { id } The rejected pending change.
proposeEdit POST agent.use { collection, id, instruction, current } The AI-proposed document (not saved).
agentChat POST agent.use { messages: [{ role: 'user' | 'assistant', content }], includeToolResults? } { reply, toolResults? }. Actual tool receipts are opt-in; record writes are staged.
editPageBlocks POST agent.use { id, collection?, blocksField?, instruction } { blocks } (not saved)
editBlockWithAi POST agent.use { block, instruction, pageTitle? } { block }
editFieldWithAi POST agent.use { fieldName, fieldLabel, fieldType: 'text' | 'textarea' | 'markdown', currentValue, instruction, contextTitle? } { value }
savePageBlocks POST content.write { id, collection?, blocksField?, blocks } { ok, staged }
listApiKeys GET settings.manage {} ApiKeySummary[]
createApiKey POST settings.manage { name, role, collections? } { key, record }. The plaintext key is returned once.
revokeApiKey POST settings.manage { id } { ok }
listUploadedMedia GET content.read { limit? (1–500), offset? } { items: MediaItem[], total }, newest first.
getUploadedMedia GET content.read { urlOrId } MediaItem or null
getMediaUsage GET content.read { urlOrId } [{ collection, id }]: documents (and pending changes) that use it, limited to readable collections.
updateUploadedMedia POST media.upload { urlOrId, alt? (≤ 1000), filename? (≤ 200) } MediaItem
deleteUploadedMedia POST media.delete { urlOrId, force? } { ok }. CONFLICT with details.usage while documents use it, unless force.
uploadImage POST media.upload { dataUrl, filename?, alt? } { url, item }. Base64 data URL; prefer multipart POST /api/media for large files. Counts against the upload limit.
aiImage POST agent.use { instruction, src? } { url, item }. Generates an image, or edits the stored one at src; saved as a new media item. Also needs media.upload.

Operations that need agent.use also count against the ai rate limit and return 501 NOT_CONFIGURED when no AI adapter is configured.


Agent endpoints

/api/mcp

A Model Context Protocol server over Streamable HTTP (GET, POST, DELETE), exposing the agent tools (list_documents, get_document, save_document, …). Write tools stage their changes for review.

Access is granted to:

  • a CMS API key or session with agent.use (tools run with that role and collection scope);
  • the shared secret in mcp.apiKey or CMS_MCP_API_KEY, sent as a bearer token (acts as mcp.apiKeyRole, default author);
  • anyone, when mcp.requireAuth is false (read and staged writes only).

Otherwise it responds 401 or 403. Requests count against the mcp rate limit.

/api/cms

The endpoint behind the in-page WebMCP tools. Like WebMCP itself it is experimental and outside the /api/cms/v1 stability guarantee (see the versioning policy).

  • GET returns { ops: [{ name, description, kind: 'read' | 'write' }] }, the agent tool list, without authentication.
  • POST { "op": "list_documents", "input": { … } } runs one tool and returns { result }. It requires agent.use, a same-origin request (CSRF check), and counts against the mcp limit.

Media endpoints

POST /api/media

Uploads an image. Requires media.upload and counts against the upload limit.

  • Multipart: a file field plus an optional alt field.
  • Raw body: the bytes as the body, with ?filename= and ?alt= in the query.

Responds 201 with { "result": MediaItem }, where result.url is the portable /api/media/<id> URL to store in documents.

curl -X POST https://example.com/api/media \
  -H "Authorization: Bearer $CMS_API_KEY" \
  -F file=@hero.png -F alt="Team photo"

GET /api/media/:name

Serves a stored image by id (an extension is optional). Query parameters:

Parameter Description
w / width Resize to this width, rounded up to the next of 64, 128, 256, 384, 640, 750, 828, 1080, 1200, 1920, 2048, 3840.
format auto (AVIF or WebP from the Accept header), webp, avif, png, or jpeg.
q Quality, 30–100 (default 80).

Transforms need the optional sharp package; without it the original is served. Responses are cached as immutable with an ETag (304 on If-None-Match), sent with nosniff, and SVGs get a sandboxing CSP. When the media adapter has a publicUrl and no transform is requested, the response is a 302 to the public object URL. createCmsApiHandler also answers HEAD.


Sitemap, robots, and redirects

  • GET /sitemap.xml lists published documents of collections that define path, skipping seo.noindex documents and documents canonicalized elsewhere. Returns 404 when seo.sitemap is false. Cached for 5 minutes.
  • GET /robots.txt allows everything except the API and admin paths and seo.robots.disallow, and links the sitemap. A string seo.robots replaces the body. Cached for an hour.
  • Redirects come from the redirects collection (redirectsCollection()). In a Start app, the notFound, page, and post routes follow them with a 301 or 302. Outside Start, call handleRedirect(request) before your own routing; it handles GET and HEAD, keeps the query string for path targets, and returns null when nothing matches.

All URLs use seo.siteUrl, or the request origin when it isn't set.


Webhooks

defineCms({ webhooks }) POSTs a JSON payload to each hook after commits (document.created, document.updated, document.published, document.unpublished, document.deleted), filtered by the hook's events and collections. The short names (publish, change, …) were removed and throw at defineCms; pnpm codemod event-names rewrites them.

{
  "event": "document.published",
  "collection": "post",
  "id": "hello-world",
  "actor": "editor@example.com",
  "at": "2026-10-08T12:00:00.000Z",
  "doc": { "title": "Hello, world", "published": true }
}

doc is omitted for document.deleted.

Header Value
content-type application/json
user-agent tanstack-cms-webhook
x-cms-event The event name (document.published, …).
x-cms-delivery A UUID, the same across retries of one delivery.
x-cms-timestamp Unix time in seconds.
x-cms-signature sha256=<hex>: HMAC-SHA256 of <timestamp>.<body> with the hook's secret (only when a secret is set).

The hook's own headers are added too. Deliveries time out after 10 seconds and are retried twice (after 0.5 s and 2 s) on network errors, 429, and 5xx. A failed delivery logs a warning and never fails the write.

Verifying signatures

Recompute the HMAC over the raw body, compare in constant time, and reject old timestamps to stop replays. JavaScript receivers can use verifyWebhookSignature; any other runtime follows the same steps:

import { createHmac, timingSafeEqual } from 'node:crypto'

export function verifyCmsWebhook(
  secret: string,
  rawBody: string,
  timestamp: string | null,
  signature: string | null,
): boolean {
  if (!timestamp || !signature) return false
  if (Math.abs(Date.now() / 1000 - Number(timestamp)) > 300) return false
  const expected = `sha256=${createHmac('sha256', secret).update(`${timestamp}.${rawBody}`).digest('hex')}`
  return expected.length === signature.length && timingSafeEqual(Buffer.from(expected), Buffer.from(signature))
}