Data fetching
Overview
Routes read CMS content on the server with RootCMSClient, in getStaticProps() (SSG) or handle() (SSR). Create a client with the rootConfig from the request or context.
Every read takes a mode: published for live content, or draft for the latest edits. A common pattern is to read drafts when the URL has ?preview=true, which the CMS adds to its preview links.
// @/routes/[...page].tsx
import {Handler, HandlerContext} from '@blinkk/root';
import {RootCMSClient} from '@blinkk/root-cms';
export const handle: Handler = async (req, res) => {
const ctx = req.handlerContext as HandlerContext;
const slug = ctx.params.page;
const mode = String(req.query.preview) === 'true' ? 'draft' : 'published';
const cmsClient = new RootCMSClient(req.rootConfig);
const doc = await cmsClient.getDoc('Pages', slug, {mode});
if (!doc) {
return ctx.render404();
}
return ctx.render({slug, mode, doc});
};
Listing docs
To list the docs in a collection, use listDocs():
const cmsClient = new RootCMSClient(req.rootConfig);
const mode = String(req.query.preview) === 'true' ? 'draft' : 'published';
const orderBy = mode === 'draft' ? 'sys.createdAt' : 'sys.firstPublishedAt';
const blogPosts = await cmsClient.listDocs('BlogPosts', {
mode,
orderBy,
orderByDirection: 'desc',
});
Custom order
Collections with customSorting: true let editors drag docs into order in the CMS. The order is stored at sys.sortKey:
const res = await cmsClient.listDocs('Guides', {
mode,
orderBy: 'sys.sortKey',
});
Ordering by sys.sortKey leaves out docs that don't have a position yet, e.g. ones created by a script.
Translations
Translations for CMS content are tagged with the doc they belong to. Load them with loadTranslations(), then pass the ones for the current locale to ctx.render():
import {translationsForLocale} from '@blinkk/root-cms';
const translationsMap = await cmsClient.loadTranslations({
tags: ['common', `Pages/${slug}`],
});
const translations = translationsForLocale(translationsMap, locale);
return ctx.render({doc}, {locale, translations});