> ## Documentation Index
> Fetch the complete documentation index at: https://docs.buntime.sh/llms.txt
> Use this file to discover all available pages before exploring further.

# Authentication

> Learn how to authenticate with the buntime.sh API

## Overview

All API requests to buntime.sh require authentication using an API key. Authentication is performed via the `Authorization` header using the Bearer token scheme.

## Getting Your API Key

<Steps>
  <Step title="Sign up for an account">
    Visit [buntime.sh/dashboard](https://buntime.sh/dashboard) and create a free account.
  </Step>

  <Step title="Generate an API key">
    In the dashboard, navigate to **API Keys** and click **Create New Key**.
  </Step>

  <Step title="Copy and store securely">
    Copy your API key immediately—you won't be able to see it again. Store it securely using environment variables or a secrets manager.
  </Step>
</Steps>

## Using Your API Key

### REST API

Include your API key in the `Authorization` header with every request:

```bash theme={null}
curl -X POST https://api.buntime.sh/sessions/create \
  -H "Authorization: Bearer your_api_key_here" \
  -H "Content-Type: application/json"
```

### TypeScript SDK

Pass your API key when initializing the client:

```typescript theme={null}
import { Buntime } from 'buntime.sh';

const client = new Buntime({
  apiKey: process.env.BUNTIME_API_KEY
});
```

<Warning>
  Never hardcode your API key in your source code. Always use environment variables or a secure secrets management solution.
</Warning>

## Managing API Keys

### Creating Multiple Keys

You can create multiple API keys for different environments or applications:

* **Development:** Use a separate key for local development
* **Staging:** Create a key for staging environments
* **Production:** Use a dedicated key for production
* **CI/CD:** Generate keys specifically for automated testing

### Rotating Keys

It's a best practice to rotate your API keys periodically:

1. Create a new API key in the dashboard
2. Update your applications to use the new key
3. Verify the new key works correctly
4. Revoke the old key

### Revoking Keys

If an API key is compromised or no longer needed:

1. Go to the dashboard
2. Find the key in your API Keys list
3. Click **Revoke** to immediately disable it

<Note>
  Revoking a key takes effect immediately. Any requests using the revoked key will fail with a 401 Unauthorized error.
</Note>

## Rate Limits

API keys are subject to rate limits based on your plan:

| Plan       | Rate Limit            | Concurrent Sessions |
| ---------- | --------------------- | ------------------- |
| Free       | 100 requests/minute   | 10 sessions         |
| Paid       | 1,000 requests/minute | 100 sessions        |
| Enterprise | Custom                | Custom              |

When you exceed the rate limit, the API returns a `429 Too Many Requests` response with headers indicating when you can retry:

```bash theme={null}
HTTP/1.1 429 Too Many Requests
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 0
X-RateLimit-Reset: 1640000000
Retry-After: 60
```

## Best Practices

<AccordionGroup>
  <Accordion icon="lock" title="Store keys securely">
    Use environment variables or secrets managers (AWS Secrets Manager, HashiCorp Vault, etc.) to store API keys. Never commit them to version control.

    ```bash theme={null}
    # .env file
    BUNTIME_API_KEY=your_api_key_here
    ```
  </Accordion>

  <Accordion icon="rotate" title="Rotate keys regularly">
    Rotate your API keys every 90 days or when team members leave. This minimizes the impact of potential key exposure.
  </Accordion>

  <Accordion icon="shield" title="Use separate keys per environment">
    Create different keys for development, staging, and production. This provides better isolation and easier debugging.
  </Accordion>

  <Accordion icon="eye" title="Monitor usage">
    Regularly review your API usage in the dashboard. Unusual patterns might indicate a compromised key.
  </Accordion>

  <Accordion icon="bell" title="Set up alerts">
    Configure alerts in the dashboard to notify you when usage approaches limits or shows suspicious activity.
  </Accordion>
</AccordionGroup>

## Troubleshooting

### 401 Unauthorized

If you receive a 401 error, check:

* ✅ The API key is correctly formatted
* ✅ The `Authorization` header is included
* ✅ The bearer scheme is used: `Bearer your_key`
* ✅ The key hasn't been revoked
* ✅ Your account is active

### 429 Too Many Requests

If you're hitting rate limits:

* Implement exponential backoff with retry logic
* Cache responses when possible
* Consider upgrading your plan for higher limits
* Batch operations to reduce request count

### Example: Handling Authentication Errors

```typescript theme={null}
import { Buntime } from 'buntime.sh';

const client = new Buntime({
  apiKey: process.env.BUNTIME_API_KEY
});

try {
  const session = await client.sessions.create();
} catch (error) {
  if (error.status === 401) {
    console.error('Authentication failed. Check your API key.');
  } else if (error.status === 429) {
    console.error('Rate limit exceeded. Retry after:', error.retryAfter);
  } else {
    console.error('Unexpected error:', error.message);
  }
}
```

## Security Considerations

<Warning>
  **Never expose your API key in:**

  * Frontend JavaScript code
  * Mobile applications
  * Public GitHub repositories
  * Log files or error messages
  * URL query parameters
</Warning>

### Server-Side Only

Always call the buntime.sh API from your backend servers, never from client-side code:

```typescript theme={null}
// ✅ Good: Server-side route
app.post('/api/execute', async (req, res) => {
  const client = new Buntime({
    apiKey: process.env.BUNTIME_API_KEY // Secure on server
  });
  
  const result = await client.execute({
    sessionId: req.body.sessionId,
    code: req.body.code
  });
  
  res.json(result);
});

// ❌ Bad: Client-side code
const client = new Buntime({
  apiKey: 'btk_...' // Exposed to all users!
});
```

## Next Steps

<CardGroup cols={2}>
  <Card title="Quickstart" icon="rocket" href="/quickstart">
    Start making your first API calls
  </Card>

  <Card title="API Reference" icon="code" href="/api-reference/introduction">
    Explore all available endpoints
  </Card>
</CardGroup>
