Skip to main content
Docs

Using API keys

Clerk's API keys feature allows your application's users to create API keys that can delegate access to your application's API on their behalf. API keys are typically long-lived tokens associated with a user or organization that provide access to a set of API endpoints for third-party services.

For example, if you're building an application like ChatGPT, you might want to allow developers on your platform to create API keys that grant them access to pull their recent chats. In this case, the API key would be scoped to a specific user and only allow access to that user's chats. API keys can also be scoped to organizations or have granular scopes like "can read chats but can't write new chats".

This guide demonstrates how to create API keys, list them, use them to authenticate requests, and revoke them when needed.

Note

If you find that the use case being described does not fit what you are looking to accomplish with machine authentication, check out the machine authentication overview for more information on the different types of machine authentication that Clerk supports and what features are available for each type.

Prerequisites

Before you can use API keys in your application, you must enable them in the Clerk Dashboard:

  1. In the Clerk Dashboard, navigate to Configure > API keys.
  2. Enable API keys for users, organizations, or both, depending on your use case.

Note

If the API keys feature is disabled in the Dashboard, any existing keys will fail verification but will not be revoked. If you re-enable the feature, those keys will work again. This is different from revoking individual keys, which permanently invalidates them.

Enabling your users to create API keys via Clerk's UI components

Clerk provides UI components that you can drop into your application to support your users in generating and managing API keys. You can integrate these components into your application's interface, or create your own custom logic for API key management using the backend SDK methods described below.

If you are using Clerk's <UserProfile /> component, or <OrganizationProfile /> component, and you have enabled API keys in the Clerk Dashboard, you will automatically see an API Keys tab appear in the user or organization profile components. This tab will allow your users to create, list, and revoke API keys, without writing any additional custom code.

If you would like to prevent the API Keys tab from appearing in the user or organization profile components, you can pass a prop to the component to hide it as such:

<UserProfile apiKeysProps={{ hide: true }} />
<OrganizationProfile apiKeysProps={{ hide: true }} />
<UserButton userProfileProps={{ apiKeysProps: { hide: true } }} />

It's also possible to render the <APIKeys /> component directly if you'd like to embed the API key management UI directly into your application's user interface.

Tip

Hiding the UI doesn't prevent users from creating API keys — they can still call Clerk's Frontend API directly. If you want to ensure only backend-issued API keys are valid, use the scopes or claims parameters (available only via the Backend SDK) when creating keys. Your verification logic can then reject any keys missing the required scopes or claims, making user-created keys ineffective.

Using API keys in requests

Once you have an API key, you can use it to authenticate requests to your application's API. The API key should be sent as a Bearer token in the Authorization header:

await fetch('https://your-api.com/users', {
  method: 'GET',
  headers: {
    'Content-Type': 'application/json',
    Authorization: `Bearer ${apiKey}`,
  },
})

On your backend, you can verify the API key using Clerk's SDKs. See the verifying API keys guideNext.js Icon for framework-specific examples.

Using API keys via Clerk's SDKs

If you would like to create, list, and revoke API keys programmatically on the server side, you can use Clerk's backend SDKs. In this guide, we will use the JavaScript Backend SDKClerk Icon to demonstrate usage, but please note that the API keys feature is available in all of Clerk's backend SDKs.

Creating API keys

To create an API key, call the create()Clerk Icon method:

const apiKey = await clerkClient.apiKeys.create({
  name: 'My API Key',
  subject: 'user_xxx', // or 'org_xxx' for organization API keys
  description: 'API key for accessing my application', // optional
  scopes: ['read:users', 'write:users'], // optional
  secondsUntilExpiration: 86400, // optional: expires in 24 hours
})

The method returns an object containing the API key details, including the secret property with the actual API key value:

{
  "id": "ak_xxx",
  "name": "My API Key",
  "description": "API key for accessing my application",
  "subject": "user_xxx",
  "scopes": ["read:users", "write:users"],
  "claims": null,
  "revoked": false,
  "revocationReason": null,
  "expired": false,
  "expiration": 1754942036732,
  "createdAt": 1754938436732,
  "updatedAt": 1754938436732,
  "createdBy": "user_xxx",
  "secret": "ak_xxx"
}

Warning

The API key secret is only available in the initial response from create() and cannot be retrieved again. Make sure to store the secret securely immediately after creation. If you lose the secret, you will need to create a new API key.

Required parameters

  • name - A descriptive name for the API key (e.g., "Production API Key", "Development Key")
  • subject - The user ID (user_xxx) or organization ID (org_xxx) to associate the API key with

Optional parameters

  • description - A longer description of what the API key is used for
  • scopes - An array of scope strings that define what the API key can access
  • claims - A JavaScript object that can be used to store additional information about the API key
  • createdBy - The user ID of the user creating the API key (for audit purposes)
  • secondsUntilExpiration - The number of seconds until the API key will expire. By default, the API key will not expire. API keys are typically long-lived tokens that don't expire, as expiring API keys would cause third-party services using them to break unexpectedly. Instead, API keys can be instantly revoked if there's a security issue, which is possible because they use opaque tokens rather than JWTs.

Listing API keys

To list API keys, call the list()Clerk Icon method:

const apiKeys = await clerkClient.apiKeys.list({
  subject: 'user_xxx', // Filter by user or organization ID
  includeInvalid: false, // Whether to include revoked or expired keys
})

The method returns a paginated response with API key objects (without secrets):

{
  "data": [
    {
      "id": "ak_xxx",
      "name": "My API Key",
      "description": "API key for accessing my application",
      "subject": "user_xxx",
      "scopes": ["read:users"],
      "revoked": false,
      "expired": false,
      "expiration": 1754942036732,
      "createdAt": 1754938436732,
      "updatedAt": 1754938436732
    }
  ],
  "totalCount": 1
}

Verifying API keys

To verify an API key secret, you can use the verify()Clerk Icon method:

const apiKey = await clerkClient.apiKeys.verify(secret)

If the API key is valid, the method will return the API key object with its properties. If the API key is invalid, revoked, or expired, the method will throw an error.

The following example demonstrates how to handle verification errors:

import { isClerkAPIResponseError } from '@clerk/shared/error'

try {
  const apiKey = await clerkClient.apiKeys.verify(secret)
  // API key is valid, proceed with the request
} catch (error) {
  if (isClerkAPIResponseError(error)) {
    console.error(error.errors[0]?.message)
  }
  throw error
}

Note

In most cases, you'll want to verify API keys using framework-specific helpers like auth() in Next.js, which handles the verification automatically. See the verifying API keys guideNext.js Icon for more details.

Revoking API keys

To revoke an API key, call the revoke()Clerk Icon method:

await clerkClient.apiKeys.revoke({
  apiKeyId: apiKey.id,
  revocationReason: 'Key compromised', // optional, for your records
})

This will revoke the API key and prevent it from being used to authenticate any future requests. The API key will remain in your list but will be marked as revoked.

Important

When you revoke an API key, it is immediately invalidated. Any requests using that API key will be rejected. Make sure to notify users or update your systems before revoking API keys that are in active use.

Feedback

What did you think of this content?

Last updated on