The TypeScript SDK: getting started
What this is. A guide to the @exponentialcms TypeScript SDK: a set of npm packages that read and write an
Exponential site through its GraphQL API (/api/graphql). It covers a first app in five minutes, picking the
packages for your framework, typed queries generated from your site's schema, tests without a site, and which
packages still wait for a kernel feature. The Headless overview lists every
package; this page puts them in order.
When to read it. You write a front end, an app or an integration in JavaScript or TypeScript and want typed
answers, the stable error codes, cache tags and webhooks without writing the HTTP by hand. Everything the SDK does
also works with plain fetch: the GraphQL API reference is the contract behind it.
Status. Every package is at version 1.0.0 and tested in CI on Node 20, 22 and 24, but not published to npm yet. Until then, install from GitHub:
npm install github:se7enxweb/exponentialcms-client, or letcreate-exponentialcmsdo it with--sdk-source github. Each package lives in its own repository athttps://github.com/se7enxweb/exponentialcms-<name>; itsdocs/folder is the full reference.
Contents
- Hello World in five minutes
- A query by hand
- Full-stack starters
- Choosing packages
- Typed content: codegen
- Keys: what goes where
- Caching and webhooks
- Rich text, images and links
- Tests without a site: the mock
- Packages that wait for kernel features
- Troubleshooting
Hello World in five minutes
You need Node 20.19 or later and Docker (or Podman).
# 1. Exponential 6 with Velocity on http://localhost:8080, the GraphQL API switched on
npx github:se7enxweb/create-exponentialcms server
2. A React app that reads it (or --framework vue)
npx github:se7enxweb/create-exponentialcms my-site --sdk-source github --framework react --url http://localhost:8080 --siteaccess site --yes
3. Run it, then open http://localhost:5173
cd my-site && npm install && npm run devThe page shows the name of the site's front page as a heading and the content below it as a list. The first start
of the container installs the site and takes a minute or two; the command waits and prints the lines for
.env.local. The administration is at http://localhost:8080/admin (user admin); the generated password stays in
the container: docker exec exponential-dev cat var/log/initial-admin-password.
The whole app is one component, src/App.tsx:
import { gql } from '@exponentialcms/client';
import { useQuery } from '@exponentialcms/react';
type Item = { id: number; name: string };
const Home = gql<{ node: (Item & { children: { nodes: Item[] } }) | null }, { alias: string }>`
query Home($alias: String) { node(urlAlias: $alias) { id name children { nodes { id name } } } }`;
export default function App() {
const { data, loading, error } = useQuery(Home, { alias: '' });
if (loading && !data) return <p>Loading</p>;
if (error || !data?.node) return <p>Could not load the page: {error?.message ?? 'not found'}</p>;
return (
<main>
<h1>{data.node.name}</h1>
<ul>{data.node.children.nodes.map((child) => <li key={child.id}>{child.name}</li>)}</ul>
</main>
);
}Already have a site? Skip step 1 and pass its address to --url. The API must be switched on in the siteaccess
(Operations, "Switching the API on"), and a browser app needs its origin in the
CORS list (CORS, rate limits and the request shield).
A query by hand
Without a framework, the client is all you need. It has no runtime dependencies and runs wherever fetch does:
Node.js, Bun, Deno, edge runtimes and browsers.
import { createClient, gql } from '@exponentialcms/client';
const client = createClient({ url: 'https://www.example.com', siteaccess: 'site' });
const About = gql<{ node: { name: string; url: string | null } | null }>`
{ node(urlAlias: "about") { name url } }
`;
const result = await client.execute(About);
result.data.node?.name; // 'About'
result.cacheTags; // ['ez-all', 'c58', 'l60', ...]: tag your cache with them
result.schemaHash; // '19deb36636de': regenerate your types when it changes
result.requestId; // quote it when you ask the site's administratorsclient.request(About) returns only the data. Every failure is a typed error with the server's stable code
(FORBIDDEN, NOT_FOUND, BAD_USER_INPUT, RATE_LIMITED ...); queries are retried safely on network errors and
on 502, 503 and 504, mutations never unless you ask.
Full-stack starters
create-exponentialcms also writes complete server-rendered projects:
npx github:se7enxweb/create-exponentialcms my-site --sdk-source github --framework next --url https://www.example.com --siteaccess site--framework | What you get |
|---|---|
react, vue | a single-page app on Vite: the Hello World above |
next | Next.js App Router; pages render with @exponentialcms/react/server in server components |
nuxt | Nuxt 4 with server routes and the Nitro cache |
sveltekit | SvelteKit with load functions on the server |
astro | Astro with server rendering and the content loader |
Each full-stack starter has a catch-all content route by URL alias, the generated types of your site (npm run codegen), cache tags on every answer, a webhook route that verifies the signature and purges exactly those tags,
draft previews with preview tokens and a 404 page. The project's README lists the steps and the
security notes. --ai-tools adds typed tools for AI agents.
Choosing packages
Start with the client and add what your project uses:
| You build | Packages |
|---|---|
| any program, script or worker | @exponentialcms/client, optionally @exponentialcms/query (a typed query builder) |
| content changes from a program (imports, sync) | @exponentialcms/write (typed mutations, drafts, publishing) |
| a React or Vue front end | @exponentialcms/react or @exponentialcms/vue (provider, query hooks, rich text and image components) |
| Next.js, Nuxt, SvelteKit, Astro, React Router | the adapter of the same name: revalidation, cache tags, previews, webhooks |
| Angular, Solid, Qwik, Lit, Ember, web components | the adapter of the same name |
| a server with Express, Fastify or Hono; an edge function | @exponentialcms/node, @exponentialcms/edge |
| a static site (Gatsby, Eleventy, Docusaurus, VitePress) | the adapter of the same name |
| a mobile or desktop app | @exponentialcms/expo, @exponentialcms/electron, @exponentialcms/tauri |
| pages built with Exponential Layouts, live editing | @exponentialcms/layouts |
| the feature sets of the API contract (search, media, taxonomy, SEO ...) | @exponentialcms/api |
| tests and debugging | @exponentialcms/mock, @exponentialcms/devtools |
The Headless overview has the full table with links to every repository.
Typed content: codegen
The server owns the contract: the types of your content classes come from the schema of your site, never written by
hand. @exponentialcms/codegen reads contentClasses and writes a TypeScript module with one type per class and the
schema hash it was made from:
EXPONENTIAL_API_KEY=expk_... npx exponential-codegen --url https://www.example.com --siteaccess site --out src/exponential/types.tsThe key must belong to a signed-in user (a public read key cannot read contentClasses). Run it again when the
schemaHash of an answer differs from the SCHEMA_HASH the module records.
Keys: what goes where
| Key or token | Where it lives | What it may do |
|---|---|---|
| none (anonymous) | anywhere | what the Anonymous role may read |
| public read key | browser code, a mobile app | read only, limited to the siteaccesses it names |
| personal API key of an integration user | the server only (environment variable) | what that user's roles allow; use a user with only the rights the site needs |
| OAuth token per person | the browser or app, from the sign-in | what that person may do |
Never ship a key that can write to a browser. The starters keep the server key in server-only modules and test that no browser bundle names a server variable. Details: Authentication.
Caching and webhooks
Every answer carries cache tags (c58 content, l60 location, p2 path, ct1 class ...). Store the answer in
your framework's cache under those tags, and set up a webhook in the site's administration that calls your
revalidation route when content changes. The route verifies the HMAC-SHA-256 signature over the raw body and purges
the tags the event names:
import { revalidateTag } from 'next/cache';
import { createWebhookReceiver, webhookResponse } from '@exponentialcms/client';
const receive = createWebhookReceiver({
secret: process.env['EXPONENTIAL_WEBHOOK_SECRET'] ?? 'set-me',
invalidate: (tags) => tags.forEach(revalidateTag), // c58, l60, pl2 ...
});
export async function POST(incoming: Request): Promise<Response> {
return webhookResponse(await receive(incoming));
}The receiver verifies the signature, drops duplicate deliveries and calls invalidate with the tags.
Each framework adapter wires this to its own cache (Next.js revalidateTag, the Nitro cache, SvelteKit, Astro) and
can send the tags as Cache-Tag or Surrogate-Key headers for Cloudflare, Fastly, Netlify or Akamai.
More: Cache tags and invalidation, Events, webhooks and subscriptions.
Rich text, images and links
- Rich text: ask for
xml, render it with@exponentialcms/richtext(toHtml,toText,toMarkdown) or theRichTextcomponent of React or Vue. Every text and attribute is escaped and only safe link addresses are kept. Links stored asurl_id,node_idorobject_idtake their address fromlinksof the same field (body { xml links { urlId nodeId objectId href } }) once the site offers it (see below). - Images: ask for the aliases you show (
variations(aliases: ["medium", "large"]));imageAttributesof the client and the image components of React and Vue give a safesrc, width, height andsrcset.
Tests without a site: the mock
@exponentialcms/mock runs real GraphQL against a site's schema in memory, with an example site (folders, articles,
images, a layout, a shop) or your own fixtures. Use it in unit tests and as the target of end-to-end tests:
import { createClient } from '@exponentialcms/client';
import { createMockServer, mockSite } from '@exponentialcms/mock';
const mock = createMockServer({
site: mockSite().folder({ name: 'News' }, (news) => news.article({ title: 'Hello', intro: 'The first story.' })),
});
const client = createClient({ url: 'https://www.example.com', fetch: mock.fetch });
const data = await client.request<{ node: { children: { nodes: { name: string }[] } } }>(
'{ node(urlAlias: "news") { children { nodes { name } } } }',
);
// data.node.children.nodes: [{ name: 'Hello' }]mock.fetch never touches the network. exampleSite() is a ready site to test against, and startMockServer()
serves a mock over HTTP for a browser or a whole app. @exponentialcms/devtools records every
request (operation, status, duration, retries, cache tags) for a debug panel or a log.
Packages that wait for kernel features
Some packages are complete on the SDK side but use API features that are proposed for the kernel and not yet in a
release. Until then they raise KernelPieceMissingError, naming the missing feature, instead of failing silently.
Each repository's docs/design.md lists the pieces.
| Package | Works today | Waits for |
|---|---|---|
@exponentialcms/layouts | rendering layouts, zones and blocks; editing the text of content in manual collections | draft editing and the layout editor over GraphQL (opt-in settings DraftEditing and LayoutEditor, under review) |
@exponentialcms/auth | sign-in with the site's web form (authorization code with PKCE), tokens, sign-out | discovery, JWKS and id tokens, token revocation, refresh reuse detection |
@exponentialcms/forms | rendering forms from the class definition, validation in the browser | submitCollection (information collection over the API) and the collector and constraint fields of contentClasses |
@exponentialcms/realtime | refetching the queries a published change touches, over the event subscription | a resume position at subscribe time and a reset when the position is lost |
@exponentialcms/commerce | the typed model and the components | prices, basket, checkout, orders and business accounts in the API |
RichText.links in the starters | rich text without links into the site | RichText.links in the kernel (under review) |
Two-factor sign-in is only ever done on the site's web form: no API (GraphQL, REST, SOAP) asks for a second factor,
and @exponentialcms/auth sends people to that form.
Troubleshooting
| Symptom | Cause and fix |
|---|---|
DISABLED, HTTP 404 from /api/graphql | the API is off in that siteaccess: exp:graphql:enable (Operations) |
| the browser reports a CORS error | the app's origin is not in the siteaccess's CORS list (CORS) |
FORBIDDEN on a field that the administration shows | the key's user lacks content/read there; check its roles (Authentication) |
Cannot query field for a field the class has | the field is in HiddenFieldList[] or the class in ExcludedClassList[] of graphql.ini: both are left out of the schema |
ExponentialShieldChallengeError | the request shield asked for a browser check: add the API path to the shield's exceptions |
| types no longer match the answers | the schema hash changed: run codegen again |
npm install cannot find @exponentialcms/... | not on npm yet: install from GitHub or use --sdk-source github |
More symptoms and fixes: Operations, "Troubleshooting".