Data fetching
Overview
createRoute() is the standard way to connect a route to the CMS. Point it at a collection, and it loads the matching doc for each URL and passes it to your component as props.doc.
It also takes care of the plumbing: loading drafts for ?preview=true URLs (which the CMS uses for live preview), resolving the request locale, loading translations, returning 404s for missing docs, and setting Cache-Control headers.
// @/routes/[...slug].tsx
import {createRoute} from '@blinkk/root-cms';
import {PagesDoc} from '@/root-cms.js';
export default function Page(props: {doc: PagesDoc}) {
return <h1>{props.doc.fields?.meta?.title}</h1>;
}
// Renders `Pages/<slug>`, e.g. `/about` renders `Pages/about` and `/`
// renders `Pages/index`.
export const {handle} = createRoute({
collection: 'Pages',
slugParam: 'slug',
});
For static sites (SSG), export getStaticProps and getStaticPaths instead to generate a page for every published doc in the collection:
export const {getStaticProps, getStaticPaths} = createRoute({
collection: 'BlogPosts',
ssg: true,
});
Route options
Most custom route behavior is handled through createRoute() options, so you rarely need to write a custom handler:
-
slug: sets the doc for a single-page route, like{slug: 'index'}inroutes/index.tsx. UseslugFormatorgetSlug(params)when a slug is built from multiple URL params. -
batchRequestandpreRenderHook: load extra content for the page and pass it as props (see Batch requests). -
translations: load additional translation sets, such as strings shared across every page (see Translations). -
resolveLocale: pick the locale yourself, such as from the user's country. -
resolveDoc: serve a different doc at the same URL, such as a regional variant. -
getMode: customize how draft vs. published mode is chosen. -
notFoundHook: render a custom page when the doc doesn't exist. -
preRenderHook: redirect usingprops.$redirect, or set an HTTP status withprops.$statusCode. -
cacheandcacheControl: cache published reads in memory for 60 seconds and set theCache-Controlheader on published responses.
See the @blinkk/root-cms API reference for the full list of options.
Batch requests
Each read from the CMS is a round trip to Firestore. A batch request bundles the reads a page needs so its docs, queries, and data sources are fetched in parallel. With the v2 translations manager, translations for every doc in the batch are fetched together for the page's locale only.
In createRoute(), add extra reads with the batchRequest option so they run alongside the route's main doc. The results are available on ctx.batchResponse in preRenderHook, where you can pass them to your page as props:
export const {handle} = createRoute({
collection: 'Pages',
slugParam: 'slug',
batchRequest: (req) => {
req.addDoc('Global/header');
req.addQuery('posts', 'BlogPosts', {limit: 3});
req.addDataSource('pricing');
},
preRenderHook: (props, ctx) => ({
...props,
header: ctx.batchResponse!.getDoc('Global/header'),
posts: ctx.batchResponse!.getQuery('posts'),
pricing: ctx.batchResponse!.getDataSource('pricing'),
}),
});
Read results using the IDs you registered: getDoc(docId) and getDataSource(id) return null if the item doesn't exist, and getQuery(queryId) returns an empty array when nothing matches.
Batch requests outside a route
In a custom handler, getStaticProps(), or a plugin, create a batch request with cmsClient.createBatchRequest(). With translate: true and the v2 translations manager, it also fetches translations for the returned docs in the locales you pass:
import {RootCMSClient} from '@blinkk/root-cms';
const cmsClient = new RootCMSClient(rootConfig);
const req = cmsClient.createBatchRequest({
mode: 'published',
translate: true,
locales: [locale],
});
req.addDoc('Pages/index');
req.addTranslations('common');
const res = await req.fetch();
const doc = res.getDoc('Pages/index');
const translations = res.getTranslations(locale);
If you need to inspect a doc before deciding which locale to load, fetch the content first and load translations afterward:
const res = await req.fetchContent();
const locale = pickLocale(res.getDoc('Pages/index'));
await req.fetchTranslations(res, {locales: [locale]});
Listing docs
To list docs in a collection, add a query with addQuery(). It accepts the same options as cmsClient.listDocs(): limit, offset, orderBy, orderByDirection, and query for Firestore filters.
// @/routes/blog/index.tsx, which renders `Pages/blog`.
export const {handle} = createRoute({
collection: 'Pages',
slug: 'blog',
batchRequest: (req, ctx) => {
req.addQuery('posts', 'BlogPosts', {
orderBy: ctx.mode === 'draft' ? 'sys.createdAt' : 'sys.firstPublishedAt',
orderByDirection: 'desc',
});
},
preRenderHook: (props, ctx) => ({
...props,
posts: ctx.batchResponse!.getQuery('posts'),
}),
});
Custom order
When a collection has customSorting: true, editors can drag docs into a custom order in the CMS. That order is stored at sys.sortKey:
req.addQuery('guides', 'Guides', {orderBy: 'sys.sortKey'});
Note that ordering by sys.sortKey excludes docs that don't have a sort key yet, such as docs created by a script.
Translations
createRoute() automatically loads translations for the page's locale: the doc's own strings plus any strings tagged common. With the v2 translations manager, it loads translations for referenced docs and batch-request docs instead of common. Inside components, translate strings with useTranslations():
import {useTranslations} from '@blinkk/root';
export default function Page(props: {doc: PagesDoc}) {
const t = useTranslations();
return <h1>{t(props.doc.fields?.meta?.title || '')}</h1>;
}
To load additional translation tags, like strings shared across every page, return them from the translations option:
createRoute({
collection: 'Pages',
translations: () => ({tags: ['common']}),
});
Outside a route, call cmsClient.loadTranslationsForLocale(locale, {tags: ['common']}). If you're using the v2 translations manager, use a batch request with translate: true and res.getTranslations(locale) instead (see Batch requests outside a route), since loadTranslations() and loadTranslationsForLocale() only read v1 translations.
Localized values
Available as of version 4.2.1.
CMS fields can store locale-specific overrides, which is handy when a field needs a different value per locale (like a localized hero image).
Overrides live in a sibling @<fieldId> metadata key next to the default value, inside a localizedValues map keyed by locale:
{
"hero": {
"title": "Build faster",
"image": {"src": "https://.../hero.png", "alt": "Hero"},
"@image": {
"localizedValues": {
"de": {"src": "https://.../hero-de.png", "alt": "Hero"},
"ja": null
}
}
}
}
An override replaces the field's entire value without merging, so the de entry above needs its own alt text. Setting an override to null clears the field for that locale (for example, to hide the image in ja). Locale matching is case-insensitive.
Overrides work on fields inside a doc's fields object, including nested objects, but not on array items (which don't have an @<fieldId> key) or fields inside rich text blocks.
Single-value fields are localizable by default: string, richtext, image, file, number, boolean, date, datetime, select, multiselect, reference, and references. Container fields (object, array, and oneof) aren't, because overriding them would duplicate all of their nested contents per locale. Set localizable on a field to change the default:
// @/collections/Pages.schema.ts
schema.string({id: 'legalText', localizable: false});
schema.object({id: 'promo', variant: 'inline', localizable: true, fields: [
// ...
]});
localizable has no effect on single-locale sites. Object fields rendered as drawers (the default variant) don't have a field header yet, so they can't be localized in the editor.
Resolving localized values
createRoute() resolves localized values automatically for both server-rendered and static routes. Once the locale is known, it swaps each field with its override across the route's doc and any docs or queries in its batch request, then strips out the localizedValues maps. translations(), preRenderHook(), and your page component all receive the resolved data.
Because resolveLocale() and resolveDoc() run before the locale is finalized, they receive the unresolved doc. If you want the raw data in your page (to resolve it yourself), pass localizedValues: false to createRoute().
Content fetched outside createRoute(), such as with cmsClient.getDoc() or inside getStaticProps(), isn't resolved automatically. Call resolveLocalizedValues() on a doc, an array of docs, or any nested object:
import {resolveLocalizedValues} from '@blinkk/root-cms';
const rawDoc = await cmsClient.getDoc('Pages', 'index', {mode: 'published'});
const doc = resolveLocalizedValues(rawDoc, 'de');
resolveLocalizedValues() returns a new object and never mutates its input, sharing unchanged subtrees rather than deep-cloning them. Pass keepLocalizedValues: true if you want to preserve the localizedValues maps in the output.
Localized values don't use i18n.fallbacks, which only applies to translations. If a locale doesn't have an override, it falls back to the field's default value even when a fallback locale has an override. createRoute() always resolves against the exact locale; with resolveLocalizedValues(), you can pass fallbacks to check other locales in order:
// Uses the en-CA override, then en-GB, then the default value.
const doc = resolveLocalizedValues(rawDoc, 'en-CA', {fallbacks: ['en-GB']});
Reading docs directly
For one-off reads, such as in a script, use RootCMSClient. Every read takes a mode: published for live content, or draft for the latest edits.
import {RootCMSClient} from '@blinkk/root-cms';
const cmsClient = new RootCMSClient(rootConfig);
const doc = await cmsClient.getDoc('Pages', 'index', {mode: 'published'});
const res = await cmsClient.listDocs('BlogPosts', {mode: 'published'});