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.
Signature
Section titled “Signature”const fetchPage = async ({ slug, language, variantName, config, fetchOptions,}: { slug: string language?: string variantName?: string config: types.ReactBricksConfig fetchOptions?: types.FetchOptions}): Promise<types.Page>| Property | Definition |
|---|---|
slug | The 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. |
config | The 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?)Return value
Section titled “Return value”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.
Usage example
Section titled “Usage example”const page = await fetchPage({ slug: 'about-us', language: 'en', config,})
const myPage = cleanPage(page, pageTypes, bricks)console.log(myPage.content)Usage with A/B Testing
Section titled “Usage with A/B Testing”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 } },})