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

# Auth SDK

> Integrate the Auth SDK for seamless user authentication

The Auth SDK is a Deck authored client-side component that your users interact with to connect their external accounts to your product and allow access to their data via the Deck API. It provides a secure interface that handles authentication and multi-factor authentication challenges.

<Columns cols={3}>
  <img src="https://mintcdn.com/decksoftwareinc/6z_od_uARNaJpzDg/images/widget_1.png?fit=max&auto=format&n=6z_od_uARNaJpzDg&q=85&s=dc1f9cd2e3992cd555535a094d9bd64c" alt="Auth SDK starting screen" width="786" height="1704" data-path="images/widget_1.png" />

  <img src="https://mintcdn.com/decksoftwareinc/6z_od_uARNaJpzDg/images/widget_2.png?fit=max&auto=format&n=6z_od_uARNaJpzDg&q=85&s=00985b8375ce14d5cb0b54bb0212ff04" alt="Auth SDK passing credentials" width="393" height="852" data-path="images/widget_2.png" />

  <img src="https://mintcdn.com/decksoftwareinc/6z_od_uARNaJpzDg/images/widget_3.png?fit=max&auto=format&n=6z_od_uARNaJpzDg&q=85&s=682fd78f18f2b0b8be70f7a05c24e870" alt="Auth SDK success" width="393" height="852" data-path="images/widget_3.png" />
</Columns>

## Prerequisites

* Your Deck API credentials. [Quickstart Guide](/guides/guides/quickstart)
* A webhook endpoint configured and ready to receive webhooks. [Quickstart Guide](/guides/guides/quickstart)
* Source GUIDs for the data sources you want to connect to. [Sources Guide](/guides/guides/sources)

## Flow Diagram

<img className="block dark:hidden" src="https://mintcdn.com/decksoftwareinc/srSH4-yXArfCRy4x/images/flow_new.png?fit=max&auto=format&n=srSH4-yXArfCRy4x&q=85&s=efa4ceba0cde54b3d5a4deca372c271f" alt="Auth SDK flow diagram" noZoom width="1640" height="1497" data-path="images/flow_new.png" />

<img className="hidden dark:block" src="https://mintcdn.com/decksoftwareinc/srSH4-yXArfCRy4x/images/flow_new.png?fit=max&auto=format&n=srSH4-yXArfCRy4x&q=85&s=efa4ceba0cde54b3d5a4deca372c271f" alt="Auth SDK flow diagram" noZoom width="1640" height="1497" data-path="images/flow_new.png" />

## Integration Guide

