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.
Prerequisites
Before you can use API keys in your application, you must enable them in the Clerk Dashboard:
- In the Clerk Dashboard, navigate to Configure > API keys.
- Enable API keys for users, organizations, or both, depending on your use case.
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.
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 guide 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 SDK
Creating API keys
To create an API key, call the create()
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"
}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 forscopes- An array of scope strings that define what the API key can accessclaims- A JavaScript object that can be used to store additional information about the API keycreatedBy- 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()
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()
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
}Revoking API keys
To revoke an API key, call the revoke()
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.
Feedback
Last updated on