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

# Authentication & API Keys

> Learn how to authenticate with Context.dev and manage your API keys securely

## API Key Authentication

Context.dev uses API key authentication to secure all API requests. Every request to the Context.dev API must include a valid API key in the request headers.

## Getting Your API Key

<Steps>
  <Step title="Sign Up">
    Create an account at [context.dev](https://context.dev/signup) if you haven't
    already.
  </Step>

  <Step title="Access Dashboard">
    Log in to your [Context.dev dashboard](https://context.dev/dashboard).
  </Step>

  <Step title="Copy API Key">
    Navigate to the API Keys section and copy your API key. Store it securely -
    it won't be shown again.
  </Step>
</Steps>

<Warning>
  **Keep your API key secret!** Never commit API keys to version control or
  expose them in client-side code. Treat them like passwords.
</Warning>

## Using Your API Key

### HTTP Header Authentication

Include your API key in the `Authorization` header with the `Bearer` prefix:

```bash theme={null}
curl https://api.context.dev/v1/brand/retrieve \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"domain": "stripe.com"}'
```

### SDK Authentication

All official SDKs handle authentication automatically when you provide your API key:

<AccordionGroup>
  <Accordion icon="js" title="JavaScript/TypeScript">
    ```typescript theme={null}
    import ContextDev from "context.dev";

    const client = new ContextDev({
      apiKey: process.env.CONTEXT_DEV_API_KEY, // Recommended: use environment variables
    });

    // API key is automatically included in all requests
    const { brand } = await client.brand.retrieve({ domain: "stripe.com" });
    ```
  </Accordion>

  <Accordion icon="python" title="Python">
    ```python theme={null}
    import context_dev
    import os

    client = context_dev.ContextDev(
        api_key=os.environ.get("CONTEXT_DEV_API_KEY"),  # Recommended: use environment variables
    )

    # API key is automatically included in all requests
    brand = client.brand.retrieve(domain="stripe.com")
    ```
  </Accordion>

  <Accordion icon="gem" title="Ruby">
    ```ruby theme={null}
    require 'context_dev'

    client = ContextDev::Client.new(
      api_key: ENV['CONTEXT_DEV_API_KEY']  # Recommended: use environment variables
    )

    # API key is automatically included in all requests
    brand = client.brand.retrieve(domain: 'stripe.com')
    ```
  </Accordion>
</AccordionGroup>

## Storing API Keys Securely

### Environment Variables (Recommended)

Store your API key in environment variables, never hardcode it in your source code:

**`.env` file (for development):**

```bash theme={null}
CONTEXT_DEV_API_KEY=your_api_key_here
```

**Load in your application:**

<CodeGroup>
  ```typescript TypeScript (Node.js) theme={null}
  // Using dotenv package
  import "dotenv/config";

  const client = new ContextDev({
    apiKey: process.env.CONTEXT_DEV_API_KEY,
  });
  ```

  ```python Python theme={null}
  import os
  from dotenv import load_dotenv

  load_dotenv()

  client = context_dev.ContextDev(
      api_key=os.environ.get("CONTEXT_DEV_API_KEY"),
  )
  ```

  ```ruby Ruby theme={null}
  require 'dotenv/load'

  client = ContextDev::Client.new(
    api_key: ENV['CONTEXT_DEV_API_KEY']
  )
  ```
</CodeGroup>

### Production Deployment

For production environments, set environment variables using your platform's configuration:

**Vercel:**

```bash theme={null}
vercel env add CONTEXT_DEV_API_KEY
```

**Heroku:**

```bash theme={null}
heroku config:set CONTEXT_DEV_API_KEY=your_api_key_here
```

**Docker:**

```bash theme={null}
docker run -e CONTEXT_DEV_API_KEY=your_api_key_here your-app
```

**AWS Lambda:**
Configure environment variables in the Lambda function configuration or use AWS Secrets Manager.

<Warning>
  **Never commit `.env` files to version control.** Add `.env` to your
  `.gitignore` file: `.env .env.local`
</Warning>

## Rate Limiting

Rate limits are applied per API key and vary by plan tier. Below are the current limits. See the [pricing page](https://www.context.dev/pricing) for the latest details on credits and overage rates.

| Plan       | Credits per Month          | Requests per Second | Overage             |
| ---------- | -------------------------- | ------------------- | ------------------- |
| Trial      | 500 one-time trial credits | —                   | —                   |
| Starter    | 30,000 / month             | 2 calls/sec         | \$19 per 1K credits |
| Pro        | 200,000 / month            | 5 calls/sec         | \$9 per 1K credits  |
| Scale      | 2,500,000 / month          | 20 calls/sec        | \$6 per 1K credits  |
| Enterprise | Custom                     | Custom              | Contact sales       |

<Note>
  Context.dev uses a credit-based pricing system. Different API endpoints consume different amounts of credits. For example, web scraping endpoints cost 1 credit each (1/10th the cost of a standard brand API call). See the [pricing page](https://www.context.dev/pricing) for full details.
</Note>

When you exceed your rate limit, you'll receive a `429 Too Many Requests` response with a `Retry-After` header.

### Handling Rate Limits

Implement exponential backoff when you receive rate limit errors:

```typescript theme={null}
async function fetchBrandWithRetry(domain: string, maxRetries = 3) {
  for (let i = 0; i < maxRetries; i++) {
    try {
      const { brand } = await client.brand.retrieve({ domain });
      return brand;
    } catch (error) {
      if (error.status === 429 && i < maxRetries - 1) {
        // Exponential backoff: wait 2^i seconds
        const delay = Math.pow(2, i) * 1000;
        await new Promise((resolve) => setTimeout(resolve, delay));
        continue;
      }
      throw error;
    }
  }
}
```

> If you consistently hit your limits, consider upgrading your plan on the [pricing page](https://www.context.dev/pricing) or contact support for a custom plan.

<Note>
  **Prefetch endpoint is rate-limit free!** The [Prefetch by
  Email](/api-reference/utility/prefetch-brand-data-by-email) endpoint doesn't
  count against your rate limits or credit usage.
</Note>

## Security Best Practices

### 1. Never Expose Keys in Client-Side Code

**Bad:** Hardcoding API keys in frontend JavaScript

```typescript theme={null}
// DON'T DO THIS!
const client = new ContextDev({
  apiKey: "brand_abc123...", // Exposed in browser
});
```

**Good:** Use a backend proxy

```typescript theme={null}
// Frontend: Call your own API
const response = await fetch("/api/brand", {
  method: "POST",
  body: JSON.stringify({ domain: "stripe.com" }),
});

// Backend API route: Use API key server-side
export async function POST(request) {
  const { domain } = await request.json();
  const client = new ContextDev({
    apiKey: process.env.CONTEXT_DEV_API_KEY, // Secure
  });
  const { brand } = await client.brand.retrieve({ domain });
  return Response.json(brand);
}
```

### 2. Use HTTPS Only

Always make API requests over HTTPS to encrypt your API key in transit. The Context.dev API only accepts HTTPS requests.

### 3. Don't Log API Keys

Avoid logging API keys in application logs or error tracking services:

```typescript theme={null}
// Bad: Logs might contain the API key
console.log("Client config:", client);

// Good: Log only necessary information
console.log("API request for domain:", domain);
```

## Testing & Development

### Local Development

For local development, use a `.env.local` file that's not committed to version control:

```bash theme={null}
# .env.local (gitignored)
CONTEXT_DEV_API_KEY=your_dev_api_key_here
```

### CI/CD Pipelines

Store API keys as secrets in your CI/CD platform:

* **GitHub Actions:** Repository Secrets
* **GitLab CI:** CI/CD Variables
* **CircleCI:** Project Environment Variables

## Authentication Errors

### 401 Unauthorized

You'll receive a `401` error if:

* Your API key is missing from the request
* Your API key is invalid or expired
* Your API key has been deleted

**Solution:** Verify your API key is correct and hasn't been deleted.

```json theme={null}
{
  "status": "error",
  "message": "Invalid API key",
  "code": 401
}
```

### 403 Forbidden

You'll receive a `403` error if:

* Your API key doesn't have permission for the requested endpoint
* Your account has been suspended

**Solution:** Check your account status in the dashboard or contact support.

## Related Resources

<CardGroup cols={2}>
  <Card title="Quickstart" icon="bolt" href="/guides/get-started/quickstart">
    Get started with your first API call
  </Card>

  <Card title="Core Concepts" icon="book" href="/guides/get-started/core-concepts">
    Understand Context.dev fundamentals
  </Card>

  <Card title="Troubleshooting" icon="triangle-exclamation" href="/guides/get-started/troubleshooting">
    Common authentication issues
  </Card>

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

***

<Tip>
  Need help with authentication? [Contact our team](mailto:hello@context.dev) for
  personalized support.
</Tip>
