Skip to the content
Documentation
Help Start
Reading in:
  • German: 9,221 of 9,224 pages
About the help in other languages
All help pages

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…

Download as PDF

Address: https://doc.exponential.earth/exphelp/viewer/headless/typescript-sdk.md

On this page

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 let create-exponentialcms do it with --sdk-source github. Each package lives in its own repository at https://github.com/se7enxweb/exponentialcms-<name>; its docs/ folder is the full reference.

Contents

  1. Hello World in five minutes
  2. A query by hand
  3. Full-stack starters
  4. Choosing packages
  5. Typed content: codegen
  6. Keys: what goes where
  7. Caching and webhooks
  8. Rich text, images and links
  9. Tests without a site: the mock
  10. Packages that wait for kernel features
  11. 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 dev

The 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 administrators

client.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
--frameworkWhat you get
react, vuea single-page app on Vite: the Hello World above
nextNext.js App Router; pages render with @exponentialcms/react/server in server components
nuxtNuxt 4 with server routes and the Nitro cache
sveltekitSvelteKit with load functions on the server
astroAstro 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 buildPackages
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 Routerthe adapter of the same name: revalidation, cache tags, previews, webhooks
Angular, Solid, Qwik, Lit, Ember, web componentsthe 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.ts

The 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 tokenWhere it livesWhat it may do
none (anonymous)anywherewhat the Anonymous role may read
public read keybrowser code, a mobile appread only, limited to the siteaccesses it names
personal API key of an integration userthe server only (environment variable)what that user's roles allow; use a user with only the rights the site needs
OAuth token per personthe browser or app, from the sign-inwhat 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: ask for xml, render it with @exponentialcms/richtext (toHtml, toText, toMarkdown) or the RichText component of React or Vue. Every text and attribute is escaped and only safe link addresses are kept. Links stored as url_id, node_id or object_id take their address from links of 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"])); imageAttributes of the client and the image components of React and Vue give a safe src, width, height and srcset.

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.

PackageWorks todayWaits for
@exponentialcms/layoutsrendering layouts, zones and blocks; editing the text of content in manual collectionsdraft editing and the layout editor over GraphQL (opt-in settings DraftEditing and LayoutEditor, under review)
@exponentialcms/authsign-in with the site's web form (authorization code with PKCE), tokens, sign-outdiscovery, JWKS and id tokens, token revocation, refresh reuse detection
@exponentialcms/formsrendering forms from the class definition, validation in the browsersubmitCollection (information collection over the API) and the collector and constraint fields of contentClasses
@exponentialcms/realtimerefetching the queries a published change touches, over the event subscriptiona resume position at subscribe time and a reset when the position is lost
@exponentialcms/commercethe typed model and the componentsprices, basket, checkout, orders and business accounts in the API
RichText.links in the startersrich text without links into the siteRichText.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

SymptomCause and fix
DISABLED, HTTP 404 from /api/graphqlthe API is off in that siteaccess: exp:graphql:enable (Operations)
the browser reports a CORS errorthe app's origin is not in the siteaccess's CORS list (CORS)
FORBIDDEN on a field that the administration showsthe key's user lacks content/read there; check its roles (Authentication)
Cannot query field for a field the class hasthe field is in HiddenFieldList[] or the class in ExcludedClassList[] of graphql.ini: both are left out of the schema
ExponentialShieldChallengeErrorthe request shield asked for a browser check: add the API path to the shield's exceptions
types no longer match the answersthe 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".

Something wrong on this page? Report an error

Documentation license

This documentation is free documentation, licensed under the GNU Free Documentation License 1.3 or later.

Exponential Copyright © 1998-2026 Exponential Foundation and 7x