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

# Introduction

> Learn how to integrate Dub with TypeScript.

## 1. Prerequisites

To follow this guide, you will need to:

* [Create a Dub account](https://d.to/try)
* [Create an API key](https://app.dub.co/settings/tokens)

## 2. Install and initialize the Dub TypeScript SDK

### 1. Install

Install the [Dub TypeScript SDK](/docs/sdks/typescript) using your preferred package manager:

**npm**

```bash theme={null}
npm install dub
```

**yarn**

```bash theme={null}
yarn add dub zod # zod is a peer dependency
```

**pnpm**

```bash theme={null}
pnpm add dub 
```

### 2. Initialize

Then, initialize the Dub TypeScript SDK with your API key.

```typescript lib/dub.ts theme={null}
import { Dub } from "dub";

export const dub = new Dub({
  token: process.env.DUB_API_KEY, // optional, defaults to DUB_API_KEY env variable
});
```

You can now use the `dub` object to interact with the Dub API.

```typescript theme={null}
import { dub } from "./lib/dub";
```

## 3. Create link

Let's create a short link using the [Dub TypeScript SDK](/docs/sdks/typescript).

```typescript create-link.ts theme={null}
const { shortLink } = await dub.links.create({
  url: "https://google.com",
});

console.log(shortLink); // e.g. https://dub.sh/abc123
```

> **Full list of available attributes for the Link model**
>
> **url** `string` *required*
>
> The destination URL of the short link.
>
> **domain** `string`
>
> The domain of the short link. If not provided, the primary domain for the
> workspace will be used (or `dub.sh` if the workspace has no domains).
>
> **key** `string`
>
> The short link slug. If not provided, a random 7-character slug will be
> generated.
>
> **keyLength** `number`
>
> The length of the short link slug. Defaults to 7 if not provided. When used
> with `prefix`, the total length of the key will be `prefix.length +
>       keyLength`.
>
> **externalId** `string | null`
>
> The ID of the link in your database. If set, it can be used to identify the
> link in future API requests (must be prefixed with 'ext\_' when passed as a
> query parameter). This key is unique across your workspace.
>
> **tenantId** `string | null`
>
> The ID of the tenant that created the link inside your system. If set, it can
> be used to fetch all links for a tenant.
>
> **programId** `string | null`
>
> The ID of the program the short link is associated with.
>
> **partnerId** `string | null`
>
> The ID of the partner the short link is associated with.
>
> **folderId** `string | null`
>
> The unique ID of an existing folder to assign the short link to.
>
> **prefix** `string`
>
> The prefix of the short link slug for randomly-generated keys (e.g. if prefix
> is `/c/`, generated keys will be in the `/c/:key` format). Will be ignored if
> key is provided.
>
> **trackConversion** `boolean` (default: false)
>
> Whether to track conversions for the short link. Defaults to `false` if not
> provided.
>
> **identifier** `string | null`
>
> The identifier of the short link that is unique across your workspace. If set,
> it can be used to identify your short link for client-side click tracking.
>
> **archived** `boolean` (default: false)
>
> Whether the short link is archived. Defaults to `false` if not provided.
>
> **publicStats** `boolean` (default: false)
>
> Deprecated: Use `dashboard` instead. Whether the short link's stats are
> publicly accessible. Defaults to `false` if not provided.
>
> **tagIds** `string | string[]`
>
> The unique IDs of the tags assigned to the short link.
>
> **tagNames** `string | string[]`
>
> The unique name of the tags assigned to the short link (case insensitive).
>
> **comments** `string | null`
>
> The comments for the short link.
>
> **expiresAt** `string | null`
>
> The date and time when the short link will expire at.
>
> **expiredUrl** `string | null`
>
> The URL to redirect to when the short link has expired.
>
> **password** `string | null`
>
> The password required to access the destination URL of the short link.
>
> **proxy** `boolean` (default: false)
>
> Whether the short link uses Custom Link Previews feature. Defaults to `false`
> if not provided.
>
> **title** `string | null`
>
> The custom link preview title (og:title). Will be used for Custom Link
> Previews if `proxy` is true. Learn more: [https://d.to/og](https://d.to/og)
>
> **description** `string | null`
>
> The custom link preview description (og:description). Will be used for Custom
> Link Previews if `proxy` is true. Learn more: [https://d.to/og](https://d.to/og)
>
> **image** `string | null`
>
> The custom link preview image (og:image). Will be used for Custom Link
> Previews if `proxy` is true. Learn more: [https://d.to/og](https://d.to/og)
>
> **video** `string | null`
>
> The custom link preview video (og:video). Will be used for Custom Link
> Previews if `proxy` is true. Learn more: [https://d.to/og](https://d.to/og)
>
> **rewrite** `boolean` (default: false)
>
> Whether the short link uses link cloaking. Defaults to `false` if not
> provided.
>
> **ios** `string | null`
>
> The iOS destination URL for the short link for iOS device targeting.
>
> **android** `string | null`
>
> The Android destination URL for the short link for Android device targeting.
>
> **geo** `object`
>
> Geographic targeting for the short link. Allows you to redirect users based on
> their location.
>
> **doIndex** `boolean` (default: false)
>
> Allow search engines to index your short link. Defaults to `false` if not
> provided. Learn more: [https://d.to/noindex](https://d.to/noindex)
>
> **utm\_source** `string | null`
>
> The UTM source of the short link. If set, this will populate or override the
> UTM source in the destination URL.
>
> **utm\_medium** `string | null`
>
> The UTM medium of the short link. If set, this will populate or override the
> UTM medium in the destination URL.
>
> **utm\_campaign** `string | null`
>
> The UTM campaign of the short link. If set, this will populate or override the
> UTM campaign in the destination URL.
>
> **utm\_term** `string | null`
>
> The UTM term of the short link. If set, this will populate or override the UTM
> term in the destination URL.
>
> **utm\_content** `string | null`
>
> The UTM content of the short link. If set, this will populate or override the
> UTM content in the destination URL.
>
> **ref** `string | null`
>
> The referral tag of the short link. If set, this will populate or override the
> `ref` query parameter in the destination URL.
>
> **webhookIds** `string[] | null`
>
> An array of webhook IDs to trigger when the link is clicked. These webhooks
> will receive click event data.
>
> **testVariants** `object[]`
>
> An array of A/B test URLs and the percentage of traffic to send to each URL.
> Requires 2-4 variants with percentages between 10-90.
>
> **testStartedAt** `string | null`
>
> The date and time when the tests started.
>
> **testCompletedAt** `string | null`
>
> The date and time when the tests were or will be completed.
>
> **tagId** `string | null`
>
> Deprecated: Use `tagIds` instead. The unique ID of the tag assigned to the
> short link.

Optionally, you can also pass an `externalId` field which is a unique identifier for the link in your own database to associate it with the link in Dub's system.

```typescript create-link-external-id.ts theme={null}
await dub.links.create({
  url: "https://google.com",
  externalId: "12345",
});
```

This will let you easily [update the link](#5-update-link) or [retrieve analytics](#6-retrieve-analytics-for-link) for it later on using the `externalId` instead of the Dub `linkId`.

## 4. Upsert link

Dub TypeScript SDK provides a method to upsert a link – where an existing link is updated if it exists, or a new link is created if it doesn't. so you don't have to worry about checking if the link already exists.

```typescript upsert-link.ts theme={null}
const { shortLink } = await dub.links.upsert({
  url: "https://www.google.com",
});

console.log(shortLink); // will always be the same short link
```

This way, you won't have to worry about checking if the link already exists when you're creating it.

## 5. Update link

Let's update an existing link using the Dub TypeScript SDK.

You can do that in two ways:

* Using the link's `linkId` in Dub's system.
* Using the link's `externalId` in your own database (prefixed with `ext_`).

```typescript update-link.ts theme={null}
// Update a link by its linkId
await dub.links.update("link_rWOKByP0bRMrstK8e4HPjprJ", {
  url: "https://www.google.uk", // new URL
});

// Update a link by its externalId
await dub.links.update("ext_12345", {
  url: "https://www.google.uk", // new URL
});
```

## 6. Retrieve analytics for link

Dub allows you to retrieve analytics for a link using the Dub TypeScript SDK.

```typescript get-analytics.ts theme={null}
import { ClicksTimeseries } from "dub/models/components";

// Retrieve the timeseries analytics for the last 7 days for a link
const response = await dub.analytics.retrieve({
  linkId: "clv3o9p9q000au1h0mc7r6l63",
  interval: "7d",
  groupBy: "timeseries",
});

const timeseries = response as ClicksTimeseries[];
```

Similarly, you can retrieve analytics for a link using the `externalId` field.

```typescript get-analytics-external-id.ts theme={null}
import { ClicksTimeseries } from "dub/models/components";

// Retrieve the timeseries analytics for the last 7 days for a link
const response = await dub.analytics.retrieve({
  externalId: "ext_12345",
  interval: "7d",
  groupBy: "timeseries",
});

const timeseries = response as ClicksTimeseries[];
```

## 7. Examples

> **[TypeScript Example](https://github.com/dubinc/examples/tree/main/typescript)**
>
> See the full example on GitHub.


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