Authentication
API keys and environment configuration for xAI APIs
xAI API Key
Get your API key from the xAI Console.
Environment Variables
# .env
XAI_API_KEY=xai-your-key-hereTypeScript Configuration
import OpenAI from "openai"
const client = new OpenAI({
apiKey: process.env.XAI_API_KEY,
baseURL: "https://api.x.ai/v1",
})xAI's API is OpenAI-compatible. Use the official openai package with the xAI base URL.
X API Authentication
For X (Twitter) API access, you need:
- API Key & Secret - From the X Developer Portal
- Bearer Token - For app-only authentication
- OAuth 2.0 - For user-context authentication
Environment Variables
# .env
X_API_KEY=your-api-key
X_API_SECRET=your-api-secret
X_BEARER_TOKEN=your-bearer-token
# For OAuth 2.0 PKCE
X_CLIENT_ID=your-client-idBasic Setup
// App-only authentication (read-only public data)
const headers = {
Authorization: `Bearer ${process.env.X_BEARER_TOKEN}`,
}
// User-context authentication (for posting, DMs, etc.)
// See X API OAuth guide for OAuth 2.0 PKCE flowSecurity Best Practices
Never commit API keys to version control. Use .env files and ensure they're in .gitignore.
- Use environment variables - Never hardcode keys
- Rotate keys regularly - Especially if compromised
- Use minimal scopes - Request only needed permissions
- Monitor usage - Check the xAI console for anomalies