If you prefer a typed experience over calling http endpoints directly, you can use our sdk @unkey/api.

Install

 npm install @unkey/api

Unkey Root Key

When creating, revoking or updating resources, you will need your root key — you can create a new one in the settings. Afterwards you need to provide it to the client:

import { Unkey } from "@unkey/api";

const unkey = new Unkey({ rootKey: "<UNKEY_ROOT_KEY>" });

Always keep your root key safe and reset it if you suspect it has been compromised.

Response format

Because forgetting to handle thrown errors properly in javascript is often forgotten, we have decided to explicitely return errors to be handled. Fortunately typescript helps us here and everything is typesafe.

Every method returns either an error or a result field, never both and never none.

{
  result: T // the result depends on what method you called
}

Checking for errors

To check for errors you use the error property, our errors are easy to read and provide a link to our documentation for more information.

import { verifyKey } from "@unkey/api";

const { result, error } = await verifyKey("key_123");

if (error) {
  // handle potential network or bad request error
  // a link to our docs will be in the `error.docs` field
  console.error(error.message);
  return;
}

if (!result.valid) {
  // do not grant access
  return;
}

// process request
console.log(result);

Options

The constructor accepts some options to customize the behavior:

Base Url

Run all requests agaisnt your own instance of unkey hosted on your own infrastructure.

baseUrl
string
default: "https://api.unkey.dev"

The age of the user. Cannot be less than 0

const unkey = new Unkey({
  //...
  baseUrl: "https://my.domain"
})

Retries

By default the client will retry on network errors, you can customize this behavior:

retry
attempts
integer

How often to retry

backoff
(retryCount: number) => number

A function that returns how many milliseconds to wait until the next attempt is made.

const unkey = new Unkey({
  // ...
  retry: {
    attempts: 3,
    backoff: (retryCount) => retryCount * 1000
  }
})

Cache

Configure the fetch cache behavior.

As of October 2023, the cache option is not yet implemented in cloudflare workers and will throw an error if used.

cache
string

Available options are: default, force-cache, no-cache, no-store, only-if-cached or reload.

const unkey = new Unkey({
  // ...
  cache: "no-cache"
})

Disable telemetry

By default, Unkey collects anonymous telemetry data to help us understand which versions of our SDK is being used, and in which environment.

If you wish to disable this, you can do so by passing a boolean flag to the constructor:

const unkey = new Unkey({
  disableTelemetry: true
})

Was this page helpful?