> For the complete documentation index, see [llms.txt](https://docs.hyperswitch.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.hyperswitch.io/integration-guide/account-management/beta-embeddable-components/integration-reference.md).

# Integration Reference

Learn how to integrate Hyperswitch embeddable components into your React application using the SDK provider pattern for secure connector configuration management.

## Integration Reference

This SDK allows you to embed Hyperswitch Control Center functionality, such as connector configuration, payments and refunds, directly into your application. It uses a provider pattern to manage authentication sessions via JWTs, ensuring your API keys never leak to the client.

Repository URL: <https://github.com/juspay/hyperswitch-control-center-embedded>

Demo URL: <https://app.hyperswitch.io/hsdemo/?flow=embedded_components>

### Prerequisites & Compatibility

Before you begin, ensure your environment meets the following requirements:

* Runtime: Node.js (v18+)
* Framework: React (v18.x and v19.x)
* Hyperswitch Credentials:
  * `API-Key` (Can be generated via Control Center)
  * `Profile-ID` (The specific merchant profile you are configuring)
* Support:
  * ✅ Vite
  * ✅ Webpack
  * ✅ Next.js (App Router requires a Client Component, see **Server-side rendering (Next.js)** below)
  * ✅ Create React App

#### Environments

The `url` option is the base URL of the Control Center that serves the components. The embedded token **must be issued by the same environment** as the `url` you render the component with. A sandbox token will not work with the production `url`, and vice versa.

| Environment | Component `url`               | Token API base URL                |
| ----------- | ----------------------------- | --------------------------------- |
| Sandbox     | `https://app.hyperswitch.io`  | `https://app.hyperswitch.io/api`  |
| Production  | `https://live.hyperswitch.io` | `https://live.hyperswitch.io/api` |

{% hint style="warning" %}
If `url` is omitted, components fall back to `http://localhost:9000`, which is meant only for local development against a locally running Control Center. Always set `url` explicitly in sandbox and production.
{% endhint %}

### Step 1: Backend Setup (Server-Side)

Security Warning: Never expose your Hyperswitch API-Key on the frontend. You must create a backend endpoint that acts as a proxy

**Frontend → requests session → Your Backend → requests token (using API Key) → Hyperswitch API**

#### Step 1.1: Create the Token Endpoint

Create a route (e.g., /embedded/hyperswitch) in your backend application.

Required Headers for Hyperswitch Call:

* api-key: Your secret API key.
* X-profile-id: The specific profile ID you want the embedded component to access. The token is scoped to this profile.

The Hyperswitch API responds with a JSON body containing the embedded token in the `token` field:

```json
{
  "token": "<embedded-jwt>"
}
```

{% code title="server.js" %}

```javascript
const express = require('express');
const cors = require('cors');
const axios = require('axios');

const app = express();
const port = 4000;

app.use(cors());
app.use(express.json());

// Sandbox: https://app.hyperswitch.io/api
// Production: https://live.hyperswitch.io/api
const HYPERSWITCH_BASE_URL = 'https://app.hyperswitch.io/api';

app.get('/embedded/hyperswitch', async (req, res) => {
  try {
    const response = await axios.get(
      `${HYPERSWITCH_BASE_URL}/embedded/token`,
      {
        headers: {
          'api-key': process.env.HYPERSWITCH_API_KEY,       // STORE IN ENV VARIABLES
          'X-profile-id': process.env.HYPERSWITCH_PROFILE_ID,
          'Content-Type': 'application/json'
        }
      }
    );

    // response.data is { token: "<embedded-jwt>" }
    res.json({
      success: true,
      message: 'Token fetched successfully',
      data: response.data
    });

  } catch (error) {
    console.error('Error fetching token:', error.message);

    res.status(500).json({
      error: 'Failed to fetch token from Hyperswitch API',
      details: error.message
    });
  }
});

app.listen(port, () => {
  console.log(`Server listening at http://localhost:${port}`);
});

