> ## Documentation Index
> Fetch the complete documentation index at: https://docs.dari.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Link Web SDK

> Reference for integrating with the Link JavaScript SDK.

Prefer to learn with a walkthrough? See the [Quickstart](https://docs.dari.dev/link/quickstart.md).

## Installation

```bash npm theme={null}
npm install @mupt-ai/dari-gateway
```

```html Script Tag theme={null}
<script type="module">
  import { DariLink } from "https://cdn.jsdelivr.net/npm/@mupt-ai/dari-gateway@1/dist/link/client.js";
</script>
```

With npm, import the client where you use it:

```js Import Link theme={null}
import { DariLink } from "@mupt-ai/dari-gateway/link/client";
```

The client is one file with no dependencies. It works in any framework: in React, call it from an event handler, as the samples below show.

### CSP Directives

If you are using a Content Security Policy (CSP), use the following directives to allow Link traffic:

```text CSP Directives theme={null}
connect-src https://routing.dari.dev;
script-src https://cdn.jsdelivr.net;
```

`connect-src` is your gateway's origin, which Link asks where to expect the result from. `script-src` is needed only for the script tag.

## open()

`DariLink.open` accepts one argument, a configuration `Object`, opens Link in a popup, and returns a `Promise`. The promise resolves with a `code` once your user allows your app, and rejects with a `LinkError` when they leave without allowing it.

Call `open` straight from a click handler, so the browser allows the popup. If the configuration comes from your server, pass a function that returns it (`DariLink.open(async () => ({ ... }))`): Link opens the popup first and then awaits it.

**Properties**

**gatewayUrl** `string` *required*

The environment to connect on: `https://routing.dari.dev` for hosted Dari, or your own gateway's URL.

**clientId** `string` *required*

Your app's `client_id`.

**redirectUri** `string` *required*

One of your app's registered redirect URIs. Link returns to it when the popup cannot reach your window. Its page must call [`callback()`](#callback).

**plans** `[string]`

The kinds of plan to offer. By default Link offers every kind your app can use.

Possible values: `openai_codex`, `anthropic_claude_code`, `github_copilot`, `xai_grok`, `opencode_go`, `meta_muse`, `vercel_token_pass`, `api_key`

**keyProviders** `[string]`

The providers whose API keys your app can use, such as `["openai", "openrouter"]`. By default Link offers every one. See [What Users Can Connect](https://docs.dari.dev/link/what-users-can-connect.md#api-keys).

**clients** `[string]`

The coding agents your app runs itself. A Claude plan serves only Claude Code, and a Meta Muse plan only Muse Code, so Link offers those plans only to an app that names the agent.

Possible values: `claude_code`, `codex`, `muse_code`, `opencode`, `pi`, `openclaw`, `hermes`

**purposes** `object`

What your app does with the plans, shown beside them in Link.

**properties**

**any\_app** `string`

For plans and keys that serve any app, such as `"Runs your evals"`.

**claude\_code** `string`

For plans that serve only Claude Code.

**muse\_code** `string`

For plans that serve only Muse Code.

**grantId** `string`

The `grant_id` of an existing connection. Opens Link in [update mode](https://docs.dari.dev/link/manage-connections.md#update-mode), where the user changes what that connection shares.

**onEvent** `callback`

A function that is called when your user reaches a step in Link. See [onEvent](#onevent).

**onExit** `callback`

A function that is called when your user leaves Link without allowing your app. See [onExit](#onexit).

**codeChallenge** `string`

A PKCE challenge made on your server, with `state`. See [Server-Made PKCE](#server-made-pkce).

**state** `string`

The `state` made with `codeChallenge`.

```js JavaScript theme={null}
button.onclick = async () => {
  const { code, codeVerifier } = await DariLink.open({
    gatewayUrl: "https://routing.dari.dev",
    clientId: "lnk_…",
    redirectUri: "https://myapp.com/dari/callback",
    onEvent: (step) => {},
    onExit: ({ error, step }) => {},
  });
  // send code and codeVerifier to your server
};
```

```tsx React theme={null}
const connect = async () => {
  const { code, codeVerifier } = await DariLink.open({
    gatewayUrl: "https://routing.dari.dev",
    clientId: "lnk_…",
    redirectUri: "https://myapp.com/dari/callback",
    onEvent: (step) => {},
    onExit: ({ error, step }) => {},
  });
  // send code and codeVerifier to your server
};

return <button onClick={connect}>Connect with Dari</button>;
```

**Returns**

**code** `string`

A temporary code for the new connection. Send it to your server, which exchanges it at [`/v1/link/token`](https://docs.dari.dev/link/reference/http#exchange-code). It is single-use and expires in 10 minutes.

**codeVerifier** `nullable, string`

The PKCE verifier that redeems `code`. Send it to your server with the code. `null` when your server made the pair.

**state** `string`

The state of this Link session.

```js Result schema theme={null}
{
  code: 'dlk_code_9mVxq3hTnA1cJ7oYb0sKe2Rw',
  codeVerifier: 'w6uP8zQxHn3vTdKbY1mEoLr5cJ7sA0fG2iX4tNqWy9U',
  state: 'c0Vd3nXo7Q2kLm5PzR8tYw',
}
```

## onEvent

The `onEvent` callback is called when your user reaches a step in Link. It takes one argument, a `step` string. Use it to see where users drop off.

**Properties**

**step** `string`

The step the user just reached.

`connect_subscription`: The user has nothing to share yet and is connecting a plan or key.

`choose_plans`: The user is choosing which plans and keys your app may use.

```js JavaScript theme={null}
DariLink.open({
  ...,
  onEvent: (step) => {
    // send the step to your analytics
    analytics.track("dari_step", { step });
  },
});
```

## onExit

The `onExit` callback is called when your user leaves Link without allowing your app, just before `open` rejects. It takes one argument, an `Object` with the `error` and the last `step`. `open` rejects with a `LinkError` whose `code` is the same `error`.

**Properties**

**error** `string`

Why Link ended.

`access_denied`: The user chose Deny.

`popup_closed`: The user closed the popup.

`popup_blocked`: The browser blocked the popup. Call `open` straight from a click.

`insecure_context`: The page is not https or localhost, so it cannot make its PKCE pair. See [Server-Made PKCE](#server-made-pkce).

**step** `nullable, string`

The last step the user reached: `connect_subscription` or `choose_plans`. `denied` when the user chose Deny, and `null` when they reached no step.

```js JavaScript theme={null}
try {
  await DariLink.open({
    ...,
    onExit: ({ error, step }) => {
      analytics.track("dari_exit", { error, step });
    },
  });
} catch (error) {
  if (error.code === "popup_blocked") showAllowPopups();
}
```

```js Exit schema theme={null}
{
  error: 'popup_closed',
  step: 'choose_plans',
}
```

## callback()

`DariLink.callback` hands a result that arrived on your redirect URI back to the window that called `open`, then closes the popup. A popup that signed your user in along the way can lose its link to your window, and Link then returns to your redirect URI instead. Call `callback` on that page.

```js JavaScript theme={null}
DariLink.callback();
```

```html Script Tag theme={null}
<script src="https://routing.dari.dev/v1/link/callback.js"></script>
```

The script tag is the whole page: your gateway serves it. `callback` returns `false` when the page holds no Link result.

## renderButton()

`DariLink.renderButton` draws the standard **Connect with Dari** button into an element. It takes the element and a configuration `Object`.

**Properties**

**onClick** `callback` *required*

A function that is called when the button is pressed. Call `open` from it.

**theme** `string`

`dark` is a black button for light pages, and `light` a white button for dark pages.

Default: `dark`

**label** `string`

The button's text. Keep "Connect with Dari", or "Reconnect Dari" for a connection that is gone.

Default: `Connect with Dari`

```js JavaScript theme={null}
DariLink.renderButton(document.getElementById("connect-dari"), {
  onClick: connect,
  theme: "dark",
});
```

## Server-Made PKCE

`open` makes its PKCE pair in the page, which needs https or localhost. If your page is neither, or you want the verifier never to reach the browser, make the pair on your server and pass `codeChallenge` and `state` to `open`.

```ts Node theme={null}
import { createAuthorization } from "@mupt-ai/dari-gateway/link/client";

app.post("/api/dari/start", async (req, res) => {
  const { codeVerifier, codeChallenge, state } = await createAuthorization();
  req.session.dari = { codeVerifier, state };
  res.json({ codeChallenge, state });
});
```

```python Python theme={null}
import base64, hashlib, secrets

@app.post("/api/dari/start")
def start():
    code_verifier = secrets.token_urlsafe(32)
    digest = hashlib.sha256(code_verifier.encode()).digest()
    code_challenge = base64.urlsafe_b64encode(digest).rstrip(b"=").decode()
    state = secrets.token_urlsafe(16)
    session["dari"] = {"code_verifier": code_verifier, "state": state}
    return {"codeChallenge": code_challenge, "state": state}
```

```go Go theme={null}
func start(w http.ResponseWriter, r *http.Request) {
	random := func(bytes int) string {
		b := make([]byte, bytes)
		rand.Read(b) // crypto/rand
		return base64.RawURLEncoding.EncodeToString(b)
	}
	codeVerifier, state := random(32), random(16)
	digest := sha256.Sum256([]byte(codeVerifier))
	// Keep codeVerifier and state in your user's session.
	json.NewEncoder(w).Encode(map[string]string{
		"codeChallenge": base64.RawURLEncoding.EncodeToString(digest[:]),
		"state":         state,
	})
}
```

`open` then resolves with a `null` `codeVerifier`. Check the returned `state` against the session, and exchange the `code` with the verifier you kept.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.