brease-client
The typed client for the delivery API. No dependencies; runs on Node 18+, edge runtimes, Deno, Bun and browsers.
pnpm add brease-clientIt reads BREASE_TOKEN from the environment and calls https://api.brease.io. BREASE_API_URL overrides that address, for example to point a site at a test environment; Brease sets it only there (see Connect a site).
API
import { createBrease } from 'brease-client'
const brease = createBrease({
token: process.env.BREASE_TOKEN, // default
apiUrl: process.env.BREASE_API_URL, // default; without it https://api.brease.io
commit: process.env.VERCEL_GIT_COMMIT_SHA, // default (or WORKERS_CI_COMMIT_SHA, CF_PAGES_COMMIT_SHA); false disables commit pinning
branch: process.env.VERCEL_GIT_COMMIT_REF, // default (or WORKERS_CI_BRANCH, CF_PAGES_BRANCH); only Brease draft branches (brease/draft/…) are sent
fetch, // optional custom fetch, e.g. to add framework cache options
retries: 2, // default: retries after 429, 5xx and network errors
retryBaseMs: 300, // default: backoff base, doubled per retry
timeoutMs: 5000 // default: per request; a timed-out request isn't retried
})
await brease.getSite() // name, url (the public address), locales, defaultLocale, localeStrategy, global SEO, analytics
await brease.getPage<Home>('', { locale: 'en' }) // Page<Home> | null ('' is the home page)
await brease.getPages({ locale: 'en' }) // [{ pageId, locale, slug, url, hidden, name, index, parentId, order, template }]
await brease.getPages({ locale: 'en', parentId: news.pageId, withContent: true }) // a news list, with each page's content
await brease.getPages({ locale: 'en', parentId: null }) // top-level pages only
await brease.getNavigation('main', { locale: 'en' }) // { key, locale, items } | null
await brease.getRedirects() // [{ source, destination, status }], cached for a minute
await brease.getRelease() // { id, number, commitSha, liveAt }: the release being served
await brease.resolve('/en/about') // { slug: 'about', locale: 'en' } | null
await brease.route(['en', 'about']) // the same from catch-all segments; null for "_" pages
await brease.routes() // [{ path: ['en', 'about'] }, …]: static params for every published page
await brease.localeContext(['en', 'about']) // { locale, settings, alternates, homes }
await brease.sitemap('https://example.com') // [{ url, alternates }]nullmeans 404. Every other failure throws aBreaseErrorwithstatus,code,requestIdanddetails.- 429 and 5xx responses and network errors are retried twice with backoff;
Retry-Afteris honoured (up to 10 seconds). A request that times out (5 seconds by default) isn't retried: keeptimeoutMsshort where a visitor waits on it, such as a proxy. - Commit pinning: the client sends the commit being built as
x-brease-commit(VERCEL_GIT_COMMIT_SHAon Vercel,WORKERS_CI_COMMIT_SHAon Cloudflare Workers Builds,CF_PAGES_COMMIT_SHAon Cloudflare Pages, all picked up automatically), so every deployment reads the content release that was built and tested with its code. On a Brease draft branch it also sends the branch, so later commits there (a developer's fix) still read the draft's content. See Publishing and caching. - Every response is the API's JSON; see the Delivery API for each shape.
getPages({ parentId, template, withContent })narrows the list to a page's children or one template.withContentadds each page's content (one locale, hidden pages left out, up to 100 pages): build news, team or job lists from it instead of fetching every page.site.urlis the site's public address (its primary domain), the one Brease uses in canonical URLs and hreflang. Use it for the sitemap andmetadataBase.getSite()andgetRedirects()are cached in memory for a minute, so a locale added in Brease is served without a restart. The revalidate route clears that cache on a publish (clearBreaseCache()does the same by hand), but only in the server instance that received the call; other instances catch up within the minute. While Brease can't be reached, the last good value is served. The editor's preview never caches it.getRelease()throws aBreaseErrorwith status 404 until the site's first release is published.sitemap()lists only pages search may show: not hidden, not kept out of search and no site-wide_pages. It has nolastModified: releases are snapshots and don't track per-page edit times.- Keep the token on the server: anyone holding it can also read draft content of a known commit or draft branch.
buildPath(settings, slug, locale)andresolvePath(settings, pathname)are exported for routing code that already has the site settings.
Next.js (App Router)
import { createBrease } from 'brease-client'
import { breaseFetch } from 'brease-client/next'
export const brease = createBrease({ fetch: breaseFetch() }) // tags requests with 'brease'import { notFound } from 'next/navigation'
import { toMetadata } from 'brease-client/next'
import { brease } from '@/lib/brease'
export const revalidate = 60
type Props = { params: Promise<{ slug?: string[] }> }
async function load(params: Props['params']) {
const { slug = [] } = await params
const target = await brease.resolve(`/${slug.join('/')}`)
return target ? brease.getPage<{ hero: { title: string } }>(target.slug, { locale: target.locale }) : null
}
export async function generateStaticParams() {
// The build goes on without pre-rendered pages if the content API has a hiccup; pages then render on first request.
try {
return (await brease.routes()).map((r) => ({ slug: r.path })) // published pages, without site-wide "_" pages
} catch (err) {
console.warn(`Brease pages unavailable at build time: ${(err as Error).message}`)
return []
}
}
export async function generateMetadata({ params }: Props) {
const page = await load(params)
return page ? toMetadata(page.resolvedSeo) : {}
}
export default async function Page({ params }: Props) {
const page = await load(params)
if (!page) notFound()
return <h1 data-brease="hero.title">{page.content.hero.title}</h1>
}import { revalidateHandler } from 'brease-client/next'
export const POST = revalidateHandler() // uses BREASE_REVALIDATE_SECRETRedirects managed in Brease apply per request, so a new one works as soon as it's published (within a minute), with no rebuild:
import { type NextRequest, NextResponse } from 'next/server'
import { matchRedirect } from 'brease-client'
import { brease } from '@/lib/brease'
export async function proxy(req: NextRequest) {
const hit = matchRedirect(await brease.getRedirects().catch(() => []), req.nextUrl.pathname)
return hit ? NextResponse.redirect(new URL(hit.destination, req.url), hit.status) : NextResponse.next()
}
export const config = { matcher: ['/((?!_next|api|.*\\..*).*)'] }breaseRedirects() (for next.config) still works, but only reads redirects at build time.
route() also resolves other forms of a page's URL (/en/about where English has no prefix). To redirect those to the canonical URL too, add this to the same proxy, before NextResponse.next(). Keep it in the try, so the page still loads when Brease can't be reached:
import { canonicalPath } from 'brease-client'
try {
const canonical = canonicalPath(await brease.getSite(), req.nextUrl.pathname)
if (canonical && (await brease.getPages()).some((p) => p.url === canonical))
return NextResponse.redirect(new URL(canonical + req.nextUrl.search, req.url), 308)
} catch {}For a site with more than one locale, use the recommended structure instead of the route above.
Astro
import { createBrease } from 'brease-client'
export const brease = createBrease({ token: import.meta.env.BREASE_TOKEN, apiUrl: import.meta.env.BREASE_API_URL })---
import { breaseHead } from 'brease-client/astro'
import { brease } from '../lib/brease'
// Static output builds one file per published page in every locale. getStaticPaths can only use imports, so the
// client lives in its own module.
export async function getStaticPaths() {
return (await brease.routes()).map(({ path }) => ({ params: { path: path.join('/') || undefined } }))
}
const route = await brease.route(Astro.params.path)
const page = route && (await brease.getPage(route.slug, { locale: route.locale }))
if (!page) return new Response(null, { status: 404 })
---
<html lang={page.locale}>
<head><Fragment set:html={breaseHead(page.resolvedSeo)} /></head>
<body><h1 data-brease="hero.title">{page.content.hero.title}</h1></body>
</html>headTagList(seo) returns the same tags as { tag, attrs, content } objects.
Plain HTML and other servers
import { headTags } from 'brease-client/html'
const html = `<head>${headTags(page.resolvedSeo, { xDefault: 'https://example.com/' })}</head>`customHead and customCode from the SEO settings are inserted as raw HTML (the site's team writes them). Pass { includeCustom: false } to leave them out.
Structured data (JSON-LD)
The page's structured data (the site's defaults, then the page's own) comes in resolvedSeo.structuredData. jsonLd returns each item with its JSON already escaped for a script tag, and works with any framework:
import { jsonLd } from 'brease-client'
{jsonLd(page.resolvedSeo).map((item, i) => (
<script key={i} type="application/ld+json" dangerouslySetInnerHTML={{ __html: item.json }} />
))}toMetadata can't output scripts, so Next.js sites need this to show structured data. headTags and breaseHead already include it for HTML and Astro; jsonLdHtml(seo) returns only the script tags. Requires brease-client 0.7.1.
Custom code
Site-wide head code and a page's own code (both set in Brease's SEO settings) run on the live site only when the site renders them. toMetadata can't, so render customTags(page.resolvedSeo) as real elements:
import { customTags } from 'brease-client'
{customTags(page.resolvedSeo).map(({ tag: Tag, attrs, content }, i) => {
const props = Object.fromEntries(Object.entries(attrs).map(([k, v]) => [k, v === '' ? true : v]))
return content ? <Tag key={i} {...props} dangerouslySetInnerHTML={{ __html: content }} /> : <Tag key={i} {...props} />
})}Only script, style, meta, link and noscript tags are kept. headTags and breaseHead include the code already. Requires brease-client 0.8.
Google Analytics (GA4)
When GA4 is linked in Brease with Add the GA4 tag to the site on, getSite() returns its measurement id in analytics.ga4 (null when the tag is off). Render it once in the root layout; turning it on or off in Brease then needs no deploy.
import Script from 'next/script'
import { ga4Tag } from 'brease-client'
import { brease } from '@/lib/brease'
export default async function RootLayout({ children }: { children: React.ReactNode }) {
const ga = ga4Tag(await brease.getSite())
return (
<html>
<body>
{children}
{ga && (
<>
<Script src={ga.src} strategy="afterInteractive" />
<Script id="brease-ga4" strategy="afterInteractive">
{ga.inline}
</Script>
</>
)}
</body>
</html>
)
}For Astro or plain HTML, put ga4Html(site) in the <head>; it returns an empty string while the tag is off.
Consent mode starts with every storage type denied, so GA4 stores nothing until your cookie banner calls grantAnalytics(). Call grantAnalytics(false) when a visitor withdraws consent. Without a banner, GA4 only receives cookieless pings.
import { grantAnalytics } from 'brease-client'
acceptButton.onclick = () => grantAnalytics()Requires brease-client 0.7.
Images
import { imageProps } from 'brease-client/image'
const props = imageProps(page.content.hero.image)
// <img src={props.src} alt={props.alt} width={props.width} height={props.height} />An image field is { assetId, url, alt, width?, height? }; imageProps takes the field or a plain URL. Brease serves files as they are, without resizing, so the helper returns the URL unchanged, without srcSet or sizes (srcset() and the resize options are deprecated and do nothing). For responsive images let your framework resize them, e.g. next/image with the asset host in images.remotePatterns.