```

{% endcode %}

### Step 2: Choose Your Integration Method

You must choose one:

* Core (JavaScript Only / HTML)
* React Integration

{% hint style="info" %}
**When is `fetchToken` called?**

* Immediately when `loadHyperswitch()` runs (the token is fetched eagerly, before any component is mounted).
* Automatically whenever the SDK detects the session has expired (auto-refresh).

Create the Hyperswitch instance **once** and reuse it. Calling `loadHyperswitch()` repeatedly (for example, on every React render) triggers a new token request each time.
{% endhint %}

#### 2A: HTML-JS Integration

**2A.1 Install the package:**

```bash
npm install @juspay-tech/hyperswitch-control-center-embed-core
```

**2A.2 Import the SDK in Your Application**

Import (ES Module):

```javascript
import { loadHyperswitch } from "@juspay-tech/hyperswitch-control-center-embed-core";
```

**OR**

Import (CommonJS):

```javascript
const { loadHyperswitch } = require("@juspay-tech/hyperswitch-control-center-embed-core");
```

**2A.3: Example app.js Implementation**

```html
<div id="connectors-root"></div>
<div id="payments-root"></div>
<div id="refunds-root"></div>
```

```javascript
import { loadHyperswitch } from "@juspay-tech/hyperswitch-control-center-embed-core";

document.addEventListener("DOMContentLoaded", async function () {

  const fetchToken = async () => {
    try {
      const response = await fetch(
        "http://localhost:4000/embedded/hyperswitch",
        {
          method: "GET",
          headers: {
            "Content-Type": "application/json"
          }
        }
      );

      if (!response.ok) {
        return undefined;
      }

      const responseData = await response.json();
      const token = responseData.data?.token || responseData.token;

      return token;

    } catch (err) {
      return undefined;
    }
  };

  // fetchToken is called immediately here
  const hyperswitch = loadHyperswitch({
    fetchToken: fetchToken
  });

  // Sandbox: https://app.hyperswitch.io | Production: https://live.hyperswitch.io
  const HYPERSWITCH_URL = "https://app.hyperswitch.io";

  const connectorConfig = hyperswitch.create("connectors", { url: HYPERSWITCH_URL });
  connectorConfig.mount("#connectors-root");

  const payments = hyperswitch.create("payments", { url: HYPERSWITCH_URL });
  payments.mount("#payments-root");

  const refunds = hyperswitch.create("refunds", { url: HYPERSWITCH_URL });
  refunds.mount("#refunds-root");

});

```

To remove a component, call `component.destroy()` (for example, `payments.destroy()`).

#### 2B: React Integration

**2B.1 Install the package:**

```bash
npm install @juspay-tech/hyperswitch-control-center-embed-react
```

The core package is installed as a dependency.

**2B.2 Import the SDK in Your Application**

```javascript
import React, { useState } from 'react';
import './App.css';
import 'tailwindcss/tailwind.css';
import { loadHyperswitch } from '@juspay-tech/hyperswitch-control-center-embed-core';
import {
  HyperswitchProvider,
  ConnectorConfiguration,
  Payments,
  Refunds
} from '@juspay-tech/hyperswitch-control-center-embed-react';
```

**2B.3 Example app.js Implementation**

Key Concept: `fetchToken` is called as soon as `loadHyperswitch()` runs, and again automatically whenever the session expires. Wrapping `loadHyperswitch()` in a `useState` initializer (as below) ensures the instance, and therefore the initial token request, is created only once.

```javascript
// Sandbox: https://app.hyperswitch.io | Production: https://live.hyperswitch.io
const HYPERSWITCH_URL = 'https://app.hyperswitch.io';

function App() {
  const [errorMessage, setErrorMessage] = useState(null);

  const [hyperswitchInstance] = useState(() => {

    const fetchToken = async () => {
      try {
        const response = await fetch(
          'http://localhost:4000/embedded/hyperswitch',
          {
            method: "GET",
            headers: {
              'Content-Type': 'application/json'
            }
          }
        );

        if (!response.ok) {
          const errorData = await response.json();
          const errorMsg = errorData.error || 'Network error fetching token';
          setErrorMessage(errorMsg);
          return undefined;
        }

        const responseData = await response.json();
        const token = responseData.data?.token || responseData.token;

        return token;

      } catch (err) {
        setErrorMessage(err.message);
        return undefined;
      }
    };

    return loadHyperswitch({
      fetchToken: fetchToken
    });

  });

  return (
    <div className="h-screen bg-gray-100 p-10 text-gray-700">
      {errorMessage ? (
        <div className="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-4">
          <strong>Error: </strong>
          <span>{errorMessage}</span>
        </div>
      ) : (
        <HyperswitchProvider hyperswitchInstance={hyperswitchInstance}>
          <ConnectorConfiguration url={HYPERSWITCH_URL} />
          <Payments url={HYPERSWITCH_URL} />
          <Refunds url={HYPERSWITCH_URL} />
        </HyperswitchProvider>
      )}
    </div>
  );
}

