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

const { result, error } = await verifyKey({ key: "key_123", apiId: "api_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);
{
  result: {
    valid: true,
    ownerId: "chronark",
    meta: {
      hello: "world"
    }
  }
}

Verify a key from your users.

Request

key
string
required

The key you want to verify.

apiId
string

The api this key belongs to. This will be required soon.

ratelimit
object

Override the behavior of the ratelimit for this verification.

cost
number
default: 1

The cost of this verification. This will be subtracted from the ratelimit. Use this if you need to ratelimit based on what the user is trying to access. For example, you may want to ratelimit a user based on the tokens they are using in the context of LLM APIs.

Response

result
valid
boolean
required

Whether or not this key is valid and has passed the ratelimit. If false you should not grant access to whatever the user is requesting

code
string

If the key is invalid this field will be set to the reason why it is invalid.

Possible values are:

  • NOT_FOUND - The key does not exist
  • FORBIDDEN - You are not allowed to verify this key. For example because of additional security checks like IP whitelists
  • USAGE_EXCEEDED - The key has been used up and is no longer valid
  • RATE_LIMITED - The verification has been blocked due to ratelimiting
  • DISABLED - the key is disabled
ownerId
string

If you have set an ownerId on this key it is returned here. You can use this to clearly authenticate a user in your system.

expires
int

The unix timestamp in milliseconds indicating when this key expires.

meta
object

This is the meta data you have set when creating the key.

Example:

{
  "billingTier": "PRO",
  "trialEnds": "2023-06-16T17:16:37.161Z"
}
ratelimit
Object

The current ratelimit state.

remaining
int

Shows how many more times this key may be verified before being invalidated. Only applies to keys where you have set a remaining count.

enabled
bool
required

Shows if the key is enabled or disabled.

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

const { result, error } = await verifyKey({ key: "key_123", apiId: "api_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);
{
  result: {
    valid: true,
    ownerId: "chronark",
    meta: {
      hello: "world"
    }
  }
}