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

# Authentication

> Secure your API requests with API keys

## API Key Authentication

All API requests must include your API key in the `X-API-Key` header.

```bash theme={null}
curl https://api.crbtrack.com/api/v1/orders/create \
  -H "X-API-Key: <YOUR_API_KEY>" \
  -H "Content-Type: application/json" \
  -d '{ ... }'
```

## Key Types

| Prefix     | Environment | Purpose                                 |
| ---------- | ----------- | --------------------------------------- |
| `pk_live_` | Production  | Live shipments with real carriers       |
| `pk_test_` | Sandbox     | Testing without creating real shipments |

<Warning>
  Never use production keys (`pk_live_`) for testing. Use sandbox keys (`pk_test_`) instead.
</Warning>

## Getting Your API Key

<Steps>
  <Step title="Login to Dashboard">
    Visit [dashboard.crbtrack.com](https://dashboard.crbtrack.com)
  </Step>

  <Step title="Go to API Keys">
    Navigate to **Settings** → **API Keys**
  </Step>

  <Step title="Generate Key">
    Click **Generate New Key** and configure:

    * **Name**: A descriptive name (e.g., "Production Website")
    * **Countries**: Which countries this key can ship to
    * **IP Whitelist**: Optional IP restrictions
  </Step>

  <Step title="Save Securely">
    The full key is shown **only once**. Save it immediately.
  </Step>
</Steps>

## Key Security Best Practices

<AccordionGroup>
  <Accordion icon="shield" title="Use Environment Variables">
    Never hardcode API keys in your source code.

    ```bash theme={null}
    # .env file (never commit this!)
    CROSSBORDERLY_API_KEY=pk_your_production_key
    ```

    ```javascript theme={null}
    // Access in code
    const apiKey = process.env.CROSSBORDERLY_API_KEY;
    ```
  </Accordion>

  <Accordion icon="lock" title="Restrict by IP">
    In the dashboard, add your server's IP addresses to the whitelist. Requests from other IPs will be rejected.
  </Accordion>

  <Accordion icon="rotate" title="Rotate Keys Regularly">
    Generate new keys periodically and revoke old ones. This limits exposure if a key is compromised.
  </Accordion>

  <Accordion icon="eye-slash" title="Never Expose Client-Side">
    API keys should only be used server-side. Never include them in:

    * Browser JavaScript
    * Mobile app bundles
    * Public repositories
  </Accordion>
</AccordionGroup>

## Country Access Control

Each API key is restricted to specific destination countries. This is configured when generating the key.

| Allowed Countries | What It Means                                           |
| ----------------- | ------------------------------------------------------- |
| `EC, MX, CO`      | Can create orders shipping to Ecuador, Mexico, Colombia |
| `*` (All)         | Can ship to any supported country                       |

If you try to create an order to a country not in your key's whitelist:

```json theme={null}
{
  "success": false,
  "error": {
    "code": "AUTH_COUNTRY_NOT_ALLOWED",
    "message": "Your API key is not authorized to ship to BR",
    "message_es": "Su clave API no está autorizada para enviar a BR"
  }
}
```

## Rate Limiting Headers

Every response includes rate limit information:

```
X-RateLimit-Limit: 50
X-RateLimit-Remaining: 47
X-RateLimit-Reset: 1703155200
```

| Header                  | Description                          |
| ----------------------- | ------------------------------------ |
| `X-RateLimit-Limit`     | Maximum requests per window          |
| `X-RateLimit-Remaining` | Requests remaining in current window |
| `X-RateLimit-Reset`     | Unix timestamp when the limit resets |

## Error Responses

### Invalid API Key

```json theme={null}
{
  "success": false,
  "error": {
    "code": "AUTH_INVALID_API_KEY",
    "message": "The provided API key is invalid or has been revoked",
    "message_es": "La clave API proporcionada es inválida o ha sido revocada"
  }
}
```

**HTTP Status**: `401 Unauthorized`

### Missing API Key

```json theme={null}
{
  "success": false,
  "error": {
    "code": "AUTH_MISSING_API_KEY",
    "message": "API key is required. Include it in the X-API-Key header",
    "message_es": "Se requiere clave API. Inclúyala en el encabezado X-API-Key"
  }
}
```

**HTTP Status**: `401 Unauthorized`

### Rate Limit Exceeded

```json theme={null}
{
  "success": false,
  "error": {
    "code": "RATE_LIMIT_EXCEEDED",
    "message": "Too many requests. Please wait before retrying.",
    "message_es": "Demasiadas solicitudes. Por favor espere antes de reintentar.",
    "retryAfter": 30
  }
}
```

**HTTP Status**: `429 Too Many Requests`

## Testing Authentication

Use this endpoint to verify your API key is working:

```bash theme={null}
curl https://api.crbtrack.com/api/v1/health \
  -H "X-API-Key: <YOUR_API_KEY>"
```

Successful response:

```json theme={null}
{
  "status": "ok",
  "authenticated": true,
  "keyName": "Production Website",
  "allowedCountries": ["EC", "MX", "CO"]
}
```
