# Vault JS

A vanilla JavaScript library to embed [Apideck Vault](https://www.apideck.com/products/vault) in any web application.

This guide will get you up and running with the Vault component. To get started, follow these 3 steps:

- [Step 1: Setup Apideck](#step-1-setup-apideck)
- [Step 2: Create a session](#step-2-create-a-session)
- [Step 3: Add Vault JS](#step-3-add-vault-js)

## Step 1: Setup Apideck

### Create an account

If you haven't already, head over to our [Signup page](https://www.apideck.com/signup?products=unify&source=docs-vault-js) and create an account. Choose an application name and a subdomain. Afterward, you will be redirected to the Apideck dashboard.

### Enable Unified APIs and connectors

Go to the [Unified APIs](https://platform.apideck.com) page in the Apideck dashboard. Choose one or more Unified APIs to enable. You'll see a list of the available connectors for each Unified API. Choose a couple of connectors to enable. The Unified APIs and connectors you select become available to your users in [Vault](https://developers.apideck.com/apis/vault/reference).

### Get your API key and Application ID

Go to the [API Keys](https://platform.apideck.com/configuration/api-keys) page in the Apideck dashboard. Copy your application ID and API key.
If your API key ever gets compromised, you can regenerate it on this page.

![API keys overview](/get-started/api-keys.png)

## Step 2: Create a session

Vault lets your users (called consumers in Apideck) easily connect and configure integrations. You can create a consumer through a Vault session through the following endpoint https://developers.apideck.com/apis/vault/reference#tag/Sessions.

Most of the time, this is an ID of your internal data model that represents a user or account in your system. E.g., account:12345. If the consumer doesn't exist yet, Vault will upsert a consumer based on your ID.

> **Note 🚨**
>
> Session creation should always happen server-side to prevent token leakage.

Use the API call below to create a session for a consumer. This will return a Vault URL that you forward to a consumer to connect integrations.

```sh meta=terminal
curl --request POST \
  --url 'https://unify.apideck.com/vault/sessions' \
  --header 'Authorization: Bearer {API_KEY}' \
  --header 'x-apideck-app-id: {APP_ID}' \
  --header 'x-apideck-consumer-id: {CONSUMER_ID}' \
```

You can also use one of our [SDKs](/sdks/node) to create a session, like for example the Node SDK:

```sh meta=terminal
npm install @apideck/unify
```

Below is an example of creating a function to create a session:

```ts meta=/api/vault/sessions.ts
import { Apideck } from '@apideck/unify'

const createSession = async (_, res) => {
  const apideck = new Apideck({
    apiKey: process.env.API_KEY ?? '',
    appId: process.env.APP_ID ?? '',
    consumerId: 'test-consumer'
  })
  const settings = {}
  const { data } = await apideck.vault.sessions.create({
    session: settings
  })

  res.json(data)
}
```

The returned `data` object will include the `session_token` that you can use pass as the `jwt` prop to the `Vault` component.
It also includes a `session_uri`, which is a link to the Hosted Vault application. You can use this link if you don't want to use `vault-js` and redirect the user to the hosted solution.

### Customizing the session

When creating a session, you can customize the Vault experience by providing various settings, for example:

```js
const settings = {
  allow_actions: ['delete', 'disconnect', 'reauthorize'], // Leave empty to hide all.
  hide_resource_settings: true, // Hide configurable resources for integrations
  unified_apis: ['crm', 'accounting'], // Only show these APIs (omit to show all)
  session_length: '1h', // Valid duration (max: 1 week)
  hide_guides: true // Hide Apideck connection guides
}
```

For all available settings and descriptions, see the [Vault API documentation](https://developers.apideck.com/apis/vault/reference#tag/Sessions/operation/sessionsCreate).

## Step 3: Add Vault JS

Vault JS lets your users authorize connectors and manage integration settings. It stores the credentials securely and lets you make authorized API calls on your consumers` (users) behalf.
To get started, install the component using NPM or Yarn.

### Installation

#### Package

```sh
npm install @apideck/vault-js
```

#### Script

If you don't want to set up a build environment, you can get `@apideck/vault-js` from a CDN like unpkg.com or jsdelivr.net and it will be globally available through the `window.ApideckVault` object.

```html
<script src="https://cdn.jsdelivr.net/npm/@apideck/vault-js"></script>
```

### Usage

Pass the JWT you got from the Vault session to `@apideck/vault-js`:

```js
import { ApideckVault } from '@apideck/vault-js'

ApideckVault.open({
  token: 'REPLACE_WITH_SESSION_TOKEN'
})
```

If you want to only show integrations for a single Unified API, you can do that by passing the `unifiedApi` option. If you want to open Vault for only a single integration, you can provide the `serviceId` option.

```js
import { ApideckVault } from '@apideck/vault-js'

ApideckVault.open({
  token: 'REPLACE_WITH_SESSION_TOKEN',
  unifiedApi: 'accounting',
  serviceId: 'quickbooks'
})
```

If you want to get notified when the modal opens and closes, you can provide the `onReady` and `onClose` options.

```js
import { ApideckVault } from '@apideck/vault-js'

ApideckVault.open({
  token: 'REPLACE_WITH_SESSION_TOKEN',
  onClose: () => {
    console.log('closed!')
  },
  onReady: () => {
    console.log('ready!')
  }
})
```

If you want to open a specific view you can pass the `initialView` prop. The available views are `settings`, `configurable-resources`, and `custom-mapping`.

```js
import { ApideckVault } from '@apideck/vault-js'

ApideckVault.open({
  token: 'REPLACE_WITH_SESSION_TOKEN',
  unifiedApi: 'accounting',
  serviceId: 'quickbooks',
  initialView: 'custom-mapping'
})
```

You can also close the modal programmatically by calling `ApideckVault.close()`.

If you want to open Vault in a specific language you can add the `locale` prop. The available locales are `en` (default), `nl`, `de`, `fr`, and `es`.

```js
import { ApideckVault } from '@apideck/vault-js'

ApideckVault.open({
  token: 'REPLACE_WITH_SESSION_TOKEN',
  locale: 'nl'
})
```

If you want to show a language switch at the bottom of the modal you can add the `showLanguageSwitch` prop.

```js
import { ApideckVault } from '@apideck/vault-js'

ApideckVault.open({
  token: 'REPLACE_WITH_SESSION_TOKEN',
  showLanguageSwitch: true
})
```

If you want to show a logo on top of the modal, you can set the `logo` property on the `theme` object you can provide through the session. [View Vault API documentation](https://developers.apideck.com/apis/vault/reference#operation/sessionsCreate).

### Properties

| Property           | Type                             | Required | Default | Description                                                                                                                                      |
| ------------------ | -------------------------------- | -------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------ |
| token              | string                           | true     | -       | The JSON Web Token returned from the [Create Session API](https://docs.apideck.com/apis/vault/reference#operation/sessionsCreate)                |
| showAttribution    | boolean                          | false    | true    | Show "Powered by Apideck" in the backdrop of the modal backdrop                                                                                  |
| open               | () => void                       | false    | -       | Function to open the Vault modal                                                                                                                 |
| close              | () => void                       | false    | -       | Function to close the Vault modal                                                                                                                |
| onReady            | () => void                       | false    | -       | Function that gets called when the modal is opened                                                                                               |
| onClose            | () => void                       | false    | -       | Function that gets called when the modal is closed                                                                                               |
| onConnectionChange | (connection: Connection) => void | false    | -       | Function that gets called when the user updates a connection. This can be linking their account, filling out settings or adding a new connection |
| onConnectionDelete | (connection: Connection) => void | false    | -       | Function that gets called when the user deletes a connection                                                                                     |
| unifiedApi         | string                           | false    | -       | When unifiedApi is provided it will only show integrations from that API.                                                                        |
| serviceId          | string                           | false    | -       | When unifiedApi and serviceId are provided Vault opens a single integration                                                                      |
| showConsumer       | boolean                          | false    | false   | If true it shows the current consumer metadata at the bottom of the modal                                                                        |
| showButtonLayout   | boolean                          | false    | false   | Use button layout instead of dropdown menu in TopBar for connection actions                                                                      |
| initialView        | ConnectionViewType               | false    | -       | Open Vault in a specific view for a connection session                                                                                           |
| locale             | string                           | false    | "en"    | Open Vault in a specific language: "en", "nl", "de", "fr" or "es"                                                                                |
| showLanguageSwitch | boolean                          | false    | false   | Show language switch at bottom                                                                                                                   |

### Demo

See a working demo [here](https://vault-demo.apideck.com/)
