Render SitecoreAI content in your app
The framework-agnostic documentation is under development. If you have suggestions for improving the content, let us know by sharing your Feedback at the bottom of this page.
This walkthrough explains how to render SitecoreAI content in your front-end application, which is a key development task with Sitecore. By the end of the walkthrough, your front-end app will render SitecoreAI Page builder content in localhost.
The walkthrough provides code examples for Astro and Go front-end applications, and it describes how to:
- Configure your Sitecore environment variables
- Retrieve JSON-formatted layout data using GraphQL
- Set up page routing
- Build components
- Handle 404 pages
- Test your app
-
Complete the Create a SitecoreAI project with your own code walkthrough. This walkthrough builds directly on the app you built there.
-
Review content rendering concepts, including the GraphQL APIs, layout query and response, and field types.
-
Open your front-end project inside the
headapps/folder, such asastro-apporgo-app, in your code editor. -
During development, we recommend you test your GraphQL queries and inspect responses using the GraphQL IDE. This is particularly useful for building components in your front-end app.
Configure your Sitecore environment variables
A series of identifiers are needed to request the layout for a single page. It's best practice to pass these identifiers into the GraphQL layout request as variables. In Node-based applications, these are typically stored in a .env file, but you should use the appropriate method for the language and framework you are building with.
Secrets such as API keys, editing secrets, and Context IDs must never be hard-coded or exposed to the browser. It's best practice to store them in environment variables or a secrets manager instead.
To interact with the GraphQL APIs, we recommend creating a scoped Context ID for Edge to limit sensitive API access to server-side operations.
| Name | Description | Example |
|---|---|---|
SITECORE_EDGE_PLATFORM_URL | The Preview GraphQL API and Delivery GraphQL API endpoint. | Set the value to the following:https://edge-platform.sitecorecloud.io/v1/content/api/graphql/v1 |
SITECORE_EDGE_CONTEXT_ID | Your environment's Preview Context ID or Live Context ID. Find the value in SitecoreAI Deploy > Projects > your project > Authoring environments > your environment > Details. Use the Preview Context ID to access both unpublished (draft) and published content, recommended for local development. Use the Live Context ID to access only published content. | 0123456789abcdefghijkl |
SITECORE_SITE_NAME | Your site's system name. Find the value in SitecoreAI Deploy > Projects > your project > Authoring environments > your environment > Sites. | my-site |
SITECORE_SITE_LANGUAGE_CODE | Your site's language code. Find the value in SitecoreAI > Settings > Languages > Language code. Use a code for a language that your site is available in. You can check available languages by opening your site in the SitecoreAI Page builder and clicking the language dropdown in the top toolbar. |
|
Retrieve JSON-formatted layout data using GraphQL
After configuring your environment variables, you can start making GraphQL queries. In this step, you retrieve the layout data (page representation) for your site's root page so you can inspect the raw JSON that SitecoreAI sends to your app.
The following GraphQL query lets you retrieve layout data for a page:
This query requires that you specify the site the page belongs to, the language version of the page, and the path to the page.
Select your framework and follow the steps to make this query in your front-end app:
-
To create the query, create
src/services/sitecoreClient.jsand paste the following code:astro -
To make the query when the root page of your front-end app loads, replace the contents of
src/pages/index.astrowith the following code:astroWhen you open your project's root page in localhost, the page will make the GraphQL query and display the raw JSON that SitecoreAI returns.
-
Start your development server and open your project's home page in localhost. The raw JSON displays. This is the actual page layout data for the Home page in the SitecoreAI Page builder.
-
To create the query, create
sitecore.goand paste the following code:go -
To make the query when the root page of your front-end app loads, create
main.goand paste the following code:goWhen you open your project's root page in localhost, the page will make the GraphQL query and display the raw JSON that SitecoreAI returns.
-
Start your development server:
bash -
Open your project's home page in localhost, such as
http://localhost:3000/. The raw JSON displays. This is the actual page layout data for the Home page in the SitecoreAI Page builder.
The raw JSON looks similar to the following. For a full explanation of the response structure and how components are represented, see Layout query and response.
The structure of a component:
Set up page routing
Now that your app can retrieve layout data for a single path, you set up a catch-all route that retrieves layout data for any URL path and redirects to /404 when a path does not exist in Sitecore.
If you restart your development server, your front-end app in localhost will now render the raw JSON for the Home page (root), but it cannot render the JSON for other pages yet. You need to set up page routing to render all the URL paths of your site.
The Home page (root) corresponds to a single forward-slash /, so you must always include a leading forward-slash in your routes. For example, to route to the Home > Products page, use the /products route, including the forward-slash in the beginning of the string.
The routing code in this step uses a simple redirect to /404 for routes that do not exist in Sitecore. This is an intentional placeholder. You will replace it with a proper Sitecore-managed 404 page in a later procedure.
Dynamic routes in Astro require server rendering or using getStaticPaths(). This walkthrough uses server rendering via export const prerender = false;.
-
Create a catch-all route
src/pages/[...slug].astroand implement the routing logic:astro -
Restart your development server, and then check that a route different to the root, such as
/about, now displays raw JSON for that page.
-
Replace the contents of
main.gowith the following code to implement the routing logic:goYou will update this file in a later procedure to call
renderLayoutafter the layout component is in place. -
Restart your development server, and then check that a route different to the root, such as
/about, now displays raw JSON for that page.
Build components
Build a component mapping and a missing component fallback
Before you implement individual components, you need two foundations in place: a component mapping that connects Sitecore componentName strings to your component implementations, and a fallback component that handles any componentName that is not yet in the mapping.
The component mapping ensures that when the layout data contains a component named "RichText", your app renders the right implementation. The fallback component ensures unmapped components are immediately visible during development because it renders an error box showing the component name.
Adding a new component is always the same two-step pattern: implement the component, then add it to the map. Every component in this walkthrough follows this pattern.
When a componentName is not mapped in the component map, the Placeholder component renders the fallback instead of a real component. The fallback renders a visible, styled error box showing the component name. No nested placeholder children are rendered.
This makes missing components immediately visible during development so you know exactly which components still need to be implemented.
To make a missing component's content appear, implement the component so it renders its own fields, and then register it in the component map. After mapping, the real implementation replaces the error box.
To build a component mapping and a missing component fallback:
-
Create
src/components/componentMap.jsand paste the following code:astroYou will add entries to this map in later procedures as you implement components.
-
Create
src/components/MissingComponent.astroand paste the following code:astro
-
Create
components.goand paste the following code:goThe
strField,imgValue, andlnkValuefield helpers read typed values out of the layout data'sfieldsobject. You will use them when implementing component renderers in the next procedures.NoteThe examples in this walkthrough consolidate helper code and component renderers into a small number of files for clarity. In a production codebase, you would typically give each component its own file.
-
Create
missingComponent.goand paste the following code:go
Build the placeholder and page layout
With the component mapping and fallback in place, you can now build the Placeholder component and the page layout. The Placeholder component is the engine of the rendering pipeline: it takes a named placeholder slot and its array of components from the layout data, looks up each component in the mapping, and renders it. Because components can contain nested placeholders, Placeholder is called recursively throughout the page.
The page layout component connects the three top-level placeholders (headless-header, headless-main, headless-footer) to your Placeholder component and generates the final HTML page. All other placeholders on the page are rendered by the recursive Placeholder component.
After this step, your app routes all pages through the full rendering pipeline. Components won't display meaningful content yet because no component implementations are registered in the mapping. You'll implement components in the next procedures.
To build the placeholder and page layout:
-
Create
src/components/Placeholder.astroand paste the following code:astroThe
Placeholdercomponent takes a placeholder name and its component array, finds the right implementation for eachcomponentName, and then passes throughfields,params, andplaceholders. This enables child components to render their own nested placeholders. -
Create
src/components/Layout.astroand paste the following code:astro -
Update
src/pages/index.astroto render theLayoutcomponent instead of raw JSON:astro -
Update
src/pages/[...slug].astroto render theLayoutcomponent instead of raw JSON:astro
-
Create
placeholder.goand paste the following code:goThe
Placeholdercomponent takes a placeholder name and its component array, finds the right implementation for eachcomponentName, and then passes throughfields,params, andplaceholders. This enables child components to render their own nested placeholders. -
Create
Layout.goand paste the following code:go -
Update
main.goto callrenderLayoutinstead of rendering raw JSON:go
Implement built-in components
Components read their content from the fields object in the layout data. Each field has a type, and each type produces a different JSON shape. In this step, you implement three of the built-in Sitecore components: Title, RichText, and Image. Each component demonstrates reading and rendering one or more field types:
Title- renders a plain text field (heading). Example:{ "value": "Hello World" }RichText- renders a rich text field (Text). The value is HTML markup that must be injected as raw HTML, not escaped text. Example:{ "value": "<p>HTML content</p>" }Image- renders three fields that together make up the built-in Image component: an image field (Image), a plain text caption field (ImageCaption), and a General Link field (TargetUrl) that wraps the image in a link when set.
To implement built-in components:
-
Create the
Titlecomponent:astro -
Create the
RichTextcomponent:astro -
Create the
Imagecomponent:astro -
Register all three components in the component mapping by updating
src/components/componentMap.js:javascript
-
In
components.go, update the import block to add"fmt":go -
Add a render function for the
Titlecomponent:go -
Add a render function for the
RichTextcomponent:go -
Add a render function for the
Imagecomponent:go -
In
components.go, register all three components by adding the following entries tocomponentRegistry:go
Implement the Promo component
Promo componentPromo is a content component that renders rich text from one of several fields (PromoText, PromoText2, or PromoText3). It demonstrates how a component can fall back across multiple field names when looking for content to display.
To implement the Promo component:
-
Create the
Promocomponent:astro -
Register
Promoin the component mapping by updatingsrc/components/componentMap.jswith the following import and entry:javascript
-
In
components.go, add a render function for thePromocomponent:go -
Register
Promoby adding the following entry tocomponentRegistry:go
Implement the ColumnSplitter component
ColumnSplitter componentColumnSplitter is a structural component that manages nested placeholders rather than rendering its own field content. It splits its content area into columns and exposes each column as a named placeholder, allowing content authors to place other components inside each column. Implementing ColumnSplitter reinforces the recursive rendering concept established earlier in this walkthrough. The Placeholder component handles each column's contents, so any component registered in the component map can be nested inside a column.
To implement the ColumnSplitter component:
-
Create the
ColumnSplittercomponent:astro -
Register
ColumnSplitterin the component mapping by updatingsrc/components/componentMap.jswith the following import and entry:javascript
-
Create
columnsplitter.goand paste the following code:go -
In
components.go, registerColumnSplitterby adding the following entry tocomponentRegistry.Because
renderColumnSplittercallsrenderPlaceholder, which readscomponentRegistry, adding it to a map literal would create a Go initialization cycle and fail to compile. To avoid this, replace thecomponentRegistrydeclaration incomponents.gowith anilvariable declaration and aninit()function that populates the map at startup:go
Implement the Container and PartialDesignDynamicPlaceholder components
Container and PartialDesignDynamicPlaceholder componentsContainer and PartialDesignDynamicPlaceholder are structural components you will encounter on most Sitecore pages. Like ColumnSplitter, they render nested placeholder slots rather than field content.
Containerwraps a set of nested placeholders in a<div>element and accepts optional CSS class parameters (StylesorCssClass). Content authors use it to group and style sections of a page.PartialDesignDynamicPlaceholderis a transparent pass-through used by partial designs, which are reusable page sections that content authors configure in the Page builder and share across many pages. It renders all of its nested placeholder slots with no wrapper element.
To implement the Container and PartialDesignDynamicPlaceholder components:
-
Create the
Containercomponent:astro -
Create the
PartialDesignDynamicPlaceholdercomponent:astro -
Register both components in the component mapping by updating
src/components/componentMap.jswith the following imports and entries:javascript
-
Create
container.goand paste the following code:goNoteBecause both
renderContainerandrenderPartialDesignDynamicPlaceholdercallrenderPlaceholder, which readscomponentRegistry, they must be registered in theinit()function (see the next step), not in a map literal. Adding them to a map literal would create a Go initialization cycle and fail to compile. -
In
components.go, addContainerandPartialDesignDynamicPlaceholderto thecomponentRegistryin theinit()function:go
Handle 404 pages
When a site visitor navigates to a path that doesn't exist in Sitecore, the layout query returns null for layout.item. The routing code you set up in a previous procedure handles this as a fallback to /404. For a more complete implementation, you can render the Sitecore-managed 404 page instead of redirecting to a generic path.
To handle 404 pages:
- Retrieve the
notFoundPagePathandserverErrorPagePaththat content authors have configured in the Page builder. You can do this by using thesitequery'serrorHandlingfield. - Using the
fetchLayoutDatafunction, retrieve and render the layout data for the paths you retrieved in the previous step. - Return the response with an HTTP 404 status code so that browsers and search engines treat it correctly as a not-found response.
Test your app
You can now test your front-end app in localhost.
To test your app:
- Save all changes in your code editor and restart your development server.
- In localhost, navigate to the root route at
/to render your Home page. - Verify that Sitecore content is being rendered.
- Test your nested routes, such as
/productsandproducts/product-item-1.
Next steps
You've now rendered Sitecore content in your front-end app. Your app:
- Queries Sitecore for page data.
- Parses the recursive layout structure.
- Renders components based on layout data.
- Handles nested components and placeholders.
Next, you can:
- Continue building and mapping component implementations, such as
Accordion,Header,Footer, and your custom components so that everycomponentNamein layout data correctly renders its fields. As you build each component, make sure to handle its field types. - Style your front-end app using CSS or a CSS framework of your choice.
- For components that need data not included in the page layout, such as navigation menus, footer links, or listing data, make other GraphQL queries using the
item,search, orsiteentry points. Retrieve this data separately from thelayoutquery and pass the results into the relevant component. Keeping global data out of the per-page layout also improves publishing performance. - Learn more about the GraphQL APIs, including their differences, limitations, and best practices.