Skip to content

fetchPage

The fetchPage function is useful when you want to retrieve the content of one page from outside the React context (where you could use the usePagePublic hook instead).

In particular, this comes in handy during the build process of a static website. This is the method used in React Bricks starter projects to retrieve page content outside React.

const fetchPage = async ({
slug,
language,
variantName,
config,
fetchOptions,
}: {
slug: string
language?: string
variantName?: string
config: types.ReactBricksConfig
fetchOptions?: types.FetchOptions
}): Promise<types.Page>
PropertyDefinition
slugThe slug of the page to fetch. Use / for the home page.
language?The language of the desired translation for the page, if more than one page shares the same slug.
variantName?The A/B Testing variant name to fetch. Use it with getAbTestingCookie to keep the served variant stable.
configThe React Bricks configuration object.
fetchOptions?Fetch options for React Bricks API calls. For example, pass Next.js fetch options or an apiPrefix for projects using a custom React Bricks API endpoint.

Older starters may use the positional signature:

fetchPage(slug, apiKey, language?, pageTypes?)

fetchPage returns a promise which resolves to a Page

Before using this page with ReactBricks’ PageViewer component, you need to parse it with the cleanPage function.

const page = await fetchPage({
slug: 'about-us',
language: 'en',
config,
})
const myPage = cleanPage(page, pageTypes, bricks)
console.log(myPage.content)

When a page uses A/B Testing, read the stable variant from the request cookies and pass it as variantName.

import { cookies } from 'next/headers'
import { fetchPage, getAbTestingCookie } from 'react-bricks/rsc'
const cookieStore = await cookies()
const variantName = getAbTestingCookie({
slug: cleanSlug,
locale,
cookieStore,
})
const page = await fetchPage({
slug: cleanSlug,
language: locale,
variantName,
config,
fetchOptions: { next: { revalidate: 3 } },
})