Security best practices for Cohere API keys, request validation, and data protection. Cohere uses bearer token auth with trial and production key tiers.
# NEVER hardcode keys — use environment variables
export CO_API_KEY="your-key-here"
# .env file (MUST be git-ignored)
CO_API_KEY=your-key-here
# .gitignore (mandatory entries)
.env
.env.local
.env.*.local
Key types:
import { CohereClientV2 } from 'cohere-ai';
function createSecureClient(): CohereClientV2 {
const apiKey = process.env.CO_API_KEY;
if (!apiKey) {
throw new Error('CO_API_KEY is required. Set it as an environment variable.');
}
// Basic key format check
if (apiKey.length < 20) {
throw new Error('CO_API_KEY appears malformed. Check dashboard.cohere.com.');
}
return new CohereClientV2({ token: apiKey });
}
# 1. Generate new key in Cohere dashboard
# → dashboard.cohere.com → API Keys → Create new key
# 2. Deploy new key (keep old key active)
# Vercel:
vercel env add CO_API_KEY production
# AWS:
aws secretsmanager update-secret --secret-id cohere/api-key --secret-string "new-key"
# GCP:
echo -n "new-key" | gcloud secrets versions add cohere-api-key --data-file=-
# 3. Verify new key works
curl -s -o /dev/null -w "%{http_code}" \
-H "Authorization: Bearer NEW_KEY" \
-H "Content-Type: application/json" \
https://api.cohere.com/v2/chat \
-d '{"model":"command-r7b-12-2024","messages":[{"role":"user","content":"test"}]}'
# Should return 200
# 4. Revoke old key in dashboard
# 5. Monitor for 401 errors after revocation
// Scrub PII before sending to Cohere API
const PII_PATTERNS: [string, RegExp][] = [
['email', /[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g],
['phone', /\b\d{3}[-.]?\d{3}[-.]?\d{4}\b/g],
['ssn', /\b\d{3}-\d{2}-\d{4}\b/g],
];
function scrubPII(text: string): string {
let scrubbed = text;
for (const [type, regex] of PII_PATTERNS) {
scrubbed = scrubbed.replace(regex, `[REDACTED_${type.toUpperCase()}]`);
}
return scrubbed;
}
// Use before API calls when handling user data
async function safeCohereChat(userInput: string) {
const sanitized = scrubPII(userInput);
return cohere.chat({
model: 'command-a-03-2025',
messages: [{ role: 'user', content: sanitized }],
safetyMode: 'CONTEXTUAL', // CONTEXTUAL (default), STRICT, or OFF
});
}
import { CohereError } from 'cohere-ai';
function safeLog(message: string, data?: Record<string, unknown>) {
const sanitized = { ...data };
// Never log API keys
delete sanitized.apiKey;
delete sanitized.token;
delete sanitized.authorization;
// Truncate request/response bodies
if (typeof sanitized.body === 'string' && (sanitized.body as string).length > 500) {
sanitized.body = (sanitized.body as string).slice(0, 500) + '...[truncated]';
}
console.log(`[cohere] ${message}`, sanitized);
}
// Wrap error logging
function logCohereError(err: unknown) {
if (err instanceof CohereError) {
safeLog('API error', {
status: err.statusCode,
message: err.message,
// Do NOT log err.body — may contain sensitive request data
});
}
}
Cohere's Chat API supports safety modes that control content filtering:
// CONTEXTUAL (default): Adapts based on context
await cohere.chat({
model: 'command-a-03-2025',
messages: [{ role: 'user', content: prompt }],
safetyMode: 'CONTEXTUAL',
});
// STRICT: Maximum safety filtering
await cohere.chat({
model: 'command-a-03-2025',
messages: [{ role: 'user', content: prompt }],
safetyMode: 'STRICT',
});
// Note: safetyMode not configurable with tools or documents params
CO_API_KEY stored in environment variables, never in code.env files listed in .gitignore
#!/bin/bash
# .git/hooks/pre-commit — detect Cohere keys in staged files
if git diff --cached --diff-filter=ACM | grep -qiE 'CO_API_KEY|cohere.*key.*=.*[a-zA-Z0-9]{20}'; then
echo "ERROR: Possible Cohere API key in commit. Remove before committing."
exit 1
fi
| Security Issue | Detection | Mitigation |
|---|---|---|
| Key in git history | git log -p | grep CO_API_KEY |
Rotate key immediately |
| Key in logs | Log audit | Add log scrubbing |
| Key in error report | Error handler review | Sanitize error payloads |
| Excessive token spend | Billing dashboard | Set budget alerts |
For production deployment, see cohere-prod-checklist.