<Steps>
  <Step title="Install the SDK">
    Add the Auth SDK script to your application. Supported platforms include React, Next.js, Expo, Vue, Angular, TanStack, and vanilla JavaScript.

    ```html theme={null}
    <script src="https://link.deck.co/link-initialize.js"></script>
    ```

    **For React/Next.js:** Dynamically load the script in a `useEffect`:

    ```javascript theme={null}
    useEffect(() => {
      const script = document.createElement('script');
      script.src = 'https://link.deck.co/link-initialize.js';
      script.async = true;
      document.body.appendChild(script);

      return () => {
        document.body.removeChild(script);
      };
    }, []);
    ```

    <Tip>
      See complete examples in our [SDK Quickstart](https://github.com/buildwithdeck/quickstart) repository.
    </Tip>
  </Step>

  <Step title="Set up environment variables">
    Configure your Deck API credentials as environment variables. These are required to generate SDK tokens and must never be exposed in frontend code. Both keys are available in your [Dashboard](https://dashboard.deck.co).

    **.env**

    ```bash theme={null}
    DECK_CLIENT_ID=your_client_id_here
    DECK_CLIENT_SECRET=your_secret_here
    ```
  </Step>

  <Step title="Generate a SDK Token">
    Create a server-side API endpoint to generate SDK tokens. Specify which data sources to make available using `source_ids`.

    The `source_ids` parameter controls which data sources appear in the Auth SDK for your users to select. You can specify one or multiple sources. Find source GUIDs in your [Dashboard](https://dashboard.deck.co) or the [Sources guide](/guides/guides/sources).

    <Note>
      Link tokens expire after **30 minutes** and are one-time use.
    </Note>

    ```bash highlight={6} theme={null}
    curl -X POST https://live.deck.co/api/v1/link/token/create \
      -H "Content-Type: application/json" \
      --header 'x-deck-client-id: <api-key>' \
      --header 'x-deck-secret: <api-key>' \
      -d '{
        "source_ids": ["b1af8246-0339-4833-9119-11da6bd68c13"]
      }'
    ```

    **Response:**

    ```json theme={null}
    {
      "link_token": "link-production-abc123..."
    }
    ```
  </Step>

  <Step title="Initialize the SDK">
    Add a button to your page that will launch the Auth SDK:

    ```html theme={null}
    <button id="connect-btn">Connect Your Account</button>
    ```

    Then fetch a SDK token from your backend and initialize the SDK:

    ```javascript theme={null}
    // Fetch link token from your backend
    const response = await fetch('/api/create_link_token', {
      method: 'POST',
    });
    const { link_token } = await response.json();

    // Initialize Auth SDK
    const deck = Deck.create({
      token: link_token,
      onSuccess({ job_guid }) {
        // Send job_guid to your backend to match with webhook
        fetch('/api/save_connection', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ job_guid })
        });
      },
      onError({ reason }) {
        if (reason === 'InvalidCredentials') {
          alert('Invalid credentials. Please try again.');
        }
      },
      onExit() {
        console.log('User closed Auth SDK');
      },
    });

    // Open Auth SDK when user clicks "Connect"
    document.getElementById('connect-btn').addEventListener('click', () => {
      deck.open();
    });
    ```
  </Step>

  <Step title="User Connects Their Account">
    When the user opens Auth SDK, they will:

    1. Consent to connect their credentials via Deck to your product.
    2. Select their data source from the options you chose to present them when creating the token
    3. Enter their credentials for the source they are connecting to.
    4. Complete any MFA challenges

    The SDK handles all of this automatically. Your `onSuccess` callback receives the `job_guid`, and your webhook receives both the `access_token` and `job_guid`.
  </Step>

  <Step title="Receive access tokens via webhook">
    Create a webhook endpoint to receive access tokens after successful authentication. Configure the webhook URL in your [Dashboard](https://dashboard.deck.co).

    **Expected Webhook Payload:**

    ```json highlight={4} theme={null}
    {
      "job_guid": "b3ab44de-f722-4685-ab3a-b27b369e859b",
      "output": {
        "access_token": "access-production-34343434-bcbc-34bc-34bc-343434343434"
      },
      "webhook_type": "Job",
      "webhook_code": "EnsureConnection",
      "environment": "Production"
    }
    ```
  </Step>

  <Step title="Use Access Tokens to Run Jobs">
    Once you receive the `access_token` via webhook, use it to run jobs on behalf of the user. Jobs can read data (e.g., fetch documents, invoices) or write data (e.g., submit orders, update records).

    See the [jobs guide](/guides/guides/jobs) for more information on available jobs and how to run them.
  </Step>
</Steps>

## Customization Options

You can customize the Auth SDK's appearance and behavior by passing additional parameters when creating the SDK token in Step 2. See the complete [API reference](https://docs.deck.co/api-reference-v1/auth-sdk/create-an-sdk-token) for all available options.

<AccordionGroup>
  <Accordion title="Language" icon="language">
    Set the SDK's display language:

    ```json theme={null}
    {
      "language": "EN"
    }
    ```

    **Supported languages:** `EN` (English), `ES` (Spanish), `FR` (French), `PT` (Portuguese), `DE` (German)
  </Accordion>

  <Accordion title="Filter by Source Type" icon="filter">
    Limit sources by their type (e.g., utility, telecom, logistics):

    ```json theme={null}
    {
      "source_types": ["utility", "telecom"]
    }
    ```
  </Accordion>

  <Accordion title="Update Mode" icon="rotate">
    Launch the SDK in update mode to refresh an existing connection:

    ```json theme={null}
    {
      "update": {
        "access_token": "access-production-34343434-bcbc-34bc-34bc-343434343434",
        "mode": "UpdateCredentials"
      }
    }
    ```

    Use this when a user needs to update their credentials or re-authenticate due to password changes.
  </Accordion>

  <Accordion title="Custom Webhook URL" icon="webhook">
    Override the default webhook URL for this session:

    ```json theme={null}
    {
      "webhook_url": "https://yourdomain.com/custom-webhook"
    }
    ```
  </Accordion>
</AccordionGroup>

## Browser Support

Deck officially supports the Auth SDK on the following browsers:

| Desktop      | Mobile              |
| ------------ | ------------------- |
| Chrome 109+  | Android Chrome 121+ |
| Safari 15.6+ | iOS Safari 15.6+    |
| Firefox 115+ |                     |
| Edge 120+    |                     |
| Opera 105+   |                     |

## SDK Reference

### Initialization Parameters

<ParamField path="token" type="string" required>
  The token is required to launch the Auth modal. Tokens expire after **30 minutes** and are one-time use.
</ParamField>

<ParamField path="onSuccess" type="function" required>
  Callback function called when a connection is successfully created.

  **Receives:** `{ job_guid: string }`

  ```javascript theme={null}
  onSuccess({ job_guid }) {
    // Send job_guid to your backend
    fetch('/api/save_connection', {
      method: 'POST',
      body: JSON.stringify({ job_guid })
    });
  }
  ```
</ParamField>

<ParamField path="onError" type="function">
  Callback function triggered when the SDK encounters an error.

  **Receives:** `{ reason: string }`

  **Common error reasons:**

  * `InvalidCredentials` - Username or password is incorrect

  ```javascript theme={null}
  onError({ reason }) {
    if (reason === 'InvalidCredentials') {
      showError('Invalid credentials. Please try again.');
    }
  }
  ```
</ParamField>

<ParamField path="onExit" type="function">
  Callback function triggered when a user closes or exits the SDK without completing the flow.

  ```javascript theme={null}
  onExit() {
    console.log('User closed Auth SDK');
  }
  ```
</ParamField>

### SDK Functions

<AccordionGroup>
  <Accordion title="open()" icon="play">
    Displays the Auth SDK and starts the authentication flow.

    ```javascript theme={null}
    const deck = Deck.create({ token, onSuccess, onError, onExit });
    deck.open();
    ```

    Call this method when the user clicks your "Connect Account" button.
  </Accordion>

  <Accordion title="exit()" icon="xmark">
    Closes the Auth SDK programmatically and triggers the `onExit()` callback.

    ```javascript theme={null}
    deck.exit();
    ```

    Use this to close the SDK from your code (e.g., after a timeout or user action).
  </Accordion>
</AccordionGroup>