export default App;

```

#### Server-side rendering (Next.js)

The components render their content in the browser only. In frameworks with server components, such as the **Next.js App Router**, render them inside a Client Component by adding the `'use client'` directive at the top of the file:

{% code title="app/payments/HyperswitchPayments.jsx" %}

```javascript
'use client';

import { useState } from 'react';
import { loadHyperswitch } from '@juspay-tech/hyperswitch-control-center-embed-core';
import {
  HyperswitchProvider,
  Payments
} from '@juspay-tech/hyperswitch-control-center-embed-react';

export default function HyperswitchPayments() {
  const [hyperswitchInstance] = useState(() =>
    loadHyperswitch({
      fetchToken: async () => {
        const response = await fetch('/api/embedded/hyperswitch');
        const responseData = await response.json();
        return responseData.data?.token || responseData.token;
      }
    })
  );

  return (
    <HyperswitchProvider hyperswitchInstance={hyperswitchInstance}>
      <Payments url="https://app.hyperswitch.io" />
    </HyperswitchProvider>
  );
}
```

{% endcode %}

You can then import this Client Component from any Server Component page.

### Components

#### Connector Configuration

Core name: `connectors` | React: `<ConnectorConfiguration />`

A self-serve interface for your users to select payment processors, enter credentials and manage connector settings.

#### Payments

Core name: `payments` | React: `<Payments />`

Renders the payments list and payment details views.

* **List view**: All payments for the profile, with search and filters.
* **Detail view**: Full details of a single payment, including status, amounts, attempts and associated refunds.

Actions available from the payment detail view:

| Action  | Available when                                        | Description                                               |
| ------- | ----------------------------------------------------- | --------------------------------------------------------- |
| Refund  | Payment status is `succeeded` or `partially_captured` | Issue a full or partial refund for the payment            |
| Capture | Payment status is `requires_capture`                  | Capture a payment that was authorized with manual capture |
| Void    | Payment status is `requires_capture`                  | Cancel an authorized payment before it is captured        |

{% hint style="info" %}
Actions are shown only to users with permission to manage operations. Refund is disabled for connectors that do not support refunds.
{% endhint %}

#### Refunds

Core name: `refunds` | React: `<Refunds />`

Renders the refunds list and refund details views.

* **List view**: All refunds for the profile, with search and filters.
* **Detail view**: Full details of a single refund, including its status and amount.

#### Modals

Modals opened inside a component (for example, the Refund, Capture and Void dialogs) are displayed over the full host page by default. While a modal is open, the SDK stretches the component's iframe across the window and locks page scrolling, and restores both when the modal closes.

To keep modals inside the component, set `fullPageModals` to `false`:

```javascript
// Core
hyperswitch.create('payments', { url: 'https://app.hyperswitch.io', fullPageModals: false });

// React
<Payments url="https://app.hyperswitch.io" fullPageModals={false} />
```

Full-page modals rely on `position: fixed`. If an ancestor of the mount point has a CSS `transform`, `filter`, `perspective` or `contain`, or creates a stacking context below other page content, the modal can be clipped or covered. Set `fullPageModals` to `false` in that layout.

### Customizing the appearance

Pass a theme configuration as `initConfig` to `loadHyperswitch()` to match the components to your brand. The theme applies to every component created from that instance.

```javascript
const hyperswitch = loadHyperswitch({
  fetchToken,
  initConfig: {
    primaryColor: '#0066ff',
    backgroundColor: '#ffffff',
    buttons: {
      primary: {
        backgroundColor: '#0066ff',
        textColor: '#ffffff',
        hoverBackgroundColor: '#0052cc'
      },
      secondary: {
        backgroundColor: '#f0f0f0',
        textColor: '#333333',
        hoverBackgroundColor: '#e0e0e0'
      }
    }
  }
});
```

All fields in `initConfig` are optional. Omitted fields use the default Control Center theme. See **MerchantTheme (initConfig)** in the API Reference below for the full list.

### Content Security Policy

If you have deployed a [Content Security Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP), include the Control Center origin (`https://app.hyperswitch.io` for sandbox, `https://live.hyperswitch.io` for production) in your `frame-src` directive.

