# Click to Edit setup

Install the Hygraph Preview SDK and configure Click to Edit so editors can jump from any preview element directly to the corresponding field in Hygraph Studio.

Click to Edit lets editors jump from any tagged element in a content preview directly to that field in Hygraph Studio. You configure it on the frontend using the [Hygraph Preview SDK](https://github.com/hygraph/preview-sdk). Editors perform the following steps without any further developer involvement:
1. Hover over a tagged element in preview to display an **Edit** button.
2. Click the **Edit** button to open the corresponding field entry in Studio.
3. Save changes to automatically refresh the preview.

**Note:**
Click to Edit is built on top of live preview. You do not need live preview running before you start, but editors get the full visual editing experience only when both are set up. See [live preview setup](https://hygraph.com/docs/developer-guides/schema/live-preview) if you have not configured it yet.

[Video: Click to Edit in content preview](https://eu-central-1-shared-euc1-02.graphassets.com/AvHQ3RDvFSousA8iwElOKz/cmirlamtb1vpz06w6c76kn30k)

## How it works

The SDK operates in two modes that are automatically detected:
  - **Iframe Mode**: When your preview loads in an iframe inside Hygraph Studio.
  - **Standalone Mode**: When your preview loads in a separate browser tab outside Studio.

In both modes, the SDK scans your rendered HTML for `data-hygraph-*` attributes. These attributes map each element back to a specific entry and field in Hygraph. The SDK adds hover overlays and **Edit** buttons automatically. When an editor saves in Studio, Hygraph sends a save event to the preview so it can refresh while preserving scroll position.

Real-time field updates are disabled by default. The preview refreshes on save only. You can enable live updates with `sync={{ fieldUpdate: true }}`.

## Get started

### Availability

- The Click to Edit feature is available for all projects and is currently in Beta.

### Prerequisites

- A Hygraph project with at least one model and content entry.
- A running preview application (local or deployed) using React, Next.js, Remix, Vue, or vanilla JavaScript.

### Setup 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 content elements](#add-data-attributes-to-content-elements).
5. [Set up the Preview widget in Studio](#set-up-the-preview-widget-in-studio).
6. [Verify the setup](#verify-the-setup).

## Install the Preview SDK

The SDK connects your frontend to Studio. It handles overlay rendering, save event listening, and iframe/standalone mode detection.

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

## Create the PreviewWrapper component

The `PreviewWrapper` component initializes the SDK across your application, and enables the preview functionality. Choose the implementation that matches your framework:
- [Next.js App Router](https://hygraph.com/docs/developer-guides/schema/click-to-edit-next-js-app-router#create-the-previewwrapper-component)
- [Next.js Pages Router](https://hygraph.com/docs/developer-guides/schema/click-to-edit-next-js-pages-router#create-the-previewwrapper-component)
- [Remix](https://hygraph.com/docs/developer-guides/schema/click-to-edit-remix#create-the-previewwrapper-component)
- [Vue](https://hygraph.com/docs/developer-guides/schema/click-to-edit-vue-nuxt#vue)
- [Nuxt](https://hygraph.com/docs/developer-guides/schema/click-to-edit-vue-nuxt#nuxt)
- [Vanilla JavaScript](https://hygraph.com/docs/developer-guides/schema/click-to-edit-vanilla-js)

### Configuration properties

| Property | Required | Description |
|---|---|---|
| `endpoint` | Required | Your Hygraph Content API endpoint. See [Content API](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. |
| `onSave` | Optional | Callback fired after Studio reports a save. Receives the saved entry ID. Use this to trigger revalidation or a router refresh. |
| `debug` | Optional | Enables verbose console logging. Useful for diagnosing missing attribute issues. |
| `mode` | Optional | Forces `'iframe'`, `'standalone'`, or `'auto'`. Auto-detection works for most cases. |
| `overlay` | Optional | Customize overlay border color, border width, button background, and button text color. |
| `sync.fieldFocus` | Optional | Synchronizes field focus between Studio and the preview when an editor selects a field. |
| `sync.fieldUpdate` | Optional | Applies live field changes to the preview as the editor types. Defaults to `false`. |
| `allowedOrigins` | Optional | Additional domains that can host the preview iframe, such as staging or QA environments. |

## Set environment variables

Set the following values in `.env.local`. If you already configured these for live preview, skip this step.

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

- **Content API endpoint**: Copy your Content API endpoint from your Hygraph project settings under **Project Settings > Access > Endpoints > High Performance Content API**. For more information, see our dedicated docs on the [Content API](https://hygraph.com/docs/developer-guides/project/api-access#endpoints).
- **Hygraph Studio base URL**: Copy the base Studio URL from your browser's address bar. Example: `https://studio-eu-central-1-shared-euc1-02.hygraph.com`.
- **Permanent Auth Token**: You can create a Permanent Auth Token under **Project Settings > Access > Permanent Auth Tokens**. Check that the default content stage is DRAFT. For more information, see our dedicated docs on [Permanent Auth Tokens](https://hygraph.com/docs/getting-started/access-and-permissions/api-access#authenticated-requests-permanent-auth-tokens).
    - This is needed only if your Hygraph project requires authentication for Content API requests.

## Add data attributes to content elements

The SDK uses `data-hygraph-*` attributes to map rendered elements back to Hygraph fields. Add them to the JSX or HTML elements that render Hygraph content. You do not need to instrument every element; add attributes only to the fields editors need to edit from the preview.

The SDK scans rendered HTML for these attributes and attaches hover overlays and **Edit** buttons automatically. The same attributes work for variants. When an editor opens a variant, clicking a tagged element focuses the corresponding field directly in the variant overlay.

| Attribute | Required | Description |
|---|---|---|
| `data-hygraph-entry-id` | Required | The content entry ID. Every editable element needs this. Always use the root entry ID, not a component instance ID. |
| `data-hygraph-field-api-id` | Optional | The API ID of the field in the schema. Without this, clicking **Edit** opens the entry without focusing a specific field. |
| `data-hygraph-rich-text-format` | Optional | Format for Rich Text fields. Accepts `html`, `markdown`, or `text`. |
| `data-hygraph-component-chain` | Optional | JSON array describing the path to a nested component field. See [tagging component fields](#tagging-component-fields). |
| `data-hygraph-list-index` | Optional | Index of the item an element renders, for a field marked as a list. See [live preview for scalar lists](https://hygraph.com/docs/developer-guides/schema/click-to-edit-advanced-api#live-preview-for-scalar-lists). |

![`data-hygraph-entry-id` - Content entry](https://hygraph.com/images/docs/developer-guides/click-to-edit-data-attributes-simple.png)

To find the `data-hygraph-field-api-id`:

1. Open **Schema** and select your model.
2. Locate the field. The API ID appears next to the field name in camelCase without any spaces.
3. Use that value as `data-hygraph-field-api-id`.

![`data-hygraph-field-api-id` - Schema](https://hygraph.com/images/docs/developer-guides/click-to-edit-data-attributes-api-id.png)

### Tagging component fields

Components require the `data-hygraph-component-chain` attribute in addition to the standard attributes. This tells Studio how to navigate from the root entry to the specific nested component instance.

The chain is a JSON array of `{ fieldApiId, instanceId }` objects ordered from outermost to innermost component. The `instanceId` is the unique identifier of the component instance returned in your GraphQL response. It is not the component type's API ID, and it does not appear in the Studio UI.

**Note:**
You do not copy instance IDs from Studio. Query for the `id` field on each component in your GraphQL query. The SDK reads this value from your data at render time to build the chain.

| Attribute | Description |
|---|---|
| `data-hygraph-entry-id` | The root content entry ID. Never use a component's own ID here. |
| `data-hygraph-field-api-id` | The API ID of the specific field inside the component. Identifies which field to focus within the entry in the editor. Without it, the edit button opens the entry unfocused. |
| `data-hygraph-component-chain` | JSON array of `{ fieldApiId, instanceId }` describing the path from root entry to the target field. <ul><li><code>fieldApiId</code> - The field that contains the nested component. </li><li><code>instanceId</code> - Unique identifier of the component instance, as returned in your GraphQL query as described below. This is not the API ID of the component. </li></ul> |

![Data attributes components markup](https://hygraph.com/images/docs/developer-guides/click-to-edit-data-attributes-components.png)

#### Query to retrieve instanceId

Retrieve the `instanceId` using the following query:

  **Query to retrieve instanceId**
```graphql
query MyQuery {
  recipes(where: {id: "<your_recipe_ID>"}) {
    __typename
    id # This is the entry ID
    nutrition {
      id # This is the instanceId for the component chain
    }
    ingredients {
      id # This is the instanceId for the component chain
    }
    featuredContent {
      ... on IngredientSpotlight {
        id # This is the instanceId for the component chain
      }
    }
    additionalSections {
      ... on ProTip {
        id # This is the instanceId for the component chain
      ... on VideoEmbed {
        id # This is the instanceId for the component chain
      }
    }
  }
}
}
```

  
  **Response with instanceId**

```json
{
  "data": {
    "recipes": [
      {
        "__typename": "Recipe",
        "id": "cmionbkxj01jm07vpwefnyv1b",
        "nutrition": {
          "id": "cmionbkxx01jz07vpqfq1fqu1"
        },
        "ingredients": [
          {
            "id": "cmionbkxw01jn07vplxi3igp7"
          },
          {
            "id": "cmionbkxw01jp07vpq225ziap"
          },
          {
            "id": "cmionbkxx01jr07vp3a7qgx9o"
          },
          {
            "id": "cmionbkxx01jt07vp26pn1h1s"
          },
          {
            "id": "cmionbkxx01jv07vpcqagyg5b"
          },
          {
            "id": "cmionbkxx01jx07vpscvzswph"
          }
        ],
        "featuredContent": {
          "id": "cmiq3y64i0cn207vpxxinofiv"
        },
        "additionalSections": [
          {
            "id": "cmiq3y64s0cn607vp4zlz0q5y"
          },
          {
            "id": "cmiq3y64s0cn407vpv509s5jq"
          }
        ]
      }
    ]
  }
}
```
  

## Set up the Preview widget in Studio

If you have already configured a Preview widget for [live preview](https://hygraph.com/docs/developer-guides/schema/live-preview), you can skip this step. Click to Edit uses the same widget.

1. Open your Hygraph project.
2. Navigate to **Schema** and select your model.
3. Click the **Sidebar** tab.
4. Select the **Preview** widget from the right sidebar.
5. Complete the **Preview name** and the **URL template** fields, and click **Add**.

## Verify the setup

After completing all setup steps, confirm Click to Edit is working end to end.

1. Open an entry in Studio for the model you configured live preview.
2. In the right sidebar, under **Preview**, 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 the **Edit** button does not appear at step 3, add `debug={true}` to your `PreviewWrapper` component and check the browser console for attribute warnings. Common causes are listed in [Troubleshooting](#troubleshooting) below.

## Known limitation

Click to Edit cannot navigate to a field in a specific locale. The **Edit** button opens the correct field in the default locale, but the editor needs to select the field for the target locale manually within Studio.

[Video: Click to Edit - Localized fields](https://eu-central-1-shared-euc1-02.graphassets.com/AvHQ3RDvFSousA8iwElOKz/cmowrrfomdqyh07upz2em2pl0)

## Troubleshooting

### Edit buttons do not appear

- Confirm `data-hygraph-entry-id` is present on the element.
- Add `debug={true}` to your `PreviewWrapper` component and check the browser console.
- Verify `NEXT_PUBLIC_HYGRAPH_ENDPOINT` is set correctly.

### Preview does not open

Vercel sets an `X-Frame-Options` response header that blocks iframe loading. In your Vercel project, go to **Settings > Deployment Protection** and disable **Vercel Authentication**.

### Preview does not refresh after saving

- Confirm the `onSave` callback calls your framework's refresh method, for example, `router.refresh()` in Next.js.
- Verify your Permanent Auth Token has **DRAFT** set as the default content stage.
- Confirm your GraphQL queries request the `DRAFT` stage in preview mode.

### Real-time field updates not working

Real-time updates are disabled by default. Add `sync={{ fieldUpdate: true }}` to your `PreviewWrapper` component to enable them.

### List fields do not update

- Confirm the installed `@hygraph/preview-sdk` is 1.1.0 or later. Studio withholds list updates from earlier versions, which have no way to render them.
- Confirm the element bound to the list has no child elements, or tag each item with `data-hygraph-list-index`. See [live preview for scalar lists](https://hygraph.com/docs/developer-guides/schema/click-to-edit-advanced-api#live-preview-for-scalar-lists).
- Rich Text lists and JSON fields never update live, whatever the SDK version. Those change in the preview after a save and a refresh.

### Components do not focus correctly

- Check that `data-hygraph-entry-id` is always the root entry ID, not the component instance ID.
- Verify the `instanceId` values in your component chain match the `id` fields returned by your GraphQL query.
- Confirm the component chain array is ordered from outermost to innermost component.

## What's next

- [Click to Edit - Next.js App Router](https://hygraph.com/docs/developer-guides/schema/click-to-edit-next-js-app-router): Complete implementation for Next.js App Router with code examples for simple fields, basic, nested, and modular components.
- [Click to Edit - Next.js Pages Router](https://hygraph.com/docs/developer-guides/schema/click-to-edit-next-js-pages-router): Complete implementation for Next.js Pages Router with code examples for simple fields, basic, nested, and modular components.
- [Click to Edit - Remix](https://hygraph.com/docs/developer-guides/schema/click-to-edit-remix): Complete implementation for Remix with code examples for simple fields, basic, nested, and modular components.
- [Click to Edit - Vue / Nuxt](https://hygraph.com/docs/developer-guides/schema/click-to-edit-vue-nuxt): Complete implementation for Vue and Nuxt, with shared attribute examples for simple fields, basic, nested, and modular components.
- [Click to Edit - Vanilla JavaScript](https://hygraph.com/docs/developer-guides/schema/click-to-edit-vanilla-js): Complete implementation for vanilla JavaScript with code examples for simple fields, basic, nested, and modular components.
- [Click to Edit - Advanced API](https://hygraph.com/docs/developer-guides/schema/click-to-edit-advanced-api): React hooks, Preview methods, DOM events, and helpers for dynamic content.
