Cookbook: complete recipes for headless Exponential
What this is. Thirty complete recipes for the tasks headless projects meet again and again: listings, pages by URL, menus, breadcrumbs, images, rich text, search, forms, previews, tags, layouts, languages, multisite, static builds, sitemaps, feeds, webhooks for rebuilds, CDN purges and search indexes, live updates, imports, uploads, workflows, type generation and monitoring.
When to use it. Copy the recipe closest to your task and replace the class identifiers and node ids with yours.
Quick example: recipe 1 in one line.
curl -s https://www.example.com/api/graphql -H 'Content-Type: application/json' \
-d '{"query":"{ children(parentId: 2, depth: 10, classes: [\"ng_article\"], limit: 10, sortField: PUBLISHED, sortOrder: DESC) { totalCount nodes { name url published } } }"}'Conventions of every recipe.
- The class identifiers are those of the media site (
ng_article,ng_recipe,ng_category,ng_landing_page,ng_frontpage): list yours with./console exp:graphql:schema --format=summary. EXPis the site's address (EXP=https://www.example.com); the JavaScript usesconst EXP = 'https://www.example.com'orprocess.env.EXP.@exponentialcms/clientis the SDK client (exponentialcms-client); every recipe also works with plainfetch, as recipe 1 shows.- Server-side code uses a read key in
EXPONENTIAL_API_KEY(scopegraphql:read) and, for writes, a key inEXPONENTIAL_WRITE_KEY(graphql:read,graphql:write); see Authentication. - Node ids differ between installations: look them up by URL alias or remote id
(
node(urlAlias: "blog") { location { id } }), never hard-code them across environments.
Recipes
- A blog listing with pagination
- A page by its URL (catch-all route)
- A navigation menu
- Breadcrumbs
- Responsive images with image aliases
- Rendering rich text
- A search page
- A contact form that creates content
- Draft preview in the front end
- Related content and authors
- Tag pages
- Pages of the page builder (layouts)
- A language switcher
- Multisite: one front end, several siteaccesses
- A static site: walking every page
- An XML sitemap
- Rebuilding a static site on webhooks
- Next.js: revalidate by cache tags
- Purging a CDN by tag
- A search index from webhooks with a query payload
- Live updates in the browser
- Persisted queries in the deployment
- Importing content idempotently
- Uploading images
- An editorial workflow with object states
- A JSON feed
- Types from the schema, and a schema check in CI
- A PHP client without the SDK
- A Python export script
- Resilient clients: retries, timeouts and error handling
1. A blog listing with pagination
Goal: the newest articles below the blog, ten per page, with title, teaser, image and author.
query BlogPage($parent: Int!, $limit: Int!, $offset: Int!) {
children(parentId: $parent, depth: 10, classes: ["ng_article"], limit: $limit, offset: $offset,
sortField: PUBLISHED, sortOrder: DESC) {
totalCount
nodes {
id name url published
... on ng_article {
teaser_title
teaser_intro { excerpt(length: 200) }
teaser_image { url(alias: "medium") width(alias: "medium") height(alias: "medium") alt }
authors { name url }
}
}
}
}Plain fetch:
const EXP = 'https://www.example.com';
const QUERY = `query BlogPage($parent: Int!, $limit: Int!, $offset: Int!) {
children(parentId: $parent, depth: 10, classes: ["ng_article"], limit: $limit, offset: $offset, sortField: PUBLISHED, sortOrder: DESC) {
totalCount
nodes { id name url published ... on ng_article { teaser_title teaser_intro { excerpt(length: 200) }
teaser_image { url(alias: "medium") width(alias: "medium") height(alias: "medium") alt } authors { name url } } }
}
}`;
export async function blogPage(parent, page = 1, perPage = 10) {
const res = await fetch(`${EXP}/api/graphql`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ query: QUERY, variables: { parent, limit: perPage, offset: (page - 1) * perPage } }),
});
const { data, errors } = await res.json();
if (errors) throw new Error(errors[0].extensions?.code + ': ' + errors[0].message);
const { totalCount, nodes } = data.children;
return { items: nodes, page, pages: Math.max(1, Math.ceil(totalCount / perPage)) };
}SDK:
import { createClient } from '@exponentialcms/client';
const client = createClient({ url: process.env.EXP!, siteaccess: 'site' });
type Article = { id: number; name: string; url: string; published: string; teaser_title?: string | null };
export async function blogPage(parent: number, page = 1, perPage = 10) {
const { children } = await client.request<{ children: { totalCount: number; nodes: Article[] } }>(QUERY,
{ parent, limit: perPage, offset: (page - 1) * perPage });
return { items: children.nodes, pages: Math.max(1, Math.ceil(children.totalCount / perPage)) };
}Notes: depth: 10 finds articles in sub-folders too (the answer is tagged p<parent>, purge it on any change below).
For "load more" buttons use first/after (recipe 15).
2. A page by its URL (catch-all route)
Goal: one route /* that renders whatever content lives at the path, by class.
query PageByAlias($alias: String!) {
node(urlAlias: $alias) {
id name classIdentifier url language
location { id pathString }
... on ng_article { title full_intro { html } body { html } image { url(alias: "large") alt } }
... on ng_landing_page { title full_intro { html } }
... on ng_category { title }
}
}// Express (any router works the same)
import express from 'express';
import { createClient } from '@exponentialcms/client';
const client = createClient({ url: process.env.EXP!, siteaccess: 'site' });
const app = express();
app.get('*', async (req, res) => {
const alias = decodeURIComponent(req.path.replace(/^\/+|\/+$/g, '')); // '' is the front page
const { node } = await client.request<{ node: { classIdentifier: string; name: string } | null }>(PAGE_QUERY, { alias });
if (!node) return res.status(404).send('Not found');
res.send(render(node)); // choose a template by node.classIdentifier
});
app.listen(3000);Notes: an alias the user may not read answers null like a missing one: send 404 for both. Aliases are those of the
siteaccess that answers. The answer's url is the canonical address: redirect when the request used another one.
3. A navigation menu
Goal: the top-level pages and their children, in the order editors set (priority).
query Menu($root: Int!) {
children(parentId: $root, classes: ["ng_category", "ng_landing_page"], sortField: PRIORITY, sortOrder: ASC, limit: 12) {
nodes {
name url location { id }
children(classes: ["ng_category", "ng_landing_page"], sortField: PRIORITY, sortOrder: ASC, limit: 12) {
nodes { name url }
}
}
}
}const { siteaccess } = await client.request<{ siteaccess: { rootNodeId: number } }>('{ siteaccess { rootNodeId } }');
const { children } = await client.request<{ children: { nodes: { name: string; url: string; children: { nodes: { name: string; url: string }[] } }[] } }>(
MENU_QUERY, { root: siteaccess.rootNodeId });
const menu = children.nodes.map((n) => ({ label: n.name, href: n.url, items: n.children.nodes.map((c) => ({ label: c.name, href: c.url })) }));Notes: complexity is 12 × (fields + 12 × fields): well under 1000. Store it as a persisted query (menu) and cache it;
its tags are the pl of the root and of each top page, so adding a page purges it.
4. Breadcrumbs
Goal: the path from the root of the site to the current page.
// 1. the path of the page
const { node } = await client.request<{ node: { location: { pathString: string } } | null }>(
'query($a: String!) { node(urlAlias: $a) { location { pathString } } }', { alias: 'recipes/power-up-smoothie' });
const { siteaccess } = await client.request<{ siteaccess: { rootNodeId: number } }>('{ siteaccess { rootNodeId } }');
// 2. every node of the path from the site's root, in one request with aliases
const ids = node!.location.pathString.split('/').filter(Boolean).map(Number);
const fromRoot = ids.slice(ids.indexOf(siteaccess.rootNodeId));
const query = `{ ${fromRoot.map((id, i) => `n${i}: node(id: ${id}) { name url }`).join(' ')} }`;
const data = await client.request<Record<string, { name: string; url: string } | null>>(query);
const crumbs = fromRoot.map((_, i) => data[`n${i}`]).filter(Boolean);Notes: nodes the visitor may not read are null and left out. The ids are integers from the API, so building the query
string is safe here; never put user input into a query string: use variables.
5. Responsive images with image aliases
Goal: an <img> with srcset, width and height from the image aliases of image.ini.
query Hero($alias: String!) {
node(urlAlias: $alias) {
... on ng_article {
image { alt variations(aliases: ["small", "medium", "large"]) { alias url width height } }
}
}
}import { imageAttributes } from '@exponentialcms/client';
const { node } = await client.request<any>(HERO_QUERY, { alias: 'fitness/ten-minutes-a-day' });
const attrs = imageAttributes(node.image, 'medium', { srcSetAliases: ['small', 'medium', 'large'], sizes: '(min-width: 800px) 50vw, 100vw' });
// attrs: { src, width, height, alt, srcset, sizes } -> <img {...attrs} loading="lazy">Without the SDK:
function img(image, sizes = '100vw') {
if (!image) return '';
const v = image.variations.filter((x) => x.url && x.width);
const main = v.find((x) => x.alias === 'medium') ?? v[0];
const esc = (s) => String(s).replace(/[&<>"]/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c]));
const srcset = v.map((x) => `${esc(x.url)} ${x.width}w`).join(', ');
return `<img src="${esc(main.url)}" width="${main.width}" height="${main.height}" alt="${esc(image.alt ?? '')}" srcset="${srcset}" sizes="${sizes}" loading="lazy">`;
}Notes: aliases are made on first request; to avoid a slow first view, let the job queue make them after publishing
(image.alias.generate). Use the URLs as given (they may be signed). Add your own aliases in image.ini and name them
in ImageAliasList[] to make them the default variations.
6. Rendering rich text
Goal: show rich text safely.
query Body($alias: String!) { node(urlAlias: $alias) { ... on ng_article { body { html text xml } } } }| Need | Use |
|---|---|
| the site's own markup is fine | html (rendered by the siteaccess's templates) |
| full control (a design system, a native app) | xml with @exponentialcms/richtext (parse to a tree, render HTML, text or Markdown with your own link and embed handlers) |
| meta description, search snippet, voice | text or excerpt(length:) |
// React: html as it is (it comes from your own editors; sanitize when other sources can write rich text)
export function Body({ html }: { html: string | null }) {
return html ? <div className="rich-text" dangerouslySetInnerHTML={{ __html: html }} /> : null;
}Notes: links inside html are site addresses of the answering siteaccess; rewrite them to your front end's routes if
they differ (or render from xml).
7. A search page
Goal: a search box with paging.
query Search($q: String!, $after: String) {
search(text: $q, classes: ["ng_article", "ng_recipe"], first: 10, after: $after) {
totalCount
nodes { name url classIdentifier ... on ng_article { teaser_intro { excerpt(length: 160) } } }
pageInfo { hasNextPage endCursor }
}
}export async function search(q: string, after: string | null = null) {
if (q.trim().length < 2) return { totalCount: 0, nodes: [], pageInfo: { hasNextPage: false, endCursor: null } };
const { search } = await client.request<any>(SEARCH_QUERY, { q, after });
return search;
}
// GET /search?q=smoothie&after=ZXhwOjk=Notes: text is passed to the installation's engine as the visitor typed it, as a variable (never concatenated into the
query). Facets need Solr (facets: ["class"]). Search answers carry the tag dq: cache them briefly or purge dq on
every event.
8. A contact form that creates content
Goal: a visitor's message stored as content, without exposing a writing key.
Once, on the server: a class contact_message (ezstring name, ezemail email, eztext message), a folder
"Messages" (say node 5012) in a section the public cannot read, a user form-writer whose role allows only
content/create of contact_message below that folder and content/read there, and a key for it:
./console exp:graphql:keys --create --for=form-writer --name='Contact form' --scope=graphql:read,graphql:write --days=365 --applyThe front end's server route (the key never reaches the browser):
import { apiKey, createClient, ExponentialGraphQLError } from '@exponentialcms/client';
const writer = createClient({ url: process.env.EXP!, auth: apiKey(process.env.EXPONENTIAL_WRITE_KEY!) });
export async function POST(request: Request) {
const form = await request.formData();
const name = String(form.get('name') ?? '').slice(0, 200);
const email = String(form.get('email') ?? '').slice(0, 200);
const message = String(form.get('message') ?? '').slice(0, 5000);
if (!name || !email.includes('@') || !message) return new Response('Please fill in every field.', { status: 400 });
try {
await writer.request(
`mutation($f: [FieldInput!]!) { createContent(parentId: 5012, classIdentifier: "contact_message", fields: $f) { status } }`,
{ f: [{ identifier: 'name', value: name }, { identifier: 'email', value: email }, { identifier: 'message', value: message }] },
);
} catch (e) {
if (e instanceof ExponentialGraphQLError && e.hasCode('BAD_USER_INPUT')) return new Response('Invalid input.', { status: 400 });
throw e;
}
return Response.redirect(new URL('/contact/thanks', request.url), 303);
}Notes: add your own spam protection (a captcha, a rate limit per visitor) in this route. Workflows of the class run as
usual (a notification to editors). An alternative without a server: AnonymousMutations=enabled on a dedicated
siteaccess whose role Anonymous may only create contact_message there; then the policy is the only guard.
9. Draft preview in the front end
Goal: an editor clicks "Preview" and sees the draft rendered by the front end.
Make a token (server side, with a key whose owner may read drafts, or from an editor's own tool):
mutation($id: Int!, $version: Int) { createPreviewToken(id: $id, version: $version, ttl: 1800) { token expires } }The preview routes (SDK, any framework with Web Requests):
import { createClient, createPreviewHandler, createPreviewExitHandler, previewTokenFromRequest } from '@exponentialcms/client'; const client = createClient({ url: process.env.EXP! }); export const preview = createPreviewHandler({ client, secure: true }); // GET /api/preview?token=...&to=/fitness/ten-minutes-a-day export const exitPreview = createPreviewExitHandler(); // GET /api/preview/exit?to=/Render the draft while the cookie is there:
const token = previewTokenFromRequest(request); const page = token ? (await client.request<any>('query($t: String!) { preview(token: $t) { name ... on ng_article { title body { html } } } }', { t: token })).preview : (await client.request<any>(PAGE_QUERY, { alias })).node; // send preview answers with Cache-Control: private, no-store (makePrivate(headers))
Notes: the token reads one version, in one language, until it expires, without signing in: treat the preview URL like
a password. Never cache preview pages in a shared cache (makePrivate()). Rotating the installation's secret key ends
every token.
10. Related content and authors
query Article($alias: String!) {
node(urlAlias: $alias) {
name
... on ng_article {
authors { name url ... on ng_article { teaser_image { url(alias: "small") } } }
related_content { name url classIdentifier ... on ng_recipe { teaser_image { url(alias: "small") alt } } }
}
}
}Notes: relations the visitor may not read are left out. They are fetched in batches, so a listing of 50 articles with their related content costs a handful of database queries. Use inline fragments per class of the related items.
11. Tag pages
Goal: /tags/<path> listing content tagged with a tag (eztags active).
query TagPage($path: String!, $after: String) {
tag(path: $path) {
keyword url childrenCount
children(limit: 20) { keyword url }
content(first: 20, after: $after, classes: ["ng_article", "ng_recipe"]) {
totalCount nodes { name url } pageInfo { hasNextPage endCursor }
}
}
}const { tag } = await client.request<any>(TAG_QUERY, { path: 'food/pasta', after: null });
if (!tag) return notFound();Notes: content includes content tagged with a synonym. A tag cloud: tags(parentId: 0, limit: 50) { keyword url childrenCount }.
12. Pages of the page builder (layouts)
Goal: render a page made with Exponential Layouts in your own front end.
query LayoutPage($alias: String!) {
layout(urlAlias: $alias) {
name type
zones {
identifier
blocks {
definition viewType itemViewType name position
parameters { name value }
collectionType
items { name url ... on ng_article { teaser_image { url(alias: "medium") alt } } }
children { definition viewType parameters { name value } items { name url } }
}
}
}
}const { layout } = await client.request<any>(LAYOUT_QUERY, { alias: '' }); // '' the front page
const components: Record<string, (block: any) => string> = {
title: (b) => `<h2>${escapeHtml(b.parameters.find((p: any) => p.name === 'title')?.value ?? '')}</h2>`,
list: (b) => `<ul>${b.items.map((i: any) => `<li><a href="${escapeHtml(i.url)}">${escapeHtml(i.name)}</a></li>`).join('')}</ul>`,
};
const html = layout.zones.map((z: any) => z.blocks.map((b: any) => (components[b.definition] ?? (() => ''))(b)).join('')).join('');Notes: items are the items placed by hand; a dynamic collection's query (collectionType: "dynamic") runs only
when the classic page renders: reproduce it with children or search from the block's parameters. Layout edits
write no content event: give layout pages a short cache TTL.
13. A language switcher
Goal: on every page, links to the same content in the other languages.
Setup: one siteaccess per language (site English, site_de German), each with its languages and URL aliases.
const SITEACCESSES = [{ code: 'eng-GB', siteaccess: 'site', label: 'English' }, { code: 'ger-DE', siteaccess: 'site_de', label: 'Deutsch' }];
export async function languageLinks(objectId: number) {
const { content } = await client.request<{ content: { languages: string[] } | null }>(
'query($id: Int!) { content(id: $id) { languages } }', { id: objectId });
const available = new Set(content?.languages ?? []);
return Promise.all(SITEACCESSES.filter((s) => available.has(s.code)).map(async (s) => {
const data = await client.with({ siteaccess: s.siteaccess }).request<{ content: { url: string } | null }>(
'query($id: Int!) { content(id: $id) { url } }', { id: objectId });
return { label: s.label, href: data.content?.url ?? null, hreflang: s.code };
}));
}Notes: client.with({ siteaccess }) sends X-Siteaccess, so url is the address in that siteaccess (its host or
prefix and its aliases). One siteaccess with several languages instead: read with language: and build URLs your own
way. Add <link rel="alternate" hreflang> from the same data.
14. Multisite: one front end, several siteaccesses
Goal: one deployment serves brand-a.example and brand-b.example, each its own siteaccess with its own tree.
import { createClient } from '@exponentialcms/client';
const SITES: Record<string, { siteaccess: string }> = {
'brand-a.example': { siteaccess: 'brand_a' },
'brand-b.example': { siteaccess: 'brand_b' },
};
const base = createClient({ url: process.env.EXP!, auth: undefined });
export function clientFor(host: string) {
const site = SITES[host];
if (!site) throw new Error(`unknown site ${host}`);
return base.with({ siteaccess: site.siteaccess });
}
// in a request handler: const client = clientFor(request.headers.get('host')!); const root = (await client.request('{ siteaccess { rootNodeId } }')).siteaccess.rootNodeId;Notes: each siteaccess has its own root node, languages, aliases and anonymous rights; the response cache keys by
siteaccess. A key limited to siteaccesses (--key-siteaccess=brand_a,brand_b) can read only these. Webhooks per site:
SiteAccessList[]=brand_a on its own end point, so each site purges only its own pages. Prefix CDN tags per site
(recipe 19).
15. A static site: walking every page
Goal: at build time, fetch every page of the site once.
import { apiKey, createClient } from '@exponentialcms/client';
const client = createClient({ url: process.env.EXP!, auth: apiKey(process.env.EXPONENTIAL_API_KEY!), siteaccess: 'site' });
const WALK = `query Walk($root: Int!, $after: String) {
children(parentId: $root, depth: 20, first: 100, after: $after, sortField: NODE_ID) {
totalCount
nodes { id remoteId name classIdentifier url urlAlias modified location { id parentId } }
pageInfo { hasNextPage endCursor }
}
}`;
export async function allPages() {
const { siteaccess } = await client.request<{ siteaccess: { rootNodeId: number } }>('{ siteaccess { rootNodeId } }');
const seen = new Map<number, any>();
let after: string | null = null;
do {
const { children } = await client.request<any>(WALK, { root: siteaccess.rootNodeId, after });
for (const n of children.nodes) seen.set(n.location.id, n);
after = children.pageInfo.hasNextPage ? children.pageInfo.endCursor : null;
} while (after);
return [...seen.values()];
}Notes: NODE_ID keeps the walk stable while editors publish (new content lands at the end); de-duplicate by node id.
100 per page is MaxListLimit. A walk of 20 000 pages is 200 requests: within the default rate limits; the client
waits on 429 by itself. Then fetch each page's full fields by class, or include them in the walk with inline fragments
(watch the complexity).
16. An XML sitemap
query Sitemap($root: Int!, $after: String) {
children(parentId: $root, depth: 20, first: 100, after: $after, sortField: NODE_ID) {
nodes {
url modified
... on ng_article { metadata { sitemapUse priority change } }
... on ng_landing_page { metadata { sitemapUse priority change } }
}
pageInfo { hasNextPage endCursor }
}
}export async function sitemapXml(root: number) {
const urls: string[] = [];
let after: string | null = null;
const esc = (s: string) => s.replace(/&/g, '&').replace(/</g, '<');
do {
const { children } = await client.request<any>(SITEMAP_QUERY, { root, after });
for (const n of children.nodes) {
if (!n.url || n.metadata?.sitemapUse === false) continue;
urls.push(`<url><loc>${esc(n.url)}</loc>${n.modified ? `<lastmod>${n.modified}</lastmod>` : ''}` +
`${n.metadata?.change ? `<changefreq>${esc(n.metadata.change)}</changefreq>` : ''}` +
`${n.metadata?.priority ? `<priority>${esc(n.metadata.priority)}</priority>` : ''}</url>`);
}
after = children.pageInfo.hasNextPage ? children.pageInfo.endCursor : null;
} while (after);
return `<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">${urls.join('')}</urlset>`;
}Notes: run it anonymously (only public content belongs in a sitemap) or with a read key whose owner reads exactly
the public content. Split at 50 000 URLs per file. modified is ISO 8601 with offset, which sitemaps accept.
17. Rebuilding a static site on webhooks
Goal: a static host (Netlify, Vercel, Cloudflare Pages, your CI) rebuilds after content changes, at most once per few minutes.
Server:
./console exp:graphql:webhooks --add=static --url=https://hooks.example.com/exponential-rebuild \
--events=publish,update,trash,delete,move,hide,reveal --siteaccess=site --applyA small receiver that debounces into the build hook (Node.js 20+, no dependencies besides the SDK):
import { createServer } from 'node:http';
import { verifyWebhook } from '@exponentialcms/client';
const SECRET = process.env.EXPONENTIAL_WEBHOOK_SECRET!;
const BUILD_HOOK = process.env.BUILD_HOOK_URL!; // the host's build hook
const QUIET_MS = 120_000; // build 2 minutes after the last change
let timer: NodeJS.Timeout | null = null;
createServer(async (req, res) => {
if (req.method !== 'POST') { res.writeHead(405).end(); return; }
const chunks: Buffer[] = [];
for await (const c of req) chunks.push(c as Buffer);
const body = Buffer.concat(chunks);
const check = await verifyWebhook({ secret: SECRET, timestamp: req.headers['x-exponential-timestamp'] as string,
signature: req.headers['x-exponential-signature'] as string, body: new Uint8Array(body) });
if (!check.ok) { res.writeHead(401).end(check.reason); return; }
res.writeHead(204).end();
if (req.headers['x-exponential-event'] === 'ping') return;
if (timer) clearTimeout(timer);
timer = setTimeout(async () => { timer = null; await fetch(BUILD_HOOK, { method: 'POST' }); }, QUIET_MS);
}).listen(8787);Notes: a migration with events: summary sends one event for thousands of changes. When the build host itself can
verify an HMAC, point the webhook at it directly; most build hooks cannot, so this receiver checks it.
18. Next.js: revalidate by cache tags
Goal: pages are cached by Next.js and dropped exactly when their content changes.
// lib/exponential.ts
import { apiKey, createClient } from '@exponentialcms/client';
export const client = createClient({ url: process.env.EXP!, auth: apiKey(process.env.EXPONENTIAL_API_KEY!), siteaccess: 'site' });
// app/[[...path]]/page.tsx
import { unstable_cache } from 'next/cache';
import { client } from '@/lib/exponential';
async function load(alias: string) {
const result = await client.execute<any>(PAGE_QUERY, { alias });
return { node: result.data.node, tags: result.cacheTags };
}
export default async function Page({ params }: { params: Promise<{ path?: string[] }> }) {
const alias = ((await params).path ?? []).join('/');
const first = await load(alias); // learn the tags once
const cached = unstable_cache(() => load(alias), ['page', alias], { tags: first.tags });
const { node } = await cached();
if (!node) return <h1>Not found</h1>;
return <article><h1>{node.name}</h1></article>;
}
// app/api/revalidate/route.ts
import { revalidateTag } from 'next/cache';
import { createWebhookReceiver, webhookResponse } from '@exponentialcms/client';
const receive = createWebhookReceiver({
secret: process.env.EXPONENTIAL_WEBHOOK_SECRET!,
invalidate: (tags) => { for (const tag of tags) revalidateTag(tag); revalidateTag('dq'); },
});
export async function POST(request: Request) { return webhookResponse(await receive(request)); }Notes: @exponentialcms/next packages this pattern (tags for cached
functions, the webhook route, previews). Purge p<ancestor> tags too if pages list deep subtrees
(caching).
19. Purging a CDN by tag
Goal: HTML pages cached at the CDN carry the tags of the answers they used; webhooks purge them.
import { applyCacheTags, createWebhookReceiver, webhookResponse } from '@exponentialcms/client';
// when rendering a page
const headers = new Headers({ 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'public, s-maxage=86400' });
applyCacheTags(headers, page.cacheTags, { cdn: 'cloudflare', prefix: 'site1-' });
applyCacheTags(headers, menu.cacheTags, { cdn: 'cloudflare', prefix: 'site1-' }); // merged into one Cache-Tag header
// the webhook route
const receive = createWebhookReceiver({
secret: process.env.EXPONENTIAL_WEBHOOK_SECRET!,
tagPrefix: 'site1-',
invalidate: async (tags) => {
for (let i = 0; i < tags.length; i += 30) {
const res = await fetch(`https://api.cloudflare.com/client/v4/zones/${process.env.CF_ZONE}/purge_cache`, {
method: 'POST',
headers: { Authorization: `Bearer ${process.env.CF_TOKEN}`, 'Content-Type': 'application/json' },
body: JSON.stringify({ tags: tags.slice(i, i + 30) }),
});
if (!res.ok) throw new Error(`purge ${res.status}`); // the webhook is retried
}
},
});
export async function POST(request: Request) { return webhookResponse(await receive(request)); }Notes: applyCacheTags leaves private and non-2xx answers untagged and handles overflow (too many tags) by making the
page no-store. Throwing in invalidate answers an error, so the installation retries the delivery. Other CDNs: the
cdn option (fastly, netlify, akamai) and their purge APIs.
20. A search index from webhooks with a query payload
Goal: an external search engine (Meilisearch, Elasticsearch, Algolia) holds every article; each change arrives with the full document.
The query (queries/article_for_index.graphql):
query ArticleForIndex($objectId: Int!, $language: String) {
content(id: $objectId, language: $language) {
id remoteId name url published modified language languages
location { pathString }
... on ng_article { title teaser_intro { text } body { text } tags { keyword } }
}
}Server:
./console exp:graphql:persist queries/article_for_index.graphql --apply
./console exp:graphql:webhooks --add=search --url=https://indexer.example.com/hook --payload=query \
--query=article_for_index --as=indexer --classes=ng_article --events=publish,update,trash,delete,move,hide,reveal --applyReceiver (PHP):
$secret = getenv( 'EXPONENTIAL_WEBHOOK_SECRET' );
$body = file_get_contents( 'php://input' );
$ts = $_SERVER['HTTP_X_EXPONENTIAL_TIMESTAMP'] ?? '';
if ( !ctype_digit( $ts ) || abs( time() - (int)$ts ) > 300
|| !hash_equals( 'sha256=' . hash_hmac( 'sha256', $ts . '.' . $body, $secret ), $_SERVER['HTTP_X_EXPONENTIAL_SIGNATURE'] ?? '' ) )
{
http_response_code( 401 );
exit;
}
$payload = json_decode( $body, true );
$event = $payload['extensions']['event'];
$doc = $payload['data']['content'] ?? null;
$index = 'https://search.example.com/indexes/articles/documents';
if ( $doc === null || in_array( $event['event'], array( 'trash', 'delete' ), true ) )
$request = array( 'DELETE', $index . '/' . rawurlencode( (string)$event['objectId'] ), null );
else
$request = array( 'POST', $index, json_encode( array( array(
'id' => $doc['id'], 'title' => $doc['title'] ?? $doc['name'], 'url' => $doc['url'], 'text' => $doc['body']['text'] ?? '',
'tags' => array_column( $doc['tags'] ?? array(), 'keyword' ), 'published' => $doc['published'] ) ) ) );
$ch = curl_init( $request[1] );
curl_setopt_array( $ch, array( CURLOPT_CUSTOMREQUEST => $request[0], CURLOPT_POSTFIELDS => $request[2], CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => array( 'Content-Type: application/json', 'Authorization: Bearer ' . getenv( 'SEARCH_KEY' ) ) ) );
curl_exec( $ch );
$status = curl_getinfo( $ch, CURLINFO_RESPONSE_CODE );
http_response_code( $status >= 200 && $status < 300 ? 204 : 502 ); // 502: Exponential retriesNotes: the query runs as indexer (a read-only user): what it may not read arrives as null and is removed from the
index, so hidden or restricted content never leaks into public search. Seed the index once with a walk (recipe 15).
The location { pathString } gives the ancestors for subtree facets.
21. Live updates in the browser
Goal: a "new articles" badge appears without reloading.
Server: allow anonymous subscriptions on the public siteaccess (each open tab holds a PHP process: size
MaxSubscriptions), or subscribe from your own server and fan out:
# settings/siteaccess/site/graphql.ini.append.php
[GraphQLSettings]
AnonymousSubscriptions=enabled
MaxSubscriptionsPerAddress=3Browser:
<span id="badge" hidden></span>
<script type="module">
const url = new URL('https://www.example.com/api/graphql/subscribe');
url.searchParams.set('query', 'subscription { contentPublished(classes: ["ng_article"]) { event objectId content { name url } } }');
const source = new EventSource(url);
let count = 0;
source.addEventListener('next', (e) => {
const { data } = JSON.parse(e.data);
if (data?.contentPublished?.event !== 'publish') return; // new articles only, not edits
document.getElementById('badge').textContent = `${++count} new`;
document.getElementById('badge').hidden = false;
});
</script>Notes: EventSource reconnects by itself with Last-Event-ID. For signed-in subscriptions use the SDK's
client.subscribe() (it sends headers, which EventSource cannot). CORS must allow the page's origin. Behind nginx,
the API sends X-Accel-Buffering: no; check other proxies do not buffer.
22. Persisted queries in the deployment
Goal: the front end ships .graphql files; the deployment stores them; production accepts nothing else from
anonymous visitors.
front-end/queries/
menu.graphql
page.graphql
article-list.graphql# on the server, as part of the front end's deploy (or via ssh from CI)
./console exp:graphql:persist /srv/front-end/queries/ --siteaccess=site # check only; exit 1 if any does not fit
./console exp:graphql:persist /srv/front-end/queries/ --siteaccess=site --apply # store# settings/siteaccess/site/graphql.ini.append.php
[GraphQLSettings]
PersistedQueriesOnly=anonymousconst menu = await client.persisted('menu'); // GET /api/graphql?id=menu
const list = await client.persisted('article-list', { limit: 10, offset: 0 });Notes: names are the file names without .graphql. Store before the new front end goes live (old and new queries can
coexist: names are independent). Remove retired ones with --remove=<name> --apply. An extension can ship queries in a
directory of PersistedQueryDirectoryList[] (read only, no store needed).
23. Importing content idempotently
Goal: import products from a CSV every night without duplicates.
import { readFile } from 'node:fs/promises';
import { apiKey, createClient, ExponentialGraphQLError } from '@exponentialcms/client';
const writer = createClient({ url: process.env.EXP!, auth: apiKey(process.env.EXPONENTIAL_WRITE_KEY!) });
const PARENT = 3100; // the products folder (look it up by URL alias in real code)
for (const line of (await readFile('products.csv', 'utf8')).trim().split('\n').slice(1)) {
const [sku, title, price] = line.split(';');
const remoteId = `erp-product-${sku}`;
const fields = [{ identifier: 'title', value: title }, { identifier: 'price', value: `${price}|1|1` }];
const { content } = await writer.request<{ content: { id: number } | null }>(
'query($r: String!) { content(remoteId: $r) { id } }', { r: remoteId });
try {
if (content) {
await writer.request('mutation($id: Int!, $f: [FieldInput!]!) { updateContent(id: $id, fields: $f) { status } }', { id: content.id, f: fields });
} else {
await writer.request(
'mutation($p: Int!, $r: String!, $f: [FieldInput!]!) { createContent(parentId: $p, classIdentifier: "product", remoteId: $r, fields: $f) { status } }',
{ p: PARENT, r: remoteId, f: fields });
}
} catch (e) {
if (e instanceof ExponentialGraphQLError) console.error(sku, e.codes, e.message); else throw e;
}
}Notes: the remote id derived from the source makes the import idempotent: a re-run updates instead of duplicating, and
a create retried after a timeout is refused ("The remote id ... is taken.") instead of duplicating. The price format is
<price>|<VAT type>|<1 included> (datatypes). For thousands of objects, prefer a
migration (exp:migration:*) with events: summary; mutations publish one by one, with workflows.
24. Uploading images
Goal: upload a file from a server-side script into the media library.
curl -s "$EXP/api/graphql" -H "Authorization: Bearer $EXPONENTIAL_WRITE_KEY" \
-F operations='{"query":"mutation($file: Upload!, $alt: String) { uploadImage(file: $file, parentId: 51, alt: $alt) { status contentId nodeId } }","variables":{"file":null,"alt":"A green smoothie"}}' \
-F map='{"0":["variables.file"]}' \
-F 0[email protected]import { readFile } from 'node:fs/promises';
const file = new Blob([await readFile('smoothie.jpg')], { type: 'image/jpeg' });
const { uploadImage } = await writer.request<any>(
'mutation($file: Upload!, $alt: String) { uploadImage(file: $file, parentId: 51, alt: $alt) { status contentId } }',
{ file, alt: 'A green smoothie' });
// then relate it: updateContent(id: <article>, fields: [{ identifier: "related_multimedia", value: "<contentId>" }])From an allowed host without downloading first: uploadFromUrl(url: "https://images.example.com/a.jpg", parentId: 51)
(only hosts of UploadFromUrlHostList[]).
Notes: the limit is MaxUploadSize and PHP's upload limits. Upload checks (UploadCheckList[], a virus scanner) run on
every file. Browsers should upload to your server, not with a writing key to the API.
25. An editorial workflow with object states
Goal: an external review tool approves content; only approved content is public.
Setup: a state group review with draft, approved; the role Anonymous reads only content in state
review/approved (a state limitation on content/read); the tool's user may state/assign in that group.
mutation Approve($id: Int!) { setObjectStates(id: $id, states: ["review/approved"]) { status } }query Queue($root: Int!) {
children(parentId: $root, depth: 20, classes: ["ng_article"], first: 50, sortField: MODIFIED, sortOrder: DESC) {
nodes { id name modified url }
}
}Notes: run the queue query as the reviewer (it sees every state); anonymous visitors only get approved content once
the state is set. State changes run the content/updateobjectstate operation and its workflows. To also move
approved content into a public section: assignSection(nodeId: ..., sectionId: ..., scope: "subtree").
26. A JSON feed
Goal: a JSON Feed (jsonfeed.org) of the newest articles.
export async function GET() {
const result = await client.execute<any>(`{
children(parentId: 2, depth: 10, classes: ["ng_article"], limit: 20, sortField: PUBLISHED, sortOrder: DESC) {
nodes { id url name published modified ... on ng_article { teaser_intro { text } } }
}
}`);
const feed = {
version: 'https://jsonfeed.org/version/1.1',
title: 'Example news',
home_page_url: 'https://www.example.com/',
feed_url: 'https://www.example.com/feed.json',
items: result.data.children.nodes.map((n: any) => ({
id: String(n.id), url: n.url, title: n.name, summary: n.teaser_intro?.text ?? undefined,
date_published: n.published, date_modified: n.modified,
})),
};
return new Response(JSON.stringify(feed), { headers: { 'Content-Type': 'application/feed+json', 'Cache-Control': 'public, max-age=300' } });
}Notes: the kernel also serves RSS itself (rss/feed); this recipe is for front ends that want their own format.
27. Types from the schema, and a schema check in CI
Goal: TypeScript types per class, and a build that fails when the server's schema changed.
# the schema, from the console on the server (or a signed-in introspection request)
./console exp:graphql:schema --siteaccess=site --output=schema.graphql
./console exp:graphql:query '{ siteaccess { schemaHash } }' --format=table// scripts/check-schema.ts: run in CI before the build
import { apiKey, createClient } from '@exponentialcms/client';
const client = createClient({ url: process.env.EXP!, auth: apiKey(process.env.EXPONENTIAL_API_KEY!), siteaccess: 'site' });
const expected = (await import('../src/generated/schema-hash.json', { with: { type: 'json' } })).default.hash;
const { schemaHash } = await client.execute('{ __typename }');
if (schemaHash !== expected) {
console.error(`The schema changed (${expected} -> ${schemaHash}): regenerate the types.`);
process.exit(1);
}Notes: generate the types with @exponentialcms/codegen (it reads
contentClasses, which needs a signed-in request) or with graphql-codegen from schema.graphql; write the hash next to
them. Run exp:graphql:persist queries/ (check only) on staging as a second gate.
28. A PHP client without the SDK
Goal: another PHP application (a shop, a CRM) reads content.
final class ExponentialClient
{
public function __construct( private string $endpoint, private ?string $key = null, private ?string $siteaccess = null ) {}
public function query( string $query, array $variables = [] ): array
{
$headers = [ 'Content-Type: application/json', 'Accept-Language: en' ];
if ( $this->key !== null ) $headers[] = 'Authorization: Bearer ' . $this->key;
if ( $this->siteaccess !== null ) $headers[] = 'X-Siteaccess: ' . $this->siteaccess;
for ( $attempt = 1; ; $attempt++ )
{
$ch = curl_init( $this->endpoint );
curl_setopt_array( $ch, [ CURLOPT_POST => true, CURLOPT_HTTPHEADER => $headers, CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 30, CURLOPT_HEADER => true,
CURLOPT_POSTFIELDS => json_encode( [ 'query' => $query, 'variables' => (object)$variables ] ) ] );
$raw = curl_exec( $ch );
if ( $raw === false ) throw new RuntimeException( curl_error( $ch ) );
$status = curl_getinfo( $ch, CURLINFO_RESPONSE_CODE );
$head = substr( $raw, 0, curl_getinfo( $ch, CURLINFO_HEADER_SIZE ) );
$body = substr( $raw, curl_getinfo( $ch, CURLINFO_HEADER_SIZE ) );
if ( $status === 429 && $attempt < 3 && preg_match( '/^Retry-After:\s*(\d+)/mi', $head, $m ) )
{
sleep( min( 30, (int)$m[1] ) );
continue;
}
$answer = json_decode( $body, true );
if ( !is_array( $answer ) ) throw new RuntimeException( "HTTP $status" );
if ( !empty( $answer['errors'] ) )
throw new RuntimeException( $answer['errors'][0]['extensions']['code'] . ': ' . $answer['errors'][0]['message'] );
return $answer['data'];
}
}
}
$client = new ExponentialClient( 'https://www.example.com/api/graphql', getenv( 'EXPONENTIAL_API_KEY' ) ?: null, 'site' );
$data = $client->query( 'query($a: String!) { node(urlAlias: $a) { name url } }', [ 'a' => 'recipes' ] );
echo $data['node']['name'], "\n";29. A Python export script
Goal: export every recipe to a CSV file.
#!/usr/bin/env python3
import csv, os, sys, time
import requests
EXP = os.environ.get('EXP', 'https://www.example.com')
HEADERS = {'Content-Type': 'application/json'}
if os.environ.get('EXPONENTIAL_API_KEY'):
HEADERS['Authorization'] = 'Bearer ' + os.environ['EXPONENTIAL_API_KEY']
QUERY = '''query Recipes($after: String) {
children(parentId: 2, depth: 20, classes: ["ng_recipe"], first: 100, after: $after, sortField: NODE_ID) {
nodes { id remoteId name url published ... on ng_recipe { title } }
pageInfo { hasNextPage endCursor }
}
}'''
def graphql(query, variables):
for attempt in range(5):
r = requests.post(f'{EXP}/api/graphql', json={'query': query, 'variables': variables}, headers=HEADERS, timeout=30)
if r.status_code == 429:
time.sleep(int(r.headers.get('Retry-After', '5')))
continue
answer = r.json()
if answer.get('errors'):
sys.exit(f"{answer['errors'][0]['extensions']['code']}: {answer['errors'][0]['message']}")
return answer['data']
sys.exit('rate limited')
writer = csv.writer(sys.stdout)
writer.writerow(['id', 'remote_id', 'title', 'url', 'published'])
after = None
while True:
page = graphql(QUERY, {'after': after})['children']
for n in page['nodes']:
writer.writerow([n['id'], n['remoteId'], n.get('title') or n['name'], n['url'], n['published']])
if not page['pageInfo']['hasNextPage']:
break
after = page['pageInfo']['endCursor']EXP=https://www.example.com python3 export_recipes.py > recipes.csv30. Resilient clients: retries, timeouts and error handling
Goal: a client that survives rate limits, deploys and network blips, and fails clearly otherwise.
import {
createClient, apiKey, ExponentialGraphQLError, ExponentialRateLimitError, ExponentialShieldChallengeError,
ExponentialHttpError, ExponentialNetworkError, ExponentialTimeoutError,
} from '@exponentialcms/client';
export const client = createClient({
url: process.env.EXP!,
auth: apiKey(process.env.EXPONENTIAL_API_KEY!),
siteaccess: 'site',
timeoutMs: 10_000,
retry: { attempts: 4, baseDelayMs: 250, maxDelayMs: 8_000, retryMutations: false },
middleware: [{
onResponse: ({ status, headers, durationMs }) => { if (status >= 500) console.warn('exponential', status, durationMs, headers.get('X-Request-Id')); },
}],
});
export async function safeRequest<T>(query: string, variables?: Record<string, unknown>): Promise<T | null> {
try {
return await client.request<T>(query, variables);
} catch (e) {
if (e instanceof ExponentialGraphQLError) {
if (e.hasCode('NOT_FOUND')) return null;
if (e.hasCode('VALIDATION') || e.hasCode('PARSE')) throw new Error(`query does not fit the schema: ${e.message}`);
}
if (e instanceof ExponentialRateLimitError) throw new Error(`rate limited, retry in ${e.retryAfterMs} ms`);
if (e instanceof ExponentialShieldChallengeError) throw new Error('the request shield wants a browser check: exempt /api/**');
if (e instanceof ExponentialHttpError && e.status === 401) throw new Error('the API key is invalid, revoked or expired');
if (e instanceof ExponentialNetworkError || e instanceof ExponentialTimeoutError) throw new Error('Exponential is unreachable');
throw e;
}
}| Situation | Retry? |
|---|---|
429 with Retry-After | yes, after that many seconds |
502, 503, 504, network error, timeout | yes, with backoff, for queries |
401 | once after refreshing an OAuth token; never with a key |
400, PARSE, VALIDATION, BAD_USER_INPUT, FORBIDDEN, NOT_FOUND | no: fix the request or the rights |
INTERNAL | at most once; report the request id |
| a mutation | no, unless it is idempotent (an update to fixed values, a create with a remote id) |
Notes: the server's answer for every error carries extensions.requestId; log it with the error, and the operators
can find the request (Operations).
Related pages
- Start here and glossary · GraphQL API reference · Datatypes · Cache tags and invalidation · Events, webhooks and subscriptions
- The SDK: exponentialcms-client and the framework packages in the overview
- The starter projects:
./console exp:graphql:starter --list