# Click to Edit - Next.js Pages Router

Add interactive edit buttons to your content previews with the Hygraph Preview SDK. Click any content element to jump directly to it in the Hygraph editor.

This page walks through implementing Click to Edit in a Next.js Pages Router project using the [Hygraph Preview SDK](https://github.com/hygraph/preview-sdk). By the end, editors can click any instrumented element in the preview to jump directly to that field in Studio.

For the general setup overview and configuration reference, see [Click to Edit setup](https://hygraph.com/docs/developer-guides/schema/click-to-edit). Examples for other supported frameworks are available at:
- [Next.js App Router](https://hygraph.com/docs/developer-guides/schema/click-to-edit-next-js-app-router)
- [Remix](https://hygraph.com/docs/developer-guides/schema/click-to-edit-remix)
- [Vue / Nuxt](https://hygraph.com/docs/developer-guides/schema/click-to-edit-vue-nuxt)
- [Vanilla JavaScript](https://hygraph.com/docs/developer-guides/schema/click-to-edit-vanilla-js)
- [Advanced API](https://hygraph.com/docs/developer-guides/schema/click-to-edit-advanced-api)

**Note:**
If you are instrumenting a frontend you did not build from scratch, start with the `PreviewWrapper` component and a single simple field. Confirm the Edit button appears and the save refresh works before adding component attributes. Components require additional data from your GraphQL queries.

## Steps

1. [Install the Preview SDK](#install-the-preview-sdk).
2. [Create a PreviewWrapper component to enable the preview functionality](#create-the-previewwrapper-component).
3. [Set environment variables](#set-environment-variables).
4. [Add data attributes to your content elements](#add-data-attributes-to-content-elements).
5. [Set up the Preview widget in Studio](https://hygraph.com/docs/developer-guides/schema/click-to-edit#set-up-the-preview-widget-in-studio).
6. [Verify the setup](#verify-the-setup).

## Install the Preview SDK

To install the Preview SDK, run the following command:

```bash
npm install @hygraph/preview-sdk
```

## Create the PreviewWrapper component

The PreviewWrapper initializes the SDK and wraps your application content. Pages Router has no server components, so the SDK's React module loads client-side through a manual dynamic `import()` once the component has mounted, rather than through the single `next/dynamic` call used in App Router.

### Step 1: Create PreviewWrapper.tsx

Create `components/PreviewWrapper.tsx`:

```ts
// components/PreviewWrapper.tsx
import { useRouter } from 'next/router';
import { useEffect, useState, useMemo, useLayoutEffect } from 'react';
import type { ComponentType, ReactNode } from 'react';

interface PreviewWrapperProps {
  children: ReactNode;
}

export function PreviewWrapper({ children }: PreviewWrapperProps) {
  const router = useRouter();
  const [PreviewComponent, setPreviewComponent] = useState<ComponentType<any> | null>(null);
  const [isMounted, setIsMounted] = useState(false);

  // useLayoutEffect ensures React is fully initialized before loading the SDK
  useLayoutEffect(() => {
    setIsMounted(true);
  }, []);

  useEffect(() => {
    if (!isMounted) return;

    import('@hygraph/preview-sdk/react')
      .then((mod) => {
        setPreviewComponent(() => mod.HygraphPreview);
      })
      .catch((error) => {
        console.error('Failed to load Hygraph Preview SDK:', error);
      });
  }, [isMounted]);

  const handleSave = useMemo(() => {
    return (entryId: string) => {  // Optional: Custom save handler
      console.log('Content saved:', entryId);
      router.replace(router.asPath);
    };
  }, [router]);

  // Don't render the preview until mounted and the SDK component is loaded
  if (!isMounted || !PreviewComponent) {
    return <>{children}</>;
  }

  return (
    <PreviewComponent
      endpoint={process.env.NEXT_PUBLIC_HYGRAPH_ENDPOINT!}
      studioUrl={process.env.NEXT_PUBLIC_HYGRAPH_STUDIO_URL}
      debug={true}  // Optional: Enable console logging
      mode="iframe"  // Optional: 'iframe' | 'standalone' | 'auto'
      onSave={handleSave}
      overlay={{  // Optional: Customize overlay styling
        style: {
          borderColor: '#3b82f6',
          borderWidth: '2px',
        },
        button: {
          backgroundColor: '#3b82f6',
          color: 'white',
        },
      }}
      sync={{
        fieldFocus: true,  // Optional: Enable field focus sync from Studio
        fieldUpdate: false,  // Optional: Apply live field updates to Preview
      }}
    >
      {children}
    </PreviewComponent>
  );
}
```

### Step 2: Register PreviewWrapper in _app.tsx

Pages Router has no root layout file. Register `PreviewWrapper` in `pages/_app.tsx` instead, and load it with `next/dynamic` and `ssr: false`. If the wrapper is absent, the SDK cannot register page content and Click to Edit will not work.

```tsx
// pages/_app.tsx
import type { AppProps } from 'next/app';
import dynamic from 'next/dynamic';

const PreviewWrapper = dynamic(
  () => import('@/components/PreviewWrapper').then(mod => ({ default: mod.PreviewWrapper })),
  { ssr: false }
);

export default function App({ Component, pageProps }: AppProps) {
  return (
    <PreviewWrapper>
      <Component {...pageProps} />
    </PreviewWrapper>
  );
}
```

**Configuration properties**

| Property              | Required / Optional | Description |
|-----------------------|----------------------|-------------|
| `endpoint`            | **Required**         | Hygraph Content API endpoint. To learn how to retrieve the Content API endpoint, see [our docs](https://hygraph.com/docs/developer-guides/project/api-access#endpoints). |
| `studioUrl`           | Optional (recommended) | Studio base URL. Defaults to `https://app.hygraph.com`. Set this if your Studio runs on a regional or custom domain. |
| `debug`               | Optional             | Enables verbose console logs to diagnose attribute issues. |
| `mode`                | Optional             | Forces a specific mode. Options: `'iframe'` \| `'standalone'` \| `'auto'`. Auto-detection works for most cases. |
| `onSave`              | Optional             | Runs after Hygraph reports a save and receives the entry ID for targeted revalidation. |
| `overlay`             | Optional             | Customize overlay border and button appearance. |
| `sync.fieldFocus`     | Optional             | Synchronizes field focus between Studio and the preview when an editor selects a field. |
| `sync.fieldUpdate`    | Optional             | Updates the preview immediately when field updates happen in Studio. Defaults to `false`. |
| `allowedOrigins`      | Optional             | Extends the list of domains that can host your preview iframe. Example: For shared preview environments (QA, staging), add the base URL here. |

## Set environment variables

Add the following to `.env.local` in your project's root directory. If you already have these from live preview setup, skip this step.

```bash
# .env.local
NEXT_PUBLIC_HYGRAPH_ENDPOINT=https://your-region.cdn.hygraph.com/content/your-project-id/master
NEXT_PUBLIC_HYGRAPH_STUDIO_URL=https://your-region.hygraph.com
HYGRAPH_TOKEN=your-permanent-auth-token  # Optional: Required if your project uses authentication
```

**Content API endpoint**: Find this under **Project Settings > Access > Endpoints > High Performance Content API**. For more information, see our documentation on the [Content API](https://hygraph.com/docs/developer-guides/project/api-access#endpoints).

**Hygraph Studio base URL**: Copy from your browser's address bar in Studio. Example: `https://studio-eu-central-1-shared-euc1-02.hygraph.com`.

**Permanent Auth Token**: Create under **Project Settings > Access > Permanent Auth Tokens**. Set the default content stage to **DRAFT**. Only required if your project enforces authentication on Content API requests. For more information, see our dedicated documentation on [Permanent Auth Tokens](https://hygraph.com/docs/getting-started/access-and-permissions/api-access#authenticated-requests-permanent-auth-tokens).

## Add data attributes to content elements

Data attributes (`data-hygraph-*`) connect your rendered elements to specific Hygraph fields. The SDK reads these attributes and attaches Edit overlays automatically. The same attributes work for variants; no additional instrumentation is required. For the full attribute reference, see [Add data attributes to content elements](https://hygraph.com/docs/developer-guides/schema/click-to-edit#add-data-attributes-to-content-elements).

The examples below use a recipe model. To bootstrap the same Hygraph project used here, follow the [project setup instructions](https://github.com/hygraph/preview-sdk/blob/main/examples/project-setup/README.md).

Pages Router fetches the entry with `getServerSideProps` (or `getStaticProps`) and passes it to the page component as a prop. The route `id` comes from `context.params`, not `useParams()`.

```ts
// pages/recipes/[id].tsx
import { GetServerSideProps } from 'next';

export const getServerSideProps: GetServerSideProps = async (context) => {
  const { id } = context.params!;
  const recipe = await getRecipe(id as string);

  if (!recipe) {
    return { notFound: true };
  }

  return { props: { recipe } };
};

export default function RecipePage({ recipe }) {
  // ... rendered below
}
```

### Simple fields

Add `data-hygraph-entry-id` and `data-hygraph-field-api-id` to any element rendering a Hygraph field value.

```tsx

// pages/recipes/[id].tsx

  return (
    <main>
      {/* Title */}
      <h1
        data-hygraph-entry-id={recipe.id}
        data-hygraph-field-api-id="title"
      >
        {recipe.title}
      </h1>

      {/* Description */}
      <div
        data-hygraph-entry-id={recipe.id}
        data-hygraph-field-api-id="description"
        data-hygraph-rich-text-format="html"
      >
        <div dangerouslySetInnerHTML={{ __html: recipe.description.html }} />
      </div>

      {/* Recipe Meta */}
      <div
        data-hygraph-entry-id={recipe.id}
        data-hygraph-field-api-id="prepTime"
      >
        {recipe.prepTime}
      </div>

      <div
        data-hygraph-entry-id={recipe.id}
        data-hygraph-field-api-id="cookTime"
      >
        {recipe.cookTime}
      </div>

      <div
        data-hygraph-entry-id={recipe.id}
        data-hygraph-field-api-id="servings"
      >
        {recipe.servings}
      </div>

      <div
        data-hygraph-entry-id={recipe.id}
        data-hygraph-field-api-id="difficulty"
      >
        {recipe.difficulty}
      </div>

      {/* Hero Image */}
      <div
        data-hygraph-entry-id={recipe.id}
        data-hygraph-field-api-id="heroImage"
      >
        {/* Example image rendering */}
        {recipe.heroImage?.url && (
          <img src={recipe.heroImage.url} alt={recipe.title} />
        )}
      </div>
    </main>
  );
```

### Component fields

Components require the `data-hygraph-component-chain` attribute so Studio can navigate to the correct nested field instance. Use the helper functions from `@hygraph/preview-sdk/core`:

```tsx
import {
  createComponentChainLink,
  createPreviewAttributes,
  withFieldPath,
} from '@hygraph/preview-sdk/core';
```

The `instanceId` in each chain link is the `id` field of the component instance returned in your GraphQL query. It is not the component type's API ID. Query for `id` on every component you want to instrument. See the GraphQL example in [Basic components](#basic-components) below.

#### Basic components

These are direct children of the Recipe model, and are not nested inside other components. Each one uses a single-link chain.

  **Ingredients**

```ts

// Type: Basic component
// Structure: `Recipe → ingredients[] → ingredient fields`
// Used for: `quantity`, `unit` fields
// Path depth: 1 level (Recipe → Ingredient)
// Chain link: 1

// pages/recipes/[id].tsx

{recipe.ingredients.map((ingredient, index) => {
  const chain = [createComponentChainLink('ingredients', ingredient.id)];
  const basePath = `ingredients.${index}`;
  const quantityAttributes = withFieldPath(
    createPreviewAttributes({
      entryId: recipe.id,
      fieldApiId: 'quantity',
      componentChain: chain,
    }),
    `${basePath}.quantity`
  );
  // ... used for quantity, unit fields
})}
```

  
  **Recipe steps**

```ts

// Type: Basic component
// Structure: `Recipe → recipeSteps[] → step fields`
// Used for: `stepNumber`, `title`, `instruction`, `estimatedTime`
// Path depth: 1 level (Recipe → Recipe Step)
// Chain link: 1

// pages/recipes/[id].tsx

{recipe.recipeSteps.map((step, index) => {
  const chain = [createComponentChainLink('recipeSteps', step.id)];
  const stepBasePath = `recipeSteps.${index}`;
  const stepNumberAttributes = withFieldPath(
    createPreviewAttributes({
      entryId: recipe.id,
      fieldApiId: 'stepNumber',
      componentChain: chain,
    }),
    `${stepBasePath}.stepNumber`
  );
  // ... used for stepNumber, title, instruction, estimatedTime
})}
```


GraphQL query to retrieve `instanceId` values for basic components:

```graphql
query GetRecipe($id: ID!) {
  recipe(where: { id: $id }, stage: DRAFT) {
    id
    title
    ingredients {
      id        # instanceId for the ingredient component
      quantity
      unit
    }
    recipeSteps {
      id        # instanceId for the step component
      stepNumber
      instruction { html }
    }
  }
}
```

#### Nested components

Nested components require a multi-link chain, ordered from the outermost to the innermost component.

  **Equipment within recipe steps**

```ts

// Type: Nested component
// Structure: `Recipe → recipeSteps[] → equipment[] → equipment fields`
// Used for: `name`, `required`, `alternatives`, `notes` fields
// Path depth: 2 levels (Recipe → Recipe Step → Equipment)
// Chain links: 2

// pages/recipes/[id].tsx

{step.equipment.map((equip, equipIndex) => {
  const equipChain = [
    createComponentChainLink('recipeSteps', step.id),
    createComponentChainLink('equipment', equip.id)
  ];
  const equipBasePath = `${stepBasePath}.equipment.${equipIndex}`;
  // ... used for name, required, alternatives, notes fields
})}
```

  
  **Ingredients used within recipe steps**

```ts

// Type: Nested component
// Structure: `Recipe → recipeSteps[] → ingredientsUsed[] → ingredient fields`
// Used for: `ingredientName`, `preparation`, `timing`, `notes` fields
// Path depth: 2 levels (Recipe → Recipe Step → Ingredient Reference)
// Chain links: 2

// pages/recipes/[id].tsx

{step.ingredientsUsed.map((ingred, ingredIndex) => {
  const ingredChain = [
    createComponentChainLink('recipeSteps', step.id),
    createComponentChainLink('ingredientsUsed', ingred.id)
  ];
  const ingredBasePath = `${stepBasePath}.ingredientsUsed.${ingredIndex}`;
  // ... used for ingredientName, preparation, timing, notes fields
})}
```

  
  **Tips within recipe steps**

```ts

// Type: Nested component
// Structure: `Recipe → recipeSteps[] → tips[] → tip fields`
// Used for: `icon`, `title`, `content` fields
// Path depth: 2 levels (Recipe → Recipe Step → Tip)
// Chain links: 2

// pages/recipes/[id].tsx

{step.tips.map((tip, tipIndex) => {
  const tipChain = [
    createComponentChainLink('recipeSteps', step.id),
    createComponentChainLink('tips', tip.id)
  ];
  const tipBasePath = `${stepBasePath}.tips.${tipIndex}`;
  // ... used for icon, title, content fields
})}
```


GraphQL query to retrieve `instanceId` values for nested components. Extend your basic component query:

```graphql
recipeSteps {
  id
  stepNumber
  instruction { html }
  equipment {
    id        # instanceId for nested equipment
    name
    required
  }
  tips {
    id        # instanceId for nested tips
    title
    content { html }
  }
}
```

#### Modular components

Modular components can be one of several types. Use `__typename` to branch and build the chain per type.

The examples below display aliased GraphQL fields such as `section.tipTitle` and `section.tipContent`. Those come from query aliases (`tipTitle: title`, `tipContent: content`). `fieldApiId` must still use the schema API IDs (`title`, `content`).

  **Featured Content**

```ts

// Type: Modular component
// Structure: `Recipe → featuredContent (ProTip | VideoEmbed | IngredientSpotlight)`
// Used for: Single featured content section
// Path depth: 1 level
// Chain link: 1

// pages/recipes/[id].tsx

// Chain creation
const section = recipe.featuredContent;
const chain = [createComponentChainLink('featuredContent', section.id)];
const basePath = 'featuredContent';

// Switch
switch (section.__typename) {
  case 'ProTip': {
    const proTipIconAttributes = withFieldPath(
      createPreviewAttributes({
        entryId: recipe.id,
        fieldApiId: 'icon',
        componentChain: chain,
      }),
      `${basePath}.icon`
    );
    const proTipTitleAttributes = withFieldPath(
      createPreviewAttributes({
        entryId: recipe.id,
        fieldApiId: 'title',
        componentChain: chain,
      }),
      `${basePath}.title`
    );
    const proTipContentAttributes = withFieldPath(
      createPreviewAttributes({
        entryId: recipe.id,
        fieldApiId: 'content',
        componentChain: chain,
      }),
      `${basePath}.content`
    );

    return (
      <div>
        <div {...proTipIconAttributes}>
          {section.icon || '⭐'}
        </div>
        <h3 {...proTipTitleAttributes}>
          {section.tipTitle}
        </h3>
        <div
          dangerouslySetInnerHTML={{ __html: section.tipContent.html }}
          {...proTipContentAttributes}
          data-hygraph-rich-text-format="html"
        />
      </div>
    );
  }

  case 'VideoEmbed': {
    const videoTitleAttributes = withFieldPath(
      createPreviewAttributes({
        entryId: recipe.id,
        fieldApiId: 'title',
        componentChain: chain,
      }),
      `${basePath}.title`
    );
    const videoUrlAttributes = withFieldPath(
      createPreviewAttributes({
        entryId: recipe.id,
        fieldApiId: 'videoUrl',
        componentChain: chain,
      }),
      `${basePath}.videoUrl`
    );
    const videoDescriptionAttributes = withFieldPath(
      createPreviewAttributes({
        entryId: recipe.id,
        fieldApiId: 'description',
        componentChain: chain,
      }),
      `${basePath}.description`
    );

    return (
      <div>
        <h3 {...videoTitleAttributes}>
          {section.videoTitle}
        </h3>
        <div {...videoUrlAttributes}>
          {/* Video embed logic */}
        </div>
        {section.videoDescription && (
          <div
            dangerouslySetInnerHTML={{ __html: section.videoDescription.html }}
            {...videoDescriptionAttributes}
            data-hygraph-rich-text-format="html"
          />
        )}
      </div>
    );
  }

  case 'IngredientSpotlight': {
    const spotlightImageAttributes = withFieldPath(
      createPreviewAttributes({
        entryId: recipe.id,
        fieldApiId: 'image',
        componentChain: chain,
      }),
      `${basePath}.image`
    );
    const spotlightTitleAttributes = withFieldPath(
      createPreviewAttributes({
        entryId: recipe.id,
        fieldApiId: 'ingredient',
        componentChain: chain,
      }),
      `${basePath}.ingredient`
    );
    const spotlightDescriptionAttributes = withFieldPath(
      createPreviewAttributes({
        entryId: recipe.id,
        fieldApiId: 'description',
        componentChain: chain,
      }),
      `${basePath}.description`
    );
    const spotlightSubstitutesAttributes = withFieldPath(
      createPreviewAttributes({
        entryId: recipe.id,
        fieldApiId: 'substitutes',
        componentChain: chain,
      }),
      `${basePath}.substitutes`
    );

    return (
      <div>
        <div {...spotlightImageAttributes}>
          {section.ingredientImage ? (
            <img
              src={section.ingredientImage.url}
              alt={section.ingredient?.name || 'Ingredient'}
              width={120}
              height={120}
            />
          ) : (
            <div>🌿</div>
          )}
        </div>
        <h3 {...spotlightTitleAttributes}>
          Star Ingredient: <span>{section.ingredient?.name || 'Unknown'}</span>
        </h3>
        <div
          dangerouslySetInnerHTML={{ __html: section.ingredientDescription.html }}
          {...spotlightDescriptionAttributes}
          data-hygraph-rich-text-format="html"
        />
        {section.substitutes && (
          <span {...spotlightSubstitutesAttributes}>
            {section.substitutes}
          </span>
        )}
      </div>
    );
  }

  default:
    return null;
}
```

  
  **Additional Sections**

```ts

// Type: Modular component
// Structure: `Recipe → additionalSections[] (ProTip | VideoEmbed | IngredientSpotlight)[]`
// Used for: Multiple additional content sections
// Path depth: 1 level
// Chain link: 1

// pages/recipes/[id].tsx

{recipe.additionalSections.map((section, index) => {
  // Chain creation
  const chain = [createComponentChainLink('additionalSections', section.id)];
  const basePath = `additionalSections.${index}`;

  // Switch
  switch (section.__typename) {
    case 'ProTip': {
      const proTipListIconAttributes = withFieldPath(
        createPreviewAttributes({
          entryId: recipe.id,
          fieldApiId: 'icon',
          componentChain: chain,
        }),
        `${basePath}.icon`
      );
      const proTipListTitleAttributes = withFieldPath(
        createPreviewAttributes({
          entryId: recipe.id,
          fieldApiId: 'title',
          componentChain: chain,
        }),
        `${basePath}.title`
      );
      const proTipListContentAttributes = withFieldPath(
        createPreviewAttributes({
          entryId: recipe.id,
          fieldApiId: 'content',
          componentChain: chain,
        }),
        `${basePath}.content`
      );

      return (
        <div key={section.id}>
          <div {...proTipListIconAttributes}>
            {section.icon || '💡'}
          </div>
          <h3 {...proTipListTitleAttributes}>
            {section.tipTitle}
          </h3>
          <div
            dangerouslySetInnerHTML={{ __html: section.tipContent.html }}
            {...proTipListContentAttributes}
            data-hygraph-rich-text-format="html"
          />
        </div>
      );
    }

    case 'VideoEmbed': {
      const listVideoTitleAttributes = withFieldPath(
        createPreviewAttributes({
          entryId: recipe.id,
          fieldApiId: 'title',
          componentChain: chain,
        }),
        `${basePath}.title`
      );
      const listVideoUrlAttributes = withFieldPath(
        createPreviewAttributes({
          entryId: recipe.id,
          fieldApiId: 'videoUrl',
          componentChain: chain,
        }),
        `${basePath}.videoUrl`
      );
      const listVideoDescriptionAttributes = withFieldPath(
        createPreviewAttributes({
          entryId: recipe.id,
          fieldApiId: 'description',
          componentChain: chain,
        }),
        `${basePath}.description`
      );

      return (
        <div key={section.id}>
          <h3 {...listVideoTitleAttributes}>
            {section.videoTitle}
          </h3>
          <div {...listVideoUrlAttributes}>
            {/* Video embed logic */}
          </div>
          {section.videoDescription && (
            <div
              dangerouslySetInnerHTML={{ __html: section.videoDescription.html }}
              {...listVideoDescriptionAttributes}
              data-hygraph-rich-text-format="html"
            />
          )}
        </div>
      );
    }

    case 'IngredientSpotlight': {
      const listSpotlightImageAttributes = withFieldPath(
        createPreviewAttributes({
          entryId: recipe.id,
          fieldApiId: 'image',
          componentChain: chain,
        }),
        `${basePath}.image`
      );
      const listSpotlightTitleAttributes = withFieldPath(
        createPreviewAttributes({
          entryId: recipe.id,
          fieldApiId: 'ingredient',
          componentChain: chain,
        }),
        `${basePath}.ingredient`
      );
      const listSpotlightDescriptionAttributes = withFieldPath(
        createPreviewAttributes({
          entryId: recipe.id,
          fieldApiId: 'description',
          componentChain: chain,
        }),
        `${basePath}.description`
      );
      const listSpotlightSubstitutesAttributes = withFieldPath(
        createPreviewAttributes({
          entryId: recipe.id,
          fieldApiId: 'substitutes',
          componentChain: chain,
        }),
        `${basePath}.substitutes`
      );

      return (
        <div key={section.id}>
          <div {...listSpotlightImageAttributes}>
            {section.ingredientImage ? (
              <img
                src={section.ingredientImage.url}
                alt={section.ingredient?.name || 'Ingredient'}
                width={80}
                height={80}
              />
            ) : (
              <div>🥬</div>
            )}
          </div>
          <h3 {...listSpotlightTitleAttributes}>
            Featured: <span>{section.ingredient?.name || 'Unknown'}</span>
          </h3>
          <div
            dangerouslySetInnerHTML={{ __html: section.ingredientDescription.html }}
            {...listSpotlightDescriptionAttributes}
            data-hygraph-rich-text-format="html"
          />
          {section.substitutes && (
            <span {...listSpotlightSubstitutesAttributes}>
              {section.substitutes}
            </span>
          )}
        </div>
      );
    }

    default:
      return null;
  }
})}
```


### Full example

```ts

// pages/recipes/[id].tsx

import { GetServerSideProps } from 'next';
import { createComponentChainLink, createPreviewAttributes, withFieldPath } from '@hygraph/preview-sdk/core';

export const getServerSideProps: GetServerSideProps = async (context) => {
  const { id } = context.params!;
  const recipe = await getRecipe(id as string);

  if (!recipe) {
    return { notFound: true };
  }

  return { props: { recipe } };
};

export default function RecipePage({ recipe }) {
  return (
    <main>
      {/* Basic fields */}

      <h1 data-hygraph-field-api-id="title" data-hygraph-entry-id={recipe.id}>
        {recipe.title}
      </h1>

      <div
        data-hygraph-field-api-id="description"
        data-hygraph-entry-id={recipe.id}
        data-hygraph-rich-text-format="html"
      >
        <div dangerouslySetInnerHTML={{ __html: recipe.description.html }} />
      </div>

      <div data-hygraph-field-api-id="prepTime" data-hygraph-entry-id={recipe.id}>
        {recipe.prepTime}min
      </div>

      <div data-hygraph-entry-id={recipe.id} data-hygraph-field-api-id="categories">
        {recipe.categories.map((category) => (
          <span key={category.id}>{category.name}</span>
        ))}
      </div>

      {/* Basic components */}

      {/* Ingredients */}
      {recipe.ingredients.map((ingredient, index) => {
        const chain = [createComponentChainLink('ingredients', ingredient.id)];
        const basePath = `ingredients.${index}`;

        const quantityAttributes = withFieldPath(
          createPreviewAttributes({
            entryId: recipe.id,
            fieldApiId: 'quantity',
            componentChain: chain,
          }),
          `${basePath}.quantity`
        );

        const unitAttributes = withFieldPath(
          createPreviewAttributes({
            entryId: recipe.id,
            fieldApiId: 'unit',
            componentChain: chain,
          }),
          `${basePath}.unit`
        );

        return (
          <div key={ingredient.id}>
            <span>{ingredient.ingredient?.name}</span>
            <span {...quantityAttributes}>{ingredient.quantity}</span>
            <span {...unitAttributes}>{ingredient.unit}</span>
          </div>
        );
      })}

      {/* Recipe Steps (with nested equipment) */}
      {recipe.recipeSteps.map((step, index) => {
        const chain = [createComponentChainLink('recipeSteps', step.id)];
        const stepBasePath = `recipeSteps.${index}`;

        const stepNumberAttributes = withFieldPath(
          createPreviewAttributes({
            entryId: recipe.id,
            fieldApiId: 'stepNumber',
            componentChain: chain,
          }),
          `${stepBasePath}.stepNumber`
        );

        const stepTitleAttributes = withFieldPath(
          createPreviewAttributes({
            entryId: recipe.id,
            fieldApiId: 'title',
            componentChain: chain,
          }),
          `${stepBasePath}.title`
        );

        const instructionAttributes = withFieldPath(
          createPreviewAttributes({
            entryId: recipe.id,
            fieldApiId: 'instruction',
            componentChain: chain,
          }),
          `${stepBasePath}.instruction`
        );

        return (
          <div key={step.id}>
            <span {...stepNumberAttributes}>{step.stepNumber}</span>
            {step.title && <h3 {...stepTitleAttributes}>{step.title}</h3>}
            <div
              dangerouslySetInnerHTML={{ __html: step.instruction.html }}
              {...instructionAttributes}
              data-hygraph-rich-text-format="html"
            />

            {/* Nested: Equipment within Recipe Steps */}
            {step.equipment?.map((equip, equipIndex) => {
              const equipChain = [
                createComponentChainLink('recipeSteps', step.id),
                createComponentChainLink('equipment', equip.id),
              ];
              const equipBasePath = `${stepBasePath}.equipment.${equipIndex}`;

              const nameAttributes = withFieldPath(
                createPreviewAttributes({
                  entryId: recipe.id,
                  fieldApiId: 'name',
                  componentChain: equipChain,
                }),
                `${equipBasePath}.name`
              );

              const requiredAttributes = withFieldPath(
                createPreviewAttributes({
                  entryId: recipe.id,
                  fieldApiId: 'required',
                  componentChain: equipChain,
                }),
                `${equipBasePath}.required`
              );

              return (
                <div key={equip.id}>
                  <span {...nameAttributes}>{equip.name}</span>
                  {equip.required && <span {...requiredAttributes}>Required</span>}
                </div>
              );
            })}
          </div>
        );
      })}

      {/* Modular components */}

      {/* Featured Content (Single) */}
      {recipe.featuredContent && (() => {
        const section = recipe.featuredContent;
        const chain = [createComponentChainLink('featuredContent', section.id)];
        const basePath = 'featuredContent';

        switch (section.__typename) {
          case 'ProTip': {
            const iconAttributes = withFieldPath(
              createPreviewAttributes({
                entryId: recipe.id,
                fieldApiId: 'icon',
                componentChain: chain,
              }),
              `${basePath}.icon`
            );
            const titleAttributes = withFieldPath(
              createPreviewAttributes({
                entryId: recipe.id,
                fieldApiId: 'title',
                componentChain: chain,
              }),
              `${basePath}.title`
            );
            const contentAttributes = withFieldPath(
              createPreviewAttributes({
                entryId: recipe.id,
                fieldApiId: 'content',
                componentChain: chain,
              }),
              `${basePath}.content`
            );

            return (
              <div>
                <div {...iconAttributes}>{section.icon}</div>
                <h3 {...titleAttributes}>{section.tipTitle}</h3>
                <div
                  dangerouslySetInnerHTML={{ __html: section.tipContent.html }}
                  {...contentAttributes}
                  data-hygraph-rich-text-format="html"
                />
              </div>
            );
          }

          default:
            return null;
        }
      })()}
    </main>
  );
}
```

## Verify the setup

1. Open an entry in Studio for the model you configured.
2. In the right sidebar, click **Open live preview**. The preview should load alongside the entry form.
3. Hover over an element you tagged with `data-hygraph-*` attributes. An **Edit** button should appear.
4. Click **Edit**. Studio should scroll to and focus the corresponding field in the entry form.
5. Edit the field value and click **Save & Preview**. The preview should refresh and show the updated content.

If you are working with variants, no additional setup is required. Clicking a tagged element while a variant is open focuses the field directly in the variant overlay.

If the **Edit** button does not appear at step 3, add `debug={true}` to your `PreviewComponent` and check the browser console for missing attribute warnings. For component fields, confirm your GraphQL query includes the `id` field on each component and that the `instanceId` values in your chain match what the query returns. For more information, see [Troubleshooting](https://hygraph.com/docs/developer-guides/schema/click-to-edit#troubleshooting).

## Related docs

- [Click to Edit setup](https://hygraph.com/docs/developer-guides/schema/click-to-edit): General setup steps, attribute reference, Studio widget configuration, and troubleshooting.
- [Click to Edit - Advanced API](https://hygraph.com/docs/developer-guides/schema/click-to-edit-advanced-api): Advanced Preview SDK APIs, including live preview updates for scalar lists, component arrays, custom save handling, and DOM events.
- [Live preview setup](https://hygraph.com/docs/developer-guides/schema/live-preview): Configure the Studio preview iframe before deploying Click to Edit to editors.
