Skip to content
All posts

Typed content queries in TypeScript

A small pattern for fetching CMS content with typed queries, build-time caching and a safe local fallback.

Matt Claffey · 1 min read

Headless CMS integrations tend to start as a fetch call in a page component and end as a tangle of untyped JSON spread across the codebase. A small, boring pattern avoids that.

One client, no SDK

Keep a single tiny client that knows how to talk to the GraphQL endpoint and nothing else: build the URL, send the query and variables, throw on HTTP errors and GraphQL errors. It's a few dozen lines with plain fetch, and it means every content request in the app fails the same way.

One module per content type

Put each query in a module next to the type it returns:

export interface HomepageContent {
  heroHeading: string;
  heroBody: string;
  primaryCtaLabel: string;
  primaryCtaUrl: string;
}

export function getHomepage(): Promise<HomepageContent> {
  cached ??= fetchHomepage();
  return cached;
}

Components import getHomepage() and get a typed object. They never see GraphQL, endpoints or tokens.

Cache the promise once per build

On a statically generated site, several components might ask for the same content during one build. Caching the promise, not the result, means only one request goes out even if the calls happen at the same time.

Fail loudly, fall back deliberately

Two cases, two behaviours:

  • Credentials missing: return local JSON from the repo so a fresh checkout or a contributor without access can still build.
  • Credentials present but the request fails: throw and fail the build. Shipping stale or empty content silently is worse than a red build.

Normalise at the edge

CMS fields are nullable in GraphQL even when they're required in the editor. Convert raw responses into your own types in one place, skip entries that are missing required fields, and drop values you don't recognise, like an unknown tag, with a build warning. The rest of the app can then trust its types.