Y-Router Setup Guide: Claude Code with OpenRouter
Tags: y-router openrouter proxy cloudflare setup
Y-Router is a lightweight proxy that enables Claude Code to work seamlessly with OpenRouter and other OpenAI-compatible APIs. This guide provides detailed setup instructions.
Table of Contents
- What is Y-Router
- Quick Start
- Detailed Setup
- Self-Hosting Guide
- Configuration Options
- Security Considerations
- Troubleshooting
What is Y-Router
Y-Router is a Cloudflare Worker that acts as a translation layer between:
- Input: Anthropic’s Claude API format (what Claude Code sends)
- Output: OpenAI-compatible API format (what OpenRouter expects)
Key Features
- Zero Configuration: Works out of the box with public instance
- API Translation: Seamless format conversion
- Model Mapping: Automatic model name translation
- Error Handling: Graceful fallbacks and retries
- Privacy Options: Self-host for complete control
Architecture
Claude Code → Y-Router → OpenRouter → LLM Provider
↑ ↓ ↓ ↓
└────────────────────────────────────┘
Quick Start
1. Get OpenRouter API Key
# Visit https://openrouter.ai
# Sign up and generate API key
# Save it securely2. Set Environment Variables
# Add to ~/.zshrc or ~/.bashrc
export ANTHROPIC_BASE_URL="https://cc.yovy.app"
export ANTHROPIC_API_KEY="sk-or-v1-your-openrouter-key"
export ANTHROPIC_MODEL="moonshotai/kimi-k2"3. Test Connection
# Reload shell configuration
source ~/.zshrc
# Test Claude Code
claude "Write a hello world in Python"Detailed Setup
Step 1: OpenRouter Account Setup
-
Create Account
- Visit OpenRouter
- Sign up with email or OAuth
- Verify email address
-
Generate API Key
- Navigate to Settings → API Keys
- Click “Create New Key”
- Name it (e.g., “Claude Code Integration”)
- Copy and save securely
-
Add Credits (Optional)
- Free tier includes limited requests
- Add credits for unlimited usage
- Set spending limits if desired
Step 2: Environment Configuration
macOS/Linux
# Edit shell configuration
nano ~/.zshrc # or ~/.bashrc
# Add these lines
# Y-Router Configuration
export ANTHROPIC_BASE_URL="https://cc.yovy.app"
export ANTHROPIC_API_KEY="sk-or-v1-your-key-here"
# Model Selection (optional)
export ANTHROPIC_MODEL="moonshotai/kimi-k2"
export ANTHROPIC_SMALL_FAST_MODEL="google/gemini-2.5-flash"
export ANTHROPIC_BACKGROUND_MODEL="meta-llama/llama-3.1-8b"
# Save and reload
source ~/.zshrcWindows
# Set permanent environment variables
[System.Environment]::SetEnvironmentVariable(
"ANTHROPIC_BASE_URL",
"https://cc.yovy.app",
[System.EnvironmentVariableTarget]::User
)
[System.Environment]::SetEnvironmentVariable(
"ANTHROPIC_API_KEY",
"sk-or-v1-your-key-here",
[System.EnvironmentVariableTarget]::User
)
# Restart terminal for changes to take effectStep 3: Model Configuration
Available Free Models
| Model | Provider | Best For |
|---|---|---|
moonshotai/kimi-k2 | Moonshot | General coding, high performance |
google/gemini-2.5-flash | Fast responses, simple tasks | |
meta-llama/llama-3.1-8b | Meta | Open source, customizable |
mistralai/mistral-7b | Mistral | Lightweight, efficient |
Model-Specific Configuration
# For specific use cases
alias claude-fast='ANTHROPIC_MODEL="google/gemini-2.5-flash" claude'
alias claude-free='ANTHROPIC_MODEL="moonshotai/kimi-k2" claude'
alias claude-local='ANTHROPIC_MODEL="local/ollama-model" claude'Self-Hosting Guide
Deploy your own y-router instance for enhanced privacy and control.
Prerequisites
- Cloudflare account (free tier works)
- Node.js installed locally
- Basic knowledge of Git
Deployment Steps
-
Clone Repository
git clone https://github.com/luohy15/y-router.git cd y-router -
Install Dependencies
npm install -
Configure Wrangler
# Install Cloudflare CLI npm install -g wrangler # Login to Cloudflare wrangler login -
Customize Configuration
// src/config.js export const config = { // Add custom headers defaultHeaders: { 'X-Custom-Header': 'your-value' }, // Model mappings modelMappings: { 'claude-sonnet': 'moonshotai/kimi-k2', 'claude-haiku': 'google/gemini-2.5-flash' }, // Rate limiting rateLimit: { requests: 100, window: 3600 // 1 hour } }; -
Deploy to Cloudflare
# Deploy to production wrangler publish # Get your worker URL # https://y-router.your-subdomain.workers.dev -
Update Claude Code Configuration
export ANTHROPIC_BASE_URL="https://y-router.your-subdomain.workers.dev"
Advanced Customizations
Add Authentication
// src/auth.js
export async function authenticate(request) {
const authHeader = request.headers.get('Authorization');
// Custom authentication logic
if (!authHeader || !isValidKey(authHeader)) {
return new Response('Unauthorized', { status: 401 });
}
return null; // Continue processing
}Add Logging
// src/logger.js
export async function logRequest(request, response) {
const log = {
timestamp: new Date().toISOString(),
method: request.method,
url: request.url,
status: response.status,
model: request.headers.get('X-Model')
};
// Send to logging service
await fetch('https://your-logger.com/api/logs', {
method: 'POST',
body: JSON.stringify(log)
});
}Configuration Options
Environment Variables
| Variable | Description | Example |
|---|---|---|
ANTHROPIC_BASE_URL | Y-Router endpoint | https://cc.yovy.app |
ANTHROPIC_API_KEY | OpenRouter API key | sk-or-v1-... |
ANTHROPIC_MODEL | Default model | moonshotai/kimi-k2 |
ANTHROPIC_TIMEOUT | Request timeout (ms) | 120000 |
ANTHROPIC_MAX_RETRIES | Retry attempts | 3 |
Headers Configuration
Custom headers for OpenRouter:
# Add site URL for better rate limits
export HTTP_REFERER="https://github.com/your-username"
# Add descriptive title
export X_TITLE="Claude Code Development"
# Custom user agent
export USER_AGENT="ClaudeCode/1.0 YRouter/1.0"Model Parameters
Fine-tune model behavior:
# Temperature (0-2, default 0.7)
export ANTHROPIC_TEMPERATURE="0.3"
# Max tokens (model dependent)
export ANTHROPIC_MAX_TOKENS="4096"
# Top-p sampling (0-1)
export ANTHROPIC_TOP_P="0.9"
# Presence penalty (-2 to 2)
export ANTHROPIC_PRESENCE_PENALTY="0.1"Security Considerations
API Key Security
-
Never Commit Keys
# .gitignore .env .env.local *.key -
Use Environment Files
# .env.example (commit this) ANTHROPIC_API_KEY=your-key-here # .env (don't commit) ANTHROPIC_API_KEY=sk-or-v1-actual-key -
Rotate Keys Regularly
- Set calendar reminders
- Use OpenRouter’s key expiration
- Monitor usage for anomalies
Network Security
-
Use HTTPS Only
- Y-Router enforces HTTPS
- Verify certificate validity
- Avoid public WiFi
-
IP Whitelisting (Self-hosted)
// Cloudflare Worker const allowedIPs = ['1.2.3.4', '5.6.7.8']; if (!allowedIPs.includes(request.headers.get('CF-Connecting-IP'))) { return new Response('Forbidden', { status: 403 }); }
Data Privacy
-
Self-Host for Sensitive Data
- Deploy your own y-router
- Control data flow
- Audit all requests
-
Disable Logging
export OPENROUTER_DISABLE_LOGS="true" export Y_ROUTER_NO_ANALYTICS="true"
Troubleshooting
Common Issues
1. Authentication Failed
# Error: 401 Unauthorized
# Fix: Verify API key
echo $ANTHROPIC_API_KEY
# Test directly with curl
curl -X POST https://openrouter.ai/api/v1/chat/completions \
-H "Authorization: Bearer $ANTHROPIC_API_KEY" \
-H "Content-Type: application/json" \
-d '{"model": "moonshotai/kimi-k2", "messages": [{"role": "user", "content": "test"}]}'2. Model Not Found
# Error: Model 'xyz' not found
# Fix: Check available models
curl https://openrouter.ai/api/v1/models \
-H "Authorization: Bearer $ANTHROPIC_API_KEY"
# Use correct format: provider/model
export ANTHROPIC_MODEL="moonshotai/kimi-k2" # ✓
# Not: kimi-k2 # ✗3. Rate Limit Exceeded
# Error: 429 Too Many Requests
# Fix: Add credits or wait
# Check usage at https://openrouter.ai/usage
# Use different model
export ANTHROPIC_MODEL="google/gemini-2.5-flash"4. Connection Timeout
# Error: Request timeout
# Fix: Increase timeout
export ANTHROPIC_TIMEOUT="180000" # 3 minutes
# Or use faster model
export ANTHROPIC_MODEL="google/gemini-2.5-flash"Debug Mode
Enable detailed logging:
# Enable all debug output
export DEBUG="*"
export CLAUDE_DEBUG="true"
export Y_ROUTER_DEBUG="true"
# Test with verbose output
claude --verbose "test message"Health Check
# Check y-router status
curl https://cc.yovy.app/health
# Check OpenRouter status
curl https://openrouter.ai/api/v1/models
# Full integration test
claude "Say 'Integration working' if you can read this"Advanced Usage
Load Balancing
Distribute requests across multiple models:
# Round-robin between models
export ANTHROPIC_MODELS="moonshotai/kimi-k2,google/gemini-2.5-flash,meta-llama/llama-3.1-8b"
export ANTHROPIC_LOAD_BALANCE="round-robin"Caching Responses
Enable response caching:
# Cache similar requests
export Y_ROUTER_CACHE="true"
export Y_ROUTER_CACHE_TTL="3600" # 1 hourWebhook Notifications
Get notified of events:
# Set webhook URL
export Y_ROUTER_WEBHOOK="https://your-server.com/webhook"
export Y_ROUTER_WEBHOOK_EVENTS="error,ratelimit,success"References
- Y-Router GitHub Repository
- OpenRouter API Documentation
- Cloudflare Workers Documentation
- Claude Code Configuration Guide