---
title: "Render SitecoreAI content in your app"
slug: "render-sitecoreai-content-in-your-app"
abstract: "How to render SitecoreAI content in your front-end web application without using any framework-specific Sitecore SDKs."
---
# Render SitecoreAI content in your app

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 on localhost.

The walkthrough provides code examples for Astro 7 and Go front-end applications, and it describes how to:

:::walkthrough
1. [Configure your Sitecore environment variables](https://doc.sitecore.com/sai/en/developers/sitecoreai/introduction-to-framework-agnostic-sitecore-development/content-rendering/render-sitecoreai-content-in-your-app.html#configure-your-sitecore-environment-variables)
2. [Retrieve JSON-formatted layout data using GraphQL](https://doc.sitecore.com/sai/en/developers/sitecoreai/introduction-to-framework-agnostic-sitecore-development/content-rendering/render-sitecoreai-content-in-your-app.html#retrieve-json-formatted-layout-data-using-graphql)
3. [Set up page routing](https://doc.sitecore.com/sai/en/developers/sitecoreai/introduction-to-framework-agnostic-sitecore-development/content-rendering/render-sitecoreai-content-in-your-app.html#set-up-page-routing)
4. [Build components](https://doc.sitecore.com/sai/en/developers/sitecoreai/introduction-to-framework-agnostic-sitecore-development/content-rendering/render-sitecoreai-content-in-your-app.html#build-components)
5. [Handle 404 pages](https://doc.sitecore.com/sai/en/developers/sitecoreai/introduction-to-framework-agnostic-sitecore-development/content-rendering/render-sitecoreai-content-in-your-app.html#handle-404-pages)
6. [Test your app](https://doc.sitecore.com/sai/en/developers/sitecoreai/introduction-to-framework-agnostic-sitecore-development/content-rendering/render-sitecoreai-content-in-your-app.html#test-your-app)
:::

> [!note]
> **Before you begin**
> -   Complete the [Create a SitecoreAI project with your own code](https://doc.sitecore.com/sai/en/developers/sitecoreai/introduction-to-framework-agnostic-sitecore-development/create-a-sitecoreai-project-with-your-own-code.html "Create a SitecoreAI project with your own code") walkthrough. This walkthrough builds directly on the app you built there.
>
> -   Review [content rendering](https://doc.sitecore.com/sai/en/developers/sitecoreai/introduction-to-framework-agnostic-sitecore-development/content-rendering.html "Content rendering") concepts, including the [GraphQL APIs](https://doc.sitecore.com/sai/en/developers/sitecoreai/introduction-to-framework-agnostic-sitecore-development/content-rendering/the-preview-and-delivery-graphql-apis.html "The Preview and Delivery GraphQL APIs"), [layout query and response](https://doc.sitecore.com/sai/en/developers/sitecoreai/introduction-to-framework-agnostic-sitecore-development/content-rendering/layout-query-and-response.html "Layout query and response"), and [field types](https://doc.sitecore.com/sai/en/developers/sitecoreai/introduction-to-framework-agnostic-sitecore-development/content-rendering/field-types-in-rendering-data.html "Field types in rendering data").
>
> -   Open your front-end project inside the `headapps/` folder, such as `astro-app` or `go-app`, in your code editor.
>
> -   During development, we recommend you test your GraphQL queries and inspect responses using the [GraphQL IDE](https://doc.sitecore.com/sai/en/developers/sitecoreai/experience-edge/experience-edge-apis/set-up-the-graphql-ides.html "Set up the GraphQL IDEs"). This is particularly useful for building components in your front-end app.

## Configure your Sitecore environment variables

Several 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.

> [!important]
> Secrets such as API keys, editing secrets, and Context IDs must never be hard-coded or [exposed to the browser](https://doc.sitecore.com/sai/en/developers/sitecoreai/experience-edge/experience-edge-best-practices.html#avoid-exposing-your-context-id-to-the-browser "Avoid exposing your Context ID 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](https://doc.sitecore.com/portal/en/developers/sitecore-cloud-portal/manage-scoped-context-ids.html#create-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:<br><br>`https://edge-platform.sitecorecloud.io/v1/content/api/graphql/v1` |
| `SITECORE_EDGE_CONTEXT_ID` | Your environment's Preview Context ID or Live Context ID.<br><br>Find the value in SitecoreAI Deploy > **Projects** > your project > **Authoring environments** > your environment > **Details**.<br><br>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.<br><br>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**.<br><br>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. | <ul><li>`en`</li><li>`de-DE`</li><li>`ja-JP`</li></ul> |

## 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:

```graphql
query LayoutQuery($site: String!, $language: String!, $routePath: String!) {
  layout(site: $site, language: $language, routePath: $routePath) {
    item {
      rendered # Returns layout data
    }
  }
}
```

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:

::::tabs
:::tab{title="Astro"}

1. To create the query, create `src/services/sitecoreClient.js` and paste the following code:

    ```js
    // src/services/sitecoreClient.js

    export async function fetchLayoutData(site, language, routePath) {
      const env = import.meta.env;

      const endpoint = env.SITECORE_EDGE_PLATFORM_URL;
      const contextId = env.SITECORE_EDGE_CONTEXT_ID;

      // Create the GraphQL query:
      const query = `
        query LayoutQuery($site: String!, $language: String!, $routePath: String!) {
          layout(site: $site, language: $language, routePath: $routePath) {
            item { rendered }
          }
        }
      `;

      const variables = {
        site,
        language,
        routePath,
      };

      /* Optionally, add if-statements to check for missing environment variables. */

      // Include the Context ID in the header:
      const headers = {
        "Content-Type": "application/json",
        "x-sitecore-contextid": contextId,
      };

      // Make the GraphQL request:
      const response = await fetch(endpoint, {
        method: "POST",
        headers,
        body: JSON.stringify({ query, variables }),
      });

      const result = await response.json();

      if (result.errors) {
        throw new Error(JSON.stringify(result.errors));
      }

      const rendered = result?.data?.layout?.item?.rendered;
      return typeof rendered === "string" ? JSON.parse(rendered) : rendered;
    }
    ```

2. To make the query when the root page of your front-end app loads, replace the contents of `src/pages/index.astro` with the following code:

    ```astro
    ---
    // src/pages/index.astro
    import { fetchLayoutData } from "../services/sitecoreClient.js";

    const site = import.meta.env.SITECORE_SITE_NAME;
    const language = import.meta.env.SITECORE_SITE_LANGUAGE_CODE || "en";
    const routePath = "/";
    const layoutData = await fetchLayoutData(site, language, routePath);
    ---

    <pre>{JSON.stringify(layoutData, null, 2)}</pre>
    ```

    When you open your project's root page on localhost, the page will make the GraphQL query and display the raw JSON that SitecoreAI returns.

  3. Start your development server and open your project's home page on localhost. The raw JSON displays. This is the actual page layout data for the **Home** page in the SitecoreAI Page builder.
:::
:::tab{title="Go"}

1. To create the query, create `sitecore.go` and paste the following code:

    ```go
    // sitecore.go
    package main

    import (
        "bytes"
        "encoding/json"
        "fmt"
        "net/http"
        "os"
    )

    const layoutQuery = `
    query LayoutQuery($site: String!, $language: String!, $routePath: String!) {
      layout(site: $site, language: $language, routePath: $routePath) {
        item { rendered }
      }
    }`

    // layoutResponse is the top-level shape of a GraphQL layout query response.
    type layoutResponse struct {
        Data struct {
            Layout struct {
                Item *struct {
                    Rendered json.RawMessage `json:"rendered"`
                } `json:"item"`
            } `json:"layout"`
        } `json:"data"`
        Errors []struct {
            Message string `json:"message"`
        } `json:"errors"`
    }

    // fetchLayoutData retrieves the Sitecore layout snapshot
    // for the given site name, language, and route path.
    // Returns (nil, nil) when the route does not exist in Sitecore.
    func fetchLayoutData(site, language, routePath string) (map[string]any, error) {
        endpoint := os.Getenv("SITECORE_EDGE_PLATFORM_URL")
        contextID := os.Getenv("SITECORE_EDGE_CONTEXT_ID")

        payload, err := json.Marshal(map[string]any{
            "query": layoutQuery,
            "variables": map[string]any{
                "site": site, "language": language, "routePath": routePath,
            },
        })
        if err != nil {
            return nil, fmt.Errorf("marshal: %w", err)
        }

        req, err := http.NewRequest(http.MethodPost, endpoint, bytes.NewReader(payload))
        if err != nil {
            return nil, fmt.Errorf("new request: %w", err)
        }
        req.Header.Set("Content-Type", "application/json")
        req.Header.Set("x-sitecore-contextid", contextID)

        resp, err := http.DefaultClient.Do(req)
        if err != nil {
            return nil, fmt.Errorf("edge request: %w", err)
        }
        defer resp.Body.Close()

        var gql layoutResponse
        if err := json.NewDecoder(resp.Body).Decode(&gql); err != nil {
            return nil, fmt.Errorf("decode: %w", err)
        }
        if len(gql.Errors) > 0 {
            return nil, fmt.Errorf("graphql: %s", gql.Errors[0].Message)
        }
        if gql.Data.Layout.Item == nil {
            return nil, nil // route does not exist in Sitecore
        }

        // `rendered` can arrive as a JSON object or a JSON-encoded string.
        raw := gql.Data.Layout.Item.Rendered
        var out map[string]any
        if json.Unmarshal(raw, &out) == nil {
            return out, nil
        }
        // Fall back: rendered was a quoted string - decode and re-parse it.
        var s string
        if json.Unmarshal(raw, &s) != nil {
            return nil, fmt.Errorf("cannot parse rendered field")
        }
        if err := json.Unmarshal([]byte(s), &out); err != nil {
            return nil, fmt.Errorf("cannot parse rendered string: %w", err)
        }
        return out, nil
    }
    ```

2. To make the query when the root page of your front-end app loads, create `main.go` and paste the following code:

    ```go
    // main.go
    package main

    import (
        "encoding/json"
        "fmt"
        "log"
        "net/http"
        "os"
        "github.com/joho/godotenv"
    )

    func main() {
        // Load .env file if present (ignored when not found, e.g. in production).
        _ = godotenv.Load()

        http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
            site := os.Getenv("SITECORE_SITE_NAME")
            language := os.Getenv("SITECORE_SITE_LANGUAGE_CODE")
            if language == "" {
                language = "en"
            }

            data, err := fetchLayoutData(site, language, "/")
            if err != nil {
                http.Error(w, err.Error(), http.StatusInternalServerError)
                return
            }

            pretty, err := json.MarshalIndent(data, "", "  ")
            if err != nil {
                http.Error(w, err.Error(), http.StatusInternalServerError)
                return
            }
            w.Header().Set("Content-Type", "text/plain; charset=utf-8")
            fmt.Fprint(w, string(pretty))
        })

        log.Println("Listening on http://localhost:3000")
        log.Fatal(http.ListenAndServe(":3000", nil))
    }
    ```

    When you open your project's root page on localhost, the page will make the GraphQL query and display the raw JSON that SitecoreAI returns.

3. Start your development server:

    ```bash
    go run .
    ```

4. Open your project's home page on 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](https://doc.sitecore.com/sai/en/developers/sitecoreai/introduction-to-framework-agnostic-sitecore-development/content-rendering/layout-query-and-response.html "Layout query and response").
:::
::::

```json
{
  "sitecore": {
    "context": { /* metadata */ },
    "route": {
      "name": "Home",
      "displayName": "Home",
      "fields": {
        /* Page-level content fields (title, summary, thumbnail, keywords, navigation information, etc.) */
      },
      "placeholders": {
        "headless-header": [ /* Array of components for page header */ ],
        "headless-main": [ /* Array of components for page main section */ ],
        "headless-footer": [ /* Array of components for page footer */ ]
      }
    }
  }
}
```

The structure of a component:

```json
{
  "uid": "<UNIQUE_COMPONENT_ID>",
  "componentName": "<COMPONENT_NAME>",
  "dataSource": "<DATA_SOURCE_PATH>",
  "params": { /* Display parameters (styles, modes) */ },
  "fields": { /* Content data for this component */ },
  "placeholders": {
    /* Nested child components (recursive structure) */
    "nested-placeholder-name": [ /* More components */ ]
  }
}
```

## 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 on 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.

> [!note]
> 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 at 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.

::::tabs
:::tab{title="Astro"}

Dynamic routes in Astro require either server rendering or `getStaticPaths()`. This walkthrough uses server rendering via `export const prerender = false;`.

1. Create a catch-all route `src/pages/[...slug].astro` and implement the routing logic:

    ```astro
    ---
    // src/pages/[...slug].astro
    import { fetchLayoutData } from '../services/sitecoreClient.js';

    export const prerender = false;

    const site = import.meta.env.SITECORE_SITE_NAME;
    const language = import.meta.env.SITECORE_SITE_LANGUAGE_CODE || "en";
    const { slug } = Astro.params;
    const routePath = slug ? `/${slug}` : '/';

    let layoutData;
    try {
      layoutData = await fetchLayoutData(site, language, routePath);
    } catch (error) {
      return Astro.redirect('/404');
    }

    if (!layoutData) {
      return Astro.redirect('/404');
    }
    ---

    <pre>{JSON.stringify(layoutData, null, 2)}</pre>
    ```

2. Restart your development server, and then check that a route different from the root, such as `/about`, now displays raw JSON for that page.

:::
:::tab{title="Go"}

1. Replace the contents of `main.go` with the following code to implement the routing logic:

    ```go
    // main.go
    package main

    import (
        "encoding/json"
        "fmt"
        "log"
        "net/http"
        "os"
        "strings"
        "github.com/joho/godotenv"
    )

    func main() {
        // Load .env file if present (ignored when not found, e.g. in production).
        _ = godotenv.Load()

        site := os.Getenv("SITECORE_SITE_NAME")
        language := os.Getenv("SITECORE_SITE_LANGUAGE_CODE")
        if language == "" {
            language = "en"
        }

        http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
            // Derive the Sitecore route path from the URL. Keep root "/" as-is;
            // trim any trailing slash from other paths.
            routePath := r.URL.Path
            if routePath != "/" {
                routePath = strings.TrimRight(routePath, "/")
            }

            data, err := fetchLayoutData(site, language, routePath)
            if err != nil {
                http.Error(w, err.Error(), http.StatusInternalServerError)
                return
            }
            if data == nil {
                // Route does not exist in Sitecore.
                if routePath == "/404" {
                    // Sitecore 404 page is not configured; serve a minimal fallback.
                    http.NotFound(w, r)
                    return
                }
                http.Redirect(w, r, "/404", http.StatusFound)
                return
            }

            pretty, err := json.MarshalIndent(data, "", "  ")
            if err != nil {
                http.Error(w, err.Error(), http.StatusInternalServerError)
                return
            }
            w.Header().Set("Content-Type", "text/plain; charset=utf-8")
            fmt.Fprint(w, string(pretty))
        })

        log.Println("Listening on http://localhost:3000")
        log.Fatal(http.ListenAndServe(":3000", nil))
    }
    ```

    You will update this file in a later procedure to call `renderLayout` after the layout component is in place.

2. Restart your development server, and then check that a route different from 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.

> [!note]
> **Handling missing content**
> 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:

::::tabs
:::tab{title="Astro"}

1. Create `src/components/componentMap.js` and paste the following code:

    ```js
    // src/components/componentMap.js
    // Import your component implementations here, then add them to the map.

    export const componentMap = {
      // Register component implementations here as you build them.
      // Example: 'ComponentName': ComponentImplementation
    };
    ```

    You will add entries to this map in later procedures as you implement components.

2. Create `src/components/MissingComponent.astro` and paste the following code:

    ```astro
    ---
    // src/components/MissingComponent.astro

    const { componentName } = Astro.props;
    ---

    <div style="background: darkorange; outline: 5px solid orange; padding: 10px; color: white; max-width: 500px;">
      <h2>{componentName}</h2>
      <p>Component is not implemented. Add an implementation and register it in the component map.</p>
    </div>
    ```

:::
:::tab{title="Go"}

1. Create `components.go` and paste the following code:

    ```go
    // components.go
    package main

    import "html/template"

    // ComponentFunc is the signature every component renderer must satisfy.
    type ComponentFunc func(fields, params map[string]any, placeholders map[string][]any) template.HTML

    // componentRegistry maps Sitecore componentName values to their Go render
    // functions. Add an entry here whenever you implement a new component.
    var componentRegistry map[string]ComponentFunc

    func init() {
        componentRegistry = map[string]ComponentFunc{
            // Register component implementations here as you build them.
        }
    }

    // field helpers

    // strField reads the "value" string of a plain-text or rich-text field.
    func strField(fields map[string]any, name string) string {
        f, _ := fields[name].(map[string]any)
        v, _ := f["value"].(string)
        return v
    }

    // imgValue reads an Image field's value object, with jsonValue as a fallback
    // for direct item queries.
    func imgValue(fields map[string]any, name string) map[string]any {
        f, _ := fields[name].(map[string]any)
        if v, ok := f["value"].(map[string]any); ok {
            return v
        }
        if jv, ok := f["jsonValue"].(map[string]any); ok {
            v, _ := jv["value"].(map[string]any)
            return v
        }
        return nil
    }

    // lnkValue reads a General Link field's value object, with jsonValue fallback.
    func lnkValue(fields map[string]any, name string) map[string]any {
        f, _ := fields[name].(map[string]any)
        if v, ok := f["value"].(map[string]any); ok {
            return v
        }
        if jv, ok := f["jsonValue"].(map[string]any); ok {
            v, _ := jv["value"].(map[string]any)
            return v
        }
        return nil
    }

    // ms reads a string value from any map[string]any by key.
    func ms(m map[string]any, key string) string {
        v, _ := m[key].(string)
        return v
    }

    func esc(s string) string { return template.HTMLEscapeString(s) }
    ```

    The `strField`, `imgValue`, and `lnkValue` field helpers read typed values out of the layout data's `fields` object. You will use them when implementing component renderers in the next procedures.

    > [!note]
    > The 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.

2. Create `missingComponent.go` and paste the following code:

    ```go
    // missingComponent.go
    package main

    import (
        "fmt"
        "html/template"
    )

    func renderMissingComponent(componentName string, _ map[string][]any) template.HTML {
        return template.HTML(fmt.Sprintf(
            `<div style="background:darkorange;outline:5px solid orange;padding:10px;color:white;max-width:500px"><h2>%s</h2><p>Component is not implemented. Add an implementation and register it in the component map.</p></div>`,
            template.HTMLEscapeString(componentName),
        ))
    }
    ```
:::
::::

### 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:

::::tabs
:::tab{title="Astro"}

1. Create `src/components/Placeholder.astro` and paste the following code:

    ```astro
    ---
    // src/components/Placeholder.astro
    import { componentMap } from './componentMap.js';
    import MissingComponent from './MissingComponent.astro';

    const { name, rendering } = Astro.props;
    // Type casts are needed because the component map is keyed dynamically
    // and rendering items are untyped layout data.
    const map = componentMap as Record<string, any>;
    const items: any[] = rendering ?? [];
    ---

    <div data-placeholder={name}>
      {items.map((component) => {
        const Component = map[component.componentName] ?? MissingComponent;

        return (
          <Component
            componentName={component.componentName}
            fields={component.fields}
            params={component.params}
            placeholders={component.placeholders}
          />
        );
      })}
    </div>
    ```

    The `Placeholder` component takes a placeholder name and its component array, finds the right implementation for each `componentName`, and then passes through `fields`, `params`, and `placeholders`. This enables child components to render their own nested placeholders.

2. Create `src/components/Layout.astro` and paste the following code:

    ```astro
    ---
    // src/components/Layout.astro
    import Placeholder from './Placeholder.astro';

    interface Props {
      layoutData: any;
    }

    const { layoutData } = Astro.props;
    const route = layoutData?.sitecore?.route;
    const placeholders = route?.placeholders || {};
    ---

    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>{route.displayName || route.name}</title>
    </head>
    <body>
      {route ? (
        <>
          <header>
            <Placeholder
              name="headless-header"
              rendering={placeholders['headless-header']}
            />
          </header>

          <main>
            <Placeholder
              name="headless-main"
              rendering={placeholders['headless-main']}
            />
          </main>

          <footer>
            <Placeholder
              name="headless-footer"
              rendering={placeholders['headless-footer']}
            />
          </footer>
        </>
      ) : (
        <main>
          <p>Layout data is missing for this route.</p>
        </main>
      )}
    </body>
    </html>
    ```

3. Update `src/pages/index.astro` to render the `Layout` component instead of raw JSON:

    ```astro
    ---
    // src/pages/index.astro
    import SitecoreLayout from '../components/Layout.astro';
    import { fetchLayoutData } from '../services/sitecoreClient.js';

    const site = import.meta.env.SITECORE_SITE_NAME;
    const language = import.meta.env.SITECORE_SITE_LANGUAGE_CODE || "en";
    const routePath = "/";
    const layoutData = await fetchLayoutData(site, language, routePath);
    ---

    <SitecoreLayout layoutData={layoutData} />
    ```

4. Update `src/pages/[...slug].astro` to render the `Layout` component instead of raw JSON:

    ```astro
    ---
    // src/pages/[...slug].astro
    import { fetchLayoutData } from '../services/sitecoreClient.js';
    import SitecoreLayout from '../components/Layout.astro';

    export const prerender = false;

    const site = import.meta.env.SITECORE_SITE_NAME;
    const language = import.meta.env.SITECORE_SITE_LANGUAGE_CODE || "en";
    const { slug } = Astro.params;
    const routePath = slug ? `/${slug}` : '/';

    let layoutData;
    try {
      layoutData = await fetchLayoutData(site, language, routePath);
    } catch (error) {
      return Astro.redirect('/404');
    }

    if (!layoutData) {
      return Astro.redirect('/404');
    }
    ---

    <SitecoreLayout layoutData={layoutData} />
    ```

:::
:::tab{title="Go"}

1. Create `placeholder.go` and paste the following code:

    ```go
    // placeholder.go
    package main

    import (
        "fmt"
        "html/template"
        "strings"
    )

    // renderPlaceholder renders every component in a named placeholder slot.
    func renderPlaceholder(name string, items []any) template.HTML {
        var sb strings.Builder
        for _, item := range items {
            comp, ok := item.(map[string]any)
            if !ok {
                continue
            }
            sb.WriteString(string(renderComponent(comp)))
        }
        return template.HTML(fmt.Sprintf(
            `<div data-placeholder="%s">%s</div>`,
            template.HTMLEscapeString(name), sb.String(),
        ))
    }

    // renderComponent dispatches one layout component object to its registered
    // renderer, or falls back to renderMissingComponent for unknown names.
    func renderComponent(comp map[string]any) template.HTML {
        componentName, _ := comp["componentName"].(string)
        fields, _ := comp["fields"].(map[string]any)
        params, _ := comp["params"].(map[string]any)
        rawPH, _ := comp["placeholders"].(map[string]any)

        if fields == nil {
            fields = map[string]any{}
        }
        if params == nil {
            params = map[string]any{}
        }
        // Coerce the nested placeholder arrays from []any to a typed slice.
        placeholders := make(map[string][]any, len(rawPH))
        for k, v := range rawPH {
            if arr, ok := v.([]any); ok {
                placeholders[k] = arr
            }
        }

        if fn, ok := componentRegistry[componentName]; ok {
            return fn(fields, params, placeholders)
        }
        return renderMissingComponent(componentName, placeholders)
    }
    ```

    The `Placeholder` component takes a placeholder name and its component array, finds the right implementation for each `componentName`, and then passes through `fields`, `params`, and `placeholders`. This enables child components to render their own nested placeholders.

2. Create `Layout.go` and paste the following code:

    ```go
    // layout.go
    package main

    import (
        "html/template"
        "io"
    )

    var pageTmpl = template.Must(template.New("page").Parse(`<!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>{{.Title}}</title>
    </head>
    <body>
      {{- if .HasRoute}}
      <header>{{.Header}}</header>
      <main>{{.Main}}</main>
      <footer>{{.Footer}}</footer>
      {{- else}}
      <main><p>Layout data is missing for this route.</p></main>
      {{- end}}
    </body>
    </html>`))

    type pageVars struct {
        Title    string
        HasRoute bool
        Header   template.HTML
        Main     template.HTML
        Footer   template.HTML
    }

    // renderLayout writes a complete HTML page to w using the provided layout data.
    // Fields of type template.HTML are rendered as-is by html/template (no escaping),
    // which is intentional. Our component renderers produce safe, trusted HTML.
    func renderLayout(w io.Writer, layoutData map[string]any) error {
        if layoutData == nil {
            return pageTmpl.Execute(w, pageVars{Title: "Page not found"})
        }
        sitecore, _ := layoutData["sitecore"].(map[string]any)
        route, _ := sitecore["route"].(map[string]any)
        if route == nil {
            return pageTmpl.Execute(w, pageVars{Title: "Page not found"})
        }

        phs, _ := route["placeholders"].(map[string]any)
        slot := func(key string) []any {
            arr, _ := phs[key].([]any)
            return arr
        }

        title, _ := route["displayName"].(string)
        if title == "" {
            title, _ = route["name"].(string)
        }
        return pageTmpl.Execute(w, pageVars{
            Title:    title,
            HasRoute: true,
            Header:   renderPlaceholder("headless-header", slot("headless-header")),
            Main:     renderPlaceholder("headless-main", slot("headless-main")),
            Footer:   renderPlaceholder("headless-footer", slot("headless-footer")),
        })
    }
    ```

3. Update `main.go` to call `renderLayout` instead of rendering raw JSON:

    ```go
    // main.go
    package main

    import (
        "log"
        "net/http"
        "os"
        "strings"
        "github.com/joho/godotenv"
    )

    func main() {
        // Load .env file if present (ignored when not found, e.g. in production).
        _ = godotenv.Load()

        site := os.Getenv("SITECORE_SITE_NAME")
        language := os.Getenv("SITECORE_SITE_LANGUAGE_CODE")
        if language == "" {
            language = "en"
        }

        http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
            // Derive the Sitecore route path from the URL. Keep root "/" as-is;
            // trim any trailing slash from other paths.
            routePath := r.URL.Path
            if routePath != "/" {
                routePath = strings.TrimRight(routePath, "/")
            }

            data, err := fetchLayoutData(site, language, routePath)
            if err != nil {
                http.Error(w, err.Error(), http.StatusInternalServerError)
                return
            }
            if data == nil {
                // Route does not exist in Sitecore.
                if routePath == "/404" {
                    // Sitecore 404 page is not configured; serve a minimal fallback.
                    http.NotFound(w, r)
                    return
                }
                http.Redirect(w, r, "/404", http.StatusFound)
                return
            }

            w.Header().Set("Content-Type", "text/html; charset=utf-8")
            if err := renderLayout(w, data); err != nil {
                http.Error(w, err.Error(), http.StatusInternalServerError)
            }
        })

        log.Println("Listening on http://localhost:3000")
        log.Fatal(http.ListenAndServe(":3000", nil))
    }
    ```

:::
::::

### 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](https://doc.sitecore.com/sai/en/developers/sitecoreai/introduction-to-framework-agnostic-sitecore-development/content-rendering/field-types-in-rendering-data.html "Field types in rendering data"):

- `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:

::::tabs
:::tab{title="Astro"}

1. Create the `Title` component:

    ```astro
    ---
    // src/components/Title.astro
    interface Props {
      fields: {
        heading?: { value?: string };
      };
      params?: Record<string, any>;
    }

    const { fields, params } = Astro.props;
    ---

    {fields?.heading?.value && (
      <h1 class={params?.cssClass}>
        {fields.heading.value}
      </h1>
    )}
    ```

2. Create the `RichText` component:

    ```astro
    ---
    // src/components/RichText.astro

    interface Props {
      fields: {
        Text?: { value?: string };
      };
    }

    const { fields } = Astro.props;
    const html = fields?.Text?.value ?? "";
    ---

    <div set:html={html} />
    ```

3. Create the `Image` component:

    ```astro
    ---
    // src/components/Image.astro

    interface Props {
      fields: {
        Image?: {
          value?: { src?: string; alt?: string; width?: string; height?: string };
          jsonValue?: {
            value?: { src?: string; alt?: string; width?: string; height?: string };
          };
        };
        ImageCaption?: { value?: string };
        TargetUrl?: {
          value?: { href?: string; target?: string };
          jsonValue?: { value?: { href?: string; target?: string } };
        };
      };
    }

    const { fields } = Astro.props;

    // Image field, with jsonValue as a fallback for direct item queries.
    const imageField = fields?.Image;
    const imageValue = imageField?.value ?? imageField?.jsonValue?.value;
    const { src, alt, width, height } = imageValue ?? {};
    const caption = fields?.ImageCaption?.value;

    // General Link field, with jsonValue as a fallback for direct item queries.
    const linkField = fields?.TargetUrl;
    const link = linkField?.value ?? linkField?.jsonValue?.value;
    ---

    {src && (
      <figure>
        {link?.href ? (
          <a href={link.href} target={link.target || undefined}>
            <img src={src} alt={alt ?? ''} width={width} height={height} />
          </a>
        ) : (
          <img src={src} alt={alt ?? ''} width={width} height={height} />
        )}
        {caption && <figcaption>{caption}</figcaption>}
      </figure>
    )}
    ```

4. Register all three components in the component mapping by updating `src/components/componentMap.js`:

    ```javascript
    // src/components/componentMap.js
    import Image from './Image.astro';
    import RichText from './RichText.astro';
    import Title from './Title.astro';
    // Import all your other components here

    export const componentMap = {
      'Image': Image,
      'RichText': RichText,
      'Title': Title,
      // Map all your other components here
    };
    ```

:::
:::tab{title="Go"}

1. In `components.go`, update the import block to add `"fmt"`:

    ```go
    // Updated import block for components.go:
    import (
        "fmt"
        "html/template"
    )
    ```

2. Add a render function for the `Title` component:

    ```go
    func renderTitle(fields, params map[string]any, _ map[string][]any) template.HTML {
        heading := strField(fields, "heading")
        if heading == "" {
            return ""
        }
        classAttr := ""
        if cssClass := ms(params, "cssClass"); cssClass != "" {
            classAttr = fmt.Sprintf(` class="%s"`, esc(cssClass))
        }
        return template.HTML(fmt.Sprintf("<h1%s>%s</h1>", classAttr, esc(heading)))
    }
    ```

3. Add a render function for the `RichText` component:

    ```go
    func renderRichText(fields, params map[string]any, _ map[string][]any) template.HTML {
        html := strField(fields, "Text")
        if html == "" {
            return ""
        }
        return template.HTML("<div>" + html + "</div>")
    }
    ```

4. Add a render function for the `Image` component:

    ```go
    func renderImage(fields, params map[string]any, _ map[string][]any) template.HTML {
        img := imgValue(fields, "Image")
        if img == nil || ms(img, "src") == "" {
            return ""
        }
        imgTag := fmt.Sprintf(
            `<img src="%s" alt="%s" width="%s" height="%s" />`,
            esc(ms(img, "src")), esc(ms(img, "alt")),
            esc(ms(img, "width")), esc(ms(img, "height")),
        )
        // Wrap the image in a link if TargetUrl is set.
        lnk := lnkValue(fields, "TargetUrl")
        var content string
        if lnk != nil && ms(lnk, "href") != "" {
            targetAttr := ""
            if target := ms(lnk, "target"); target != "" {
                targetAttr = fmt.Sprintf(` target="%s"`, esc(target))
            }
            content = fmt.Sprintf(`<a href="%s"%s>%s</a>`, esc(ms(lnk, "href")), targetAttr, imgTag)
        } else {
            content = imgTag
        }
        // Show a caption below the image if ImageCaption is set.
        caption := strField(fields, "ImageCaption")
        if caption != "" {
            return template.HTML(fmt.Sprintf("<figure>%s<figcaption>%s</figcaption></figure>", content, esc(caption)))
        }
        return template.HTML(fmt.Sprintf("<figure>%s</figure>", content))
    }
    ```

5. In `components.go`, update the `init()` function to register all three components:

    ```go
    func init() {
        componentRegistry = map[string]ComponentFunc{
            "Image":    renderImage,
            "RichText": renderRichText,
            "Title":    renderTitle,
            // Add entries here as you implement each component
        }
    }
    ```

:::
::::

### Implement the `Promo` component

`Promo` 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:

::::tabs
:::tab{title="Astro"}

1. Create the `Promo` component:

    ```astro
    ---
    // src/components/Promo.astro

    interface Props {
      fields: {
        PromoText?: { value?: string };
        PromoText2?: { value?: string };
        PromoText3?: { value?: string };
      };
    }

    const { fields } = Astro.props;
    const html =
      fields?.PromoText?.value ||
      fields?.PromoText2?.value ||
      fields?.PromoText3?.value ||
      "";
    ---

    {html && <div set:html={html} />}
    ```

2. Register `Promo` in the component mapping by updating `src/components/componentMap.js` with the following import and entry:

    ```javascript
    import Promo from './Promo.astro';

    export const componentMap = {
      // ...existing entries...
      'Promo': Promo,
    };
    ```

:::
:::tab{title="Go"}

1. In `components.go`, add a render function for the `Promo` component:

    ```go
    func renderPromo(fields, params map[string]any, _ map[string][]any) template.HTML {
        for _, name := range []string{"PromoText", "PromoText2", "PromoText3"} {
            if html := strField(fields, name); html != "" {
                return template.HTML(html) // rich-text: inject as raw HTML, not escaped
            }
        }
        return ""
    }
    ```

2. Register `Promo` by adding the following entry to `componentRegistry`:

    ```go
    "Promo": renderPromo,
    ```

:::
::::

### Implement the `ColumnSplitter` component

`ColumnSplitter` 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:

::::tabs
:::tab{title="Astro"}

1. Create the `ColumnSplitter` component:

    ```astro
    ---
    // src/components/ColumnSplitter.astro
    import Placeholder from './Placeholder.astro';

    interface Props {
      params?: Record<string, any>;
      placeholders?: Record<string, any[]>;
    }

    const { params, placeholders } = Astro.props;
    const enabled = typeof params?.EnabledPlaceholders === 'string'
      ? params.EnabledPlaceholders.split(',').map((value) => value.trim()).filter(Boolean)
      : null;
    type Column = { key: string; items: any[]; index: number };
    const columns = (Object.entries(placeholders ?? {})
      .map(([key, items]) => {
        const match = key.match(/^column-(\d+)-/);
        if (!match) return null;

        return {
          key,
          items,
          index: Number(match[1]),
        };
      })
      .filter((c): c is Column => c !== null)
      .filter((column) => !enabled || enabled.includes(String(column.index)))
      .sort((a, b) => a.index - b.index));
    const wrapperClass = [params?.GridParameters].filter(Boolean).join(' ');
    ---

    <div data-component="ColumnSplitter" class={wrapperClass || undefined}>
      {columns.map((column) => {
        const columnClass = params?.[`ColumnWidth${column.index}`];

        return (
          <div data-column={column.index} class={columnClass || undefined}>
            <Placeholder name={column.key} rendering={column.items} />
          </div>
        );
      })}
    </div>
    ```

2. Register `ColumnSplitter` in the component mapping by updating `src/components/componentMap.js` with the following import and entry:

    ```javascript
    import ColumnSplitter from './ColumnSplitter.astro';

    export const componentMap = {
      // ...existing entries...
      'ColumnSplitter': ColumnSplitter,
    };
    ```

:::
:::tab{title="Go"}

1. Create `columnsplitter.go` and paste the following code:

    ```go
    // columnsplitter.go
    package main

    import (
        "fmt"
        "html/template"
        "sort"
        "strconv"
        "strings"
    )

    func renderColumnSplitter(fields, params map[string]any, placeholders map[string][]any) template.HTML {
        // Determine which column indices are enabled (params value: "1,2,3").
        var enabled []string
        if ep := ms(params, "EnabledPlaceholders"); ep != "" {
            for _, p := range strings.Split(ep, ",") {
                enabled = append(enabled, strings.TrimSpace(p))
            }
        }

        type col struct {
            index int
            key   string
            items []any
        }
        var cols []col
        for key, items := range placeholders {
            // Column placeholder keys look like "column-N-{uid}".
            if !strings.HasPrefix(key, "column-") {
                continue
            }
            rest := key[len("column-"):]
            dash := strings.Index(rest, "-")
            if dash < 0 {
                continue
            }
            idx, err := strconv.Atoi(rest[:dash])
            if err != nil {
                continue
            }
            idxStr := strconv.Itoa(idx)
            if len(enabled) > 0 {
                found := false
                for _, e := range enabled {
                    if e == idxStr {
                        found = true
                        break
                    }
                }
                if !found {
                    continue
                }
            }
            cols = append(cols, col{index: idx, key: key, items: items})
        }
        sort.Slice(cols, func(i, j int) bool { return cols[i].index < cols[j].index })

        var sb strings.Builder
        sb.WriteString(fmt.Sprintf(`<div data-component="ColumnSplitter" class="%s">`, esc(ms(params, "GridParameters"))))
        for _, c := range cols {
            colClass := ms(params, fmt.Sprintf("ColumnWidth%d", c.index))
            sb.WriteString(fmt.Sprintf(`<div data-column="%d" class="%s">`, c.index, esc(colClass)))
            sb.WriteString(string(renderPlaceholder(c.key, c.items)))
            sb.WriteString("</div>")
        }
        sb.WriteString("</div>")
        return template.HTML(sb.String())
    }
    ```

2. In `components.go`, add `ColumnSplitter` to the `componentRegistry` in the `init()` function:

    > [!note]
    > `renderColumnSplitter` calls `renderPlaceholder`, which reads `componentRegistry`. This is why `componentRegistry` is populated in `init()` rather than in a map literal. A map literal would create a Go initialization cycle and fail to compile.

    ```go
    func init() {
        componentRegistry = map[string]ComponentFunc{
            "ColumnSplitter": renderColumnSplitter,
            "Image":          renderImage,
            "Promo":          renderPromo,
            "RichText":       renderRichText,
            "Title":          renderTitle,
            // Add entries here as you implement each component
        }
    }
    ```
:::
::::

### Implement the `Container` and `PartialDesignDynamicPlaceholder` components

`Container` and `PartialDesignDynamicPlaceholder` are structural components you will encounter on most Sitecore pages. Like `ColumnSplitter`, they render nested placeholder slots rather than field content.

- `Container` wraps a set of nested placeholders in a `<div>` element and accepts optional CSS class parameters (`Styles` or `CssClass`). Content authors use it to group and style sections of a page.
- `PartialDesignDynamicPlaceholder` is 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:

::::tabs
:::tab{title="Astro"}

1. Create the `Container` component:

    ```astro
    ---
    // src/components/Container.astro
    import Placeholder from './Placeholder.astro';

    interface Props {
      params?: Record<string, any>;
      placeholders?: Record<string, any[]>;
    }

    const { params, placeholders } = Astro.props;
    const cssClass = params?.Styles ?? params?.CssClass ?? '';
    ---

    <div class={cssClass || undefined}>
      {Object.entries(placeholders ?? {}).map(([name, items]) => (
        <Placeholder name={name} rendering={items} />
      ))}
    </div>
    ```

2. Create the `PartialDesignDynamicPlaceholder` component:

    ```astro
    ---
    // src/components/PartialDesignDynamicPlaceholder.astro
    import Placeholder from './Placeholder.astro';

    interface Props {
      placeholders?: Record<string, any[]>;
      params?: Record<string, any>;
    }

    const { placeholders } = Astro.props;
    ---

    {Object.entries(placeholders ?? {}).map(([name, items]) => (
      <Placeholder name={name} rendering={items} />
    ))}
    ```

3. Register both components in the component mapping by updating `src/components/componentMap.js` with the following imports and entries:

    ```javascript
    import Container from './Container.astro';
    import PartialDesignDynamicPlaceholder from './PartialDesignDynamicPlaceholder.astro';

    export const componentMap = {
      // ...existing entries...
      'Container': Container,
      'PartialDesignDynamicPlaceholder': PartialDesignDynamicPlaceholder,
    };
    ```

:::
:::tab{title="Go"}

1. Create `container.go` and paste the following code:

    ```go
    // container.go
    package main

    import (
        "fmt"
        "html/template"
        "strings"
    )

    func renderContainer(fields, params map[string]any, placeholders map[string][]any) template.HTML {
        cssClass := ms(params, "Styles")
        if cssClass == "" {
            cssClass = ms(params, "CssClass")
        }
        classAttr := ""
        if cssClass != "" {
            classAttr = fmt.Sprintf(` class="%s"`, esc(cssClass))
        }
        var sb strings.Builder
        sb.WriteString(fmt.Sprintf("<div%s>", classAttr))
        for name, items := range placeholders {
            sb.WriteString(string(renderPlaceholder(name, items)))
        }
        sb.WriteString("</div>")
        return template.HTML(sb.String())
    }

    func renderPartialDesignDynamicPlaceholder(_ map[string]any, _ map[string]any, placeholders map[string][]any) template.HTML {
        var sb strings.Builder
        for name, items := range placeholders {
            sb.WriteString(string(renderPlaceholder(name, items)))
        }
        return template.HTML(sb.String())
    }
    ```

    > [!note]
    > Because both `renderContainer` and `renderPartialDesignDynamicPlaceholder` call `renderPlaceholder`, which reads `componentRegistry`, they must be registered in the `init()` 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.

2. In `components.go`, add `Container` and `PartialDesignDynamicPlaceholder` to the `componentRegistry` in the `init()` function:

    ```go
    func init() {
        componentRegistry = map[string]ComponentFunc{
            "ColumnSplitter":                  renderColumnSplitter,
            "Container":                       renderContainer,
            "Image":                           renderImage,
            "PartialDesignDynamicPlaceholder": renderPartialDesignDynamicPlaceholder,
            "Promo":                           renderPromo,
            "RichText":                        renderRichText,
            "Title":                           renderTitle,
            // Add entries here as you implement each component
        }
    }
    ```

:::
::::

## 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:

1. Retrieve the `notFoundPagePath` and `serverErrorPagePath` that content authors have configured in the Page builder. You can do this by using the `site` query's `errorHandling` field.
2. Using the `fetchLayoutData` function, retrieve and render the layout data for the paths you retrieved in the previous step.
3. 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 on localhost.

To test your app:

1. Save all changes in your code editor and restart your development server.
2. On localhost, navigate to the root route at `/` to render your **Home** page.
3. Verify that Sitecore content is being rendered.
4. Test your nested routes, such as `/products` and `products/product-item-1`.

## Next steps { .notintoc }

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 every `componentName` in 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](https://doc.sitecore.com/sai/en/developers/sitecoreai/experience-edge/experience-edge-apis/query-examples-for-the-delivery-graphql-api.html "Query examples for the Delivery GraphQL API") using the `item`, `search`, or `site` entry points. Retrieve this data separately from the `layout` query and pass the results into the relevant component. Keeping global data out of the per-page layout also [improves publishing performance](https://doc.sitecore.com/sai/en/developers/sitecoreai/experience-edge/experience-edge-best-practices.html "Experience Edge best practices").
- Learn more about the [GraphQL APIs](https://doc.sitecore.com/sai/en/developers/sitecoreai/experience-edge/experience-edge-apis.html "Experience Edge APIs"), including their differences, limitations, and best practices.
- Enable [visual editing](https://doc.sitecore.com/sai/en/developers/sitecoreai/introduction-to-framework-agnostic-sitecore-development/visual-editing.html), which is the next key development task after rendering Sitecore content.