### API Reference

#### 1. loadHyperswitch(options)

Initializes the SDK logic and returns a Hyperswitch instance. `fetchToken` is invoked immediately.

| Parameter    | Type                                 | Required | Description                                                                                                        |
| ------------ | ------------------------------------ | -------- | ------------------------------------------------------------------------------------------------------------------ |
| `fetchToken` | `() => Promise<string \| undefined>` | Yes      | Retrieves a fresh embedded token from your backend. Return the token string on success, or `undefined` on failure. |
| `initConfig` | `MerchantTheme`                      | No       | Theme customization object. See **MerchantTheme (initConfig)** below.                                              |

#### 2. HyperswitchProvider

Context provider that holds the authentication state.

* **hyperswitchInstance**: The object returned by loadHyperswitch.

The React package also exports a `useHyperswitchInstance` hook that returns the instance from the nearest provider.

#### 3. ConnectorConfiguration

The UI Component that renders the connector settings form. Accepts the component props listed under **Payments and Refunds** below.

* **url (string)**: The base URL of the Control Center that serves the component.
  * Sandbox: <https://app.hyperswitch.io>
  * Production: <https://live.hyperswitch.io>
  * Default (if omitted): <http://localhost:9000> (local development only)

#### 4. Payments and Refunds

`<Payments />` renders the payments list and payment details. `<Refunds />` renders the refunds list and refund details. In the core SDK, create them with `hyperswitch.create('payments', options)` and `hyperswitch.create('refunds', options)`.

All components (`ConnectorConfiguration`, `Payments`, `Refunds`, and core `hyperswitch.create(...)` options) accept:

| Prop              | Type                                                      | Description                                                                                               |
| ----------------- | --------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- |
| `url`             | `string`                                                  | Base URL of the Control Center that serves the component. Defaults to `http://localhost:9000` if omitted. |
| `width?`          | `string`                                                  | Width of the component container. Defaults to `100%`.                                                     |
| `height?`         | `string`                                                  | Initial height of the component container. The component resizes to fit its content.                      |
| `className?`      | `string`                                                  | Additional class names for the component container.                                                       |
| `style?`          | `Partial<CSSStyleDeclaration>`                            | Inline styles for the component container.                                                                |
| `fullPageModals?` | `boolean`                                                 | Display modals over the full host page. Defaults to `true`.                                               |
| `onResize?`       | `(dimensions: { width: number; height: number }) => void` | Called when the component is resized.                                                                     |

Core component methods:

* `component.mount(target)`: Mounts the component to a CSS selector or `HTMLElement`. Returns the component.
* `component.destroy()`: Removes the component from the page and cleans up its event listeners.

#### 5. MerchantTheme (initConfig)

| Property                                    | Type     | Description                       |
| ------------------------------------------- | -------- | --------------------------------- |
| `primaryColor?`                             | `string` | Primary accent color              |
| `backgroundColor?`                          | `string` | Page background color             |
| `buttons?.primary?.backgroundColor?`        | `string` | Primary button background color   |
| `buttons?.primary?.textColor?`              | `string` | Primary button text color         |
| `buttons?.primary?.hoverBackgroundColor?`   | `string` | Primary button hover color        |
| `buttons?.secondary?.backgroundColor?`      | `string` | Secondary button background color |
| `buttons?.secondary?.textColor?`            | `string` | Secondary button text color       |
| `buttons?.secondary?.hoverBackgroundColor?` | `string` | Secondary button hover color      |

TypeScript types `HyperswitchInitOptions`, `ElementOptions` and `MerchantTheme` are exported from `@juspay-tech/hyperswitch-control-center-embed-core`.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.hyperswitch.io/integration-guide/account-management/beta-embeddable-components/integration-reference.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
