# Authentication

The Chainworks API uses token-based authentication over WebSocket connections.

## Authentication Flow

1. Obtain your API credentials (API URL and Auth Token)
2. Connect to the WebSocket server with your token
3. The server validates your token on connection
4. If valid, you can start making API requests

## Connecting with Credentials

### TypeScript

```typescript
import { io } from "socket.io-client";

const socket = io(CHAINWORKS_API_URL, {
  transports: ["websocket"],
  auth: {
    token: CHAINWORKS_API_AUTH_TOKEN,
  },
});
```

### Python

```python
import socketio

sio = socketio.Client()

sio.connect(
    CHAINWORKS_API_URL,
    transports=["websocket"],
    auth={"token": CHAINWORKS_API_AUTH_TOKEN}
)
```

## Environment Variables

We recommend storing your credentials in environment variables:

```bash
# .env
CHAINWORKS_API_URL=https://api.chainworks.co
CHAINWORKS_API_AUTH_TOKEN=your-secret-token
```

```typescript
const socket = io(process.env.CHAINWORKS_API_URL!, {
  transports: ["websocket"],
  auth: {
    token: process.env.CHAINWORKS_API_AUTH_TOKEN!,
  },
});
```

## Connection Events

Handle connection lifecycle events to ensure robust operation:

```typescript
socket.on("connect", () => {
  console.log("Connected successfully");
  // Start making API requests
});

socket.on("connect_error", (error) => {
  console.error("Connection error:", error.message);
  // Handle authentication failures
  if (error.message.includes("unauthorized")) {
    console.error("Invalid API token");
  }
});

socket.on("disconnect", (reason) => {
  console.log("Disconnected:", reason);
  // Handle reconnection if needed
});
```

## Reconnection

Socket.IO automatically handles reconnection. You can configure the behavior:

```typescript
const socket = io(CHAINWORKS_API_URL, {
  transports: ["websocket"],
  auth: {
    token: CHAINWORKS_API_AUTH_TOKEN,
  },
  reconnection: true,
  reconnectionAttempts: 5,
  reconnectionDelay: 1000,
  reconnectionDelayMax: 5000,
});
```

## Security Best Practices

1. **Never expose tokens in client-side code** - Use server-side proxies for browser applications
2. **Rotate tokens regularly** - Contact us to regenerate compromised tokens
3. **Use environment variables** - Never hardcode tokens in source code
4. **Monitor usage** - Track API calls to detect unauthorized access

## Rate Limits

API rate limits depend on your subscription tier. Contact us for details about rate limits and quotas.

## Getting Credentials

To obtain API credentials:

1. Contact us at [info@chainworks.co](mailto:info@chainworks.co)
2. Describe your use case
3. We'll provision credentials for your application

## Next Steps

- [Quick Start](/docs/quickstart) - Get started with your first request
- [EVM Endpoints](/docs/evm) - Explore Ethereum, Base, and BSC endpoints
- [SVM Endpoints](/docs/svm) - Explore Solana endpoints
