# Integrating the Link SDK (/data-api/guides/link-widget/integrating-the-link-sdk)

Step-by-step guide to integrate the Fiskil Link SDK



The [Fiskil Link SDK](https://github.com/Fiskil/link) makes it simple to launch the consent flow inside your web application. You provide an `auth_session_id` created on your backend, and the SDK handles the rest — from rendering the consent UI to returning the result of the flow.

<Callout type="info">
  To use this SDK, you'll need a Fiskil team account. If you don't have an account, you can [get in touch](https://www.fiskil.com/contact) for a quick demo. If you're new to the Fiskil platform, start with the [Quick Start Guide](/data-api/guides/getting-started/quick-start).
</Callout>

This guide covers `@fiskil/link` 1.0.0. If you're upgrading from an earlier version, see [Migrating to 1.0.0](#migrating-to-100).

Integration Flow [#integration-flow]

1) Install Link SDK [#1-install-link-sdk]

This step is only required if you're using Node.js — for browser usage, you can import the SDK directly from CDN.

```bash
npm install @fiskil/link
# or
pnpm add @fiskil/link
```

2) Create an Auth Session [#2-create-an-auth-session]

On your backend, call the [`/v1/auth/session`](/data-api/api-reference/create-auth-session) endpoint with the end user ID. The `redirect_uri` and `cancel_uri` can be left blank (empty string) but `end_user_id` is required.

```bash
curl --request POST \
  --url https://api.fiskil.com/v1/auth/session \
  --header 'Authorization: Bearer ${access_token}' \
  --header 'Content-Type: application/json' \
  --data '{"end_user_id": "${end_user_id}"}'
```

3) Launch the SDK [#3-launch-the-sdk]

In your frontend, call the `link()` function with the `auth_session_id` to open the consent flow. On success, the result contains `consents`, an array of consent IDs. If the flow fails, the promise rejects with a `LinkError`.

4) Handle the Result [#4-handle-the-result]

When the flow finishes, the SDK resolves with `{ consents: string[], redirectURL?: string }`.
If the flow fails or the user exits, it rejects with a typed error.

Quick Start (ESM / TypeScript) [#quick-start-esm--typescript]

```typescript
import { link, type LinkError } from '@fiskil/link';

// Start the consent flow
const flow = link('auth_session_id');

try {
  const result = await flow;
  for (const consentId of result.consents) {
    console.log('Consent ID:', consentId);
    // Handle each consent in your application
  }
} catch (err) {
  const error = err as LinkError;
  console.log('Link error code:', error.code, error.details);
  if (error.code === 'LINK_INVALID_SESSION') flow.close();
}

// To cancel the flow programmatically
// flow.close();
```

Quick Start (UMD / CDN) [#quick-start-umd--cdn]

```html
<!-- Include the SDK from the Fiskil CDN -->
<!-- Pin the SDK version in production so upgrades are deliberate. -->
<script src="https://cdn.jsdelivr.net/npm/@fiskil/link@1.0.0/dist/fiskil-link.umd.js"></script>
<script>
  // Launch the consent flow with your auth_session_id
  const flow = FiskilLink.link('auth_session_id');

  // Handle the result
  flow
    .then((result) => {
      console.log('Consent IDs:', result.consents);
      // Handle every consent ID in the array
    })
    .catch((err) => {
      console.error('Consent failed:', err.code, err.details);
      if (err.code === 'LINK_INVALID_SESSION') flow.close();
    });

  // You can also close the flow programmatically if needed:
  // flow.close();
</script>
```

API Usage [#api-usage]

link(sessionId, options?) [#linksessionid-options]

Creates and mounts the consent UI. Returns a `LinkFlow` object that is both:

* a **Promise** that resolves with a `LinkResult` on success or rejects with a `LinkError` on failure, and
* a **controller** with `.close()` to cancel the flow programmatically

Options [#options]

| Option      | Type     | Description                                                                           |
| ----------- | -------- | ------------------------------------------------------------------------------------- |
| `timeoutMs` | `number` | Maximum duration of the consent flow in milliseconds. Default: `600000` (10 minutes). |

Result [#result]

When the consent flow completes successfully, the promise resolves with the following payload:

```typescript
type LinkResult = {
  consents: string[];
  redirectURL?: string;
};
```

* `consents` — an array containing one or more consent IDs. Handle every ID, even if your current flow only returns one.
* `redirectURL` — the redirect URL, if provided. It is optional and is not required for a successful result.

The SDK ignores completion messages with empty or invalid consent IDs and waits for a valid result or the flow timeout. Use [webhooks](/data-api/guides/core-concepts/webhooks) to confirm when data is ready.

Error Handling [#error-handling]

The promise rejects with a `LinkError` if the flow fails. Known error types are returned in `code`. Unknown error types use `LINK_INTERNAL_ERROR`, with the original value preserved in `details.error_type`.

For consent and auth-session errors, `details` can include `error_id`, `error_type`, `error_description` and `error_uri`. These fields may be absent. The exported type is `unknown`, so narrow it before reading individual fields.

Errors in a callback URL are also handled by the SDK. A non-empty `error` or `error_type` takes precedence over a completion result, including for relative or URL-encoded callback URLs.

```typescript
interface LinkError extends Error {
  name: 'LinkError';
  code: LinkErrorCode;
  details?: unknown;
}
```

Error Codes [#error-codes]

| Code                                | Description                                                                                                |
| ----------------------------------- | ---------------------------------------------------------------------------------------------------------- |
| `LINK_NOT_FOUND`                    | Consent UI container not found in DOM                                                                      |
| `LINK_TIMEOUT`                      | Flow exceeded timeout duration                                                                             |
| `LINK_USER_CANCELLED`               | User cancelled or flow closed programmatically                                                             |
| `LINK_INVALID_SESSION`              | The Auth Session is invalid; the iframe remains mounted until you call `flow.close()`                      |
| `AUTH_SESSION_INVALID`              | The Auth Session is invalid or no longer active; create a new session before reopening Link                |
| `LINK_ORIGIN_MISMATCH`              | Message received from unexpected origin                                                                    |
| `LINK_INTERNAL_ERROR`               | An unrecognised error occurred; the original error type is available in `details.error_type` when provided |
| `CONSENT_UPSTREAM_PROCESSING_ERROR` | Institution-level error during consent                                                                     |
| `CONSENT_ENDUSER_DENIED`            | User denied consent                                                                                        |
| `AUTH_SESSION_CANCELLED`            | Non-retryable: hosted authorisation was cancelled; start a new authorisation session before reopening Link |
| `CONSENT_OTP_FAILURE`               | OTP verification failed                                                                                    |
| `CONSENT_ENDUSER_INELIGIBLE`        | User not eligible for data sharing                                                                         |
| `CONSENT_TIMEOUT`                   | The institution's consent flow timed out                                                                   |

For `LINK_INVALID_SESSION`, call `flow.close()` to remove the retained iframe, including after the promise has rejected. For `AUTH_SESSION_INVALID` and other failures, the SDK removes the iframe automatically. Calling `flow.close()` while the flow is pending rejects with `LINK_USER_CANCELLED`.

For troubleshooting guidance, see [Error Types](/data-api/api-reference/errors#error-types).

React Integration Example [#react-integration-example]

```tsx
import { useState } from 'react';
import { link, type LinkError } from '@fiskil/link';

function LinkAccountButton({ authSessionId, onSuccess }: {
  authSessionId: string;
  onSuccess: (consents: string[]) => void;
}) {
  const [loading, setLoading] = useState(false);

  const handleClick = async () => {
    setLoading(true);
    const flow = link(authSessionId);
    try {
      const result = await flow;
      onSuccess(result.consents);
    } catch (err) {
      const error = err as LinkError;
      console.error('Link failed:', error.code, error.details);
      if (error.code === 'LINK_INVALID_SESSION') flow.close();
    } finally {
      setLoading(false);
    }
  };

  return (
    <button onClick={handleClick} disabled={loading}>
      {loading ? 'Connecting…' : 'Link Account'}
    </button>
  );
}
```

Migrating to 1.0.0 [#migrating-to-100]

Version 1.0.0 changes the success result from `result.consentID` to `result.consents`, an array of consent IDs.

1. Upgrade with `npm install @fiskil/link@1.0.0`, or update your CDN URL to `@fiskil/link@1.0.0`.
2. Update result handlers, callback types and any WebView bridge payloads to accept `string[]`. Handle every ID rather than selecting the first one. `redirectURL` remains optional.
3. Handle `AUTH_SESSION_INVALID` and `AUTH_SESSION_CANCELLED` by creating a new Auth Session before reopening Link. Unknown error types now use `LINK_INTERNAL_ERROR`; use `details.error_type` for the original value. If you receive `LINK_INVALID_SESSION`, call `flow.close()` to remove the retained iframe.
4. Check single and multiple consent results, cancellation, invalid sessions and timeouts before deploying.

The SDK still accepts legacy completion messages containing `consentID` and converts them to `consents: [consentID]`. Your application always receives the new result shape. The SDK sends its version automatically as `sdkVersion`; no configuration is required.

Next Steps [#next-steps]

* Review the [Flow Overview](/data-api/guides/link-widget/flow-overview) to understand the user experience.
* Set up [Webhooks](/data-api/guides/core-concepts/webhooks) to listen for consent events.
* Begin retrieving data through the [Banking API](/data-api/api-reference#banking-api) or [Energy API](/data-api/api-reference#energy-api).
