# API Key Rotation

> Learn how to securely rotate your OpenRouter API keys using the key minting API. Includes best practices and BYOK advantages for simplified key management.

Regular API key rotation is a security best practice that limits the impact of compromised credentials. OpenRouter's [Provisioning API](/docs/guides/overview/auth/provisioning-api-keys) makes it easy to rotate keys programmatically without service interruption.

## Why Rotate API Keys?

Rotating API keys regularly helps protect your applications by limiting the window of exposure if a key is compromised, meeting compliance requirements for credential management, enabling clean audit trails of key usage, and allowing you to revoke access for former team members or deprecated systems.

## Rotation Strategy

A zero-downtime key rotation follows three steps: create a new key, update your applications to use the new key, and delete the old key once all systems have migrated.

<Note>
  Always verify your new key is working in production before deleting the old one. This prevents accidental service disruption.
</Note>

## Rotating Keys with the Provisioning API

First, you'll need a [Provisioning API key](https://openrouter.ai/settings/provisioning-keys) to manage your API keys programmatically.

### Step 1: Create a New Key

<CodeGroup>
  ```typescript title="TypeScript SDK"
  import { OpenRouter } from '@openrouter/sdk';

  const openRouter = new OpenRouter({
    apiKey: 'your-provisioning-key',
  });

  const newKey = await openRouter.apiKeys.create({
    name: 'Production Key - Rotated 2025-01',
    limit: 1000,
  });

  console.log('New key created:', newKey.data.key);
  console.log('Key hash:', newKey.data.hash);
  ```

  ```python title="Python"
  import requests

  PROVISIONING_API_KEY = "your-provisioning-key"
  BASE_URL = "https://openrouter.ai/api/v1/keys"

  response = requests.post(
      f"{BASE_URL}/",
      headers={
          "Authorization": f"Bearer {PROVISIONING_API_KEY}",
          "Content-Type": "application/json"
      },
      json={
          "name": "Production Key - Rotated 2025-01",
          "limit": 1000
      }
  )

  data = response.json()
  print(f"New key created: {data['data']['key']}")
  print(f"Key hash: {data['data']['hash']}")
  ```

  ```typescript title="TypeScript (fetch)"
  const PROVISIONING_API_KEY = 'your-provisioning-key';
  const BASE_URL = 'https://openrouter.ai/api/v1/keys';

  const response = await fetch(BASE_URL, {
    method: 'POST',
    headers: {
      Authorization: `Bearer ${PROVISIONING_API_KEY}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      name: 'Production Key - Rotated 2025-01',
      limit: 1000,
    }),
  });

  const { data } = await response.json();
  console.log('New key created:', data.key);
  console.log('Key hash:', data.hash);
  ```
</CodeGroup>

<Tip>
  Store the key hash returned in the response. You'll need it to delete the old key later.
</Tip>

### Step 2: Update Your Applications

Deploy your new API key to your applications. The specific process depends on your infrastructure, but common approaches include updating environment variables in your deployment configuration, rotating secrets in your secrets manager (AWS Secrets Manager, HashiCorp Vault, etc.), or updating your CI/CD pipeline variables.

Both keys remain valid during this transition period, so you can roll out changes gradually without service interruption.

### Step 3: Delete the Old Key

Once all your applications are using the new key, delete the old one:

<CodeGroup>
  ```typescript title="TypeScript SDK"
  import { OpenRouter } from '@openrouter/sdk';

  const openRouter = new OpenRouter({
    apiKey: 'your-provisioning-key',
  });

  const oldKeyHash = 'hash-of-old-key';
  await openRouter.apiKeys.delete(oldKeyHash);

  console.log('Old key deleted successfully');
  ```

  ```python title="Python"
  import requests

  PROVISIONING_API_KEY = "your-provisioning-key"
  BASE_URL = "https://openrouter.ai/api/v1/keys"

  old_key_hash = "hash-of-old-key"
  response = requests.delete(
      f"{BASE_URL}/{old_key_hash}",
      headers={
          "Authorization": f"Bearer {PROVISIONING_API_KEY}",
          "Content-Type": "application/json"
      }
  )

  print("Old key deleted successfully")
  ```

  ```typescript title="TypeScript (fetch)"
  const PROVISIONING_API_KEY = 'your-provisioning-key';
  const BASE_URL = 'https://openrouter.ai/api/v1/keys';

  const oldKeyHash = 'hash-of-old-key';
  await fetch(`${BASE_URL}/${oldKeyHash}`, {
    method: 'DELETE',
    headers: {
      Authorization: `Bearer ${PROVISIONING_API_KEY}`,
      'Content-Type': 'application/json',
    },
  });

  console.log('Old key deleted successfully');
  ```
</CodeGroup>

## BYOK Advantage: Simplified Key Rotation

If you use [Bring Your Own Key (BYOK)](/docs/guides/overview/auth/byok) with OpenRouter, you get a significant advantage when it comes to key rotation: **you can rotate your OpenRouter API keys without ever needing to rotate your provider keys**.

When you configure BYOK, your provider API keys (OpenAI, Anthropic, Google, etc.) are stored securely in OpenRouter and associated with your account, not with individual OpenRouter API keys. This means:

* **Rotate OpenRouter keys freely**: You can rotate your OpenRouter API keys as often as you like for security compliance without touching your provider credentials.
* **Provider keys stay stable**: Your provider API keys remain unchanged, avoiding the complexity of rotating credentials across multiple AI providers.
* **Single point of management**: Manage all your provider keys in one place through OpenRouter's [integrations settings](https://openrouter.ai/settings/integrations), while rotating your application-facing OpenRouter keys independently.

This separation of concerns makes BYOK particularly valuable for organizations with strict key rotation policies. You get the security benefits of regular key rotation for your application credentials while maintaining stable, long-lived connections to your AI providers.

<Tip>
  With BYOK, your provider keys are tied to your OpenRouter account, not to individual API keys. Rotate your OpenRouter keys as often as needed without any changes to your provider configuration.
</Tip>

## Best Practices

When implementing key rotation, keep these recommendations in mind:

* **Use descriptive key names**: Include rotation dates or version numbers in key names for easy tracking.
* **Monitor key usage**: Check the [Activity page](https://openrouter.ai/activity) to verify traffic has migrated to the new key before deleting the old one.
* **Set appropriate limits**: Apply spending limits to new keys to prevent unexpected costs.
* **Document your rotation schedule**: Establish and follow a regular rotation cadence (e.g., quarterly).
* **Test in staging first**: Validate your rotation process in a non-production environment.

## Related Resources

* [Provisioning API Keys](/docs/guides/overview/auth/provisioning-api-keys) - Full API reference for key management
* [BYOK](/docs/guides/overview/auth/byok) - Configure your own provider keys