Environment Configuration Skill
Quick Setup
# Clone and install
git clone <repo-url>
cd omer-akben
npm install
# Copy environment template
cp .env.example .env
# Configure required environment variables (see below)
# Run development server
npm run dev
```typescript
## Required Environment Variables
### Core Services
```bash
# AI Models (Primary: XAI Grok)
XAI_API_KEY=your-xai-api-key
XAI_REASONING_MODEL=grok-4-fast-reasoning
XAI_NON_REASONING_MODEL=grok-4-fast-non-reasoning
# AI Models (Fallback: OpenAI)
OPENAI_API_KEY=your-openai-api-key
OPENAI_FALLBACK_MODEL=gpt-4o-mini
OPENAI_EMBEDDING_MODEL=text-embedding-3-small
```typescript
### Email Service (Resend)
```bash
RESEND_API_KEY=your-resend-api-key
RESEND_FROM_EMAIL=noreply@omerakben.com
```typescript
### Rate Limiting & Caching (Upstash Redis)
```bash
UPSTASH_REDIS_REST_URL=https://your-redis-url.upstash.io
UPSTASH_REDIS_REST_TOKEN=your-redis-token
```typescript
### Episodic Memory (Upstash Vector)
```bash
UPSTASH_VECTOR_REST_URL=https://your-vector-url.upstash.io
UPSTASH_VECTOR_REST_TOKEN=your-vector-token
```typescript
### Analytics (PostHog)
```bash
NEXT_PUBLIC_POSTHOG_KEY=your-posthog-key
NEXT_PUBLIC_POSTHOG_HOST=https://us.i.posthog.com
```typescript
### Error Tracking (Sentry)
```bash
SENTRY_AUTH_TOKEN=your-sentry-auth-token
NEXT_PUBLIC_SENTRY_DSN=your-sentry-dsn
```typescript
### Cron Security (Vercel)
```bash
CRON_SECRET=your-random-secret-key
```typescript
## Service Setup Guides
### XAI Grok Setup
1. Visit <https://console.x.ai/>
2. Create API key
3. Add to `.env` as `XAI_API_KEY`
4. Models: `grok-4-fast-reasoning`, `grok-4-fast-non-reasoning`
**Pricing:** $2/M input tokens, $10/M output tokens
### OpenAI Setup (Fallback)
1. Visit <https://platform.openai.com/>
2. Create API key
3. Add to `.env` as `OPENAI_API_KEY`
4. Models: `gpt-4o-mini`, `text-embedding-3-small`
**Pricing:** $0.15/M input tokens, $0.60/M output tokens
### Upstash Redis Setup
1. Visit <https://console.upstash.com/>
2. Create Redis database
3. Copy REST URL and token to `.env`
4. Used for: Rate limiting, caching
**Free Tier:** 10,000 commands/day
### Upstash Vector Setup
1. Visit <https://console.upstash.com/>
2. Create Vector index (1536 dimensions for OpenAI embeddings)
3. Copy REST URL and token to `.env`
4. Used for: Episodic memory search
**Free Tier:** 10,000 queries/month
### Resend Email Setup
1. Visit <https://resend.com/>
2. Add and verify sending domain
3. Create API key
4. Add to `.env` as `RESEND_API_KEY` and `RESEND_FROM_EMAIL`
**Free Tier:** 3,000 emails/month
### PostHog Analytics Setup
1. Visit <https://posthog.com/>
2. Create project
3. Copy project API key
4. Add to `.env` as `NEXT_PUBLIC_POSTHOG_KEY`
**Free Tier:** 1M events/month
### Sentry Error Tracking Setup
1. Visit <https://sentry.io/>
2. Create Next.js project
3. Copy DSN and auth token
4. Add to `.env`
5. Configure in `sentry.*.config.ts` files
**Free Tier:** 5,000 errors/month
## Environment Validation
### Check Required Variables
```typescript
// Runtime validation
const requiredEnvVars = [
'XAI_API_KEY',
'OPENAI_API_KEY',
'UPSTASH_REDIS_REST_URL',
'UPSTASH_REDIS_REST_TOKEN',
'RESEND_API_KEY',
];
requiredEnvVars.forEach((varName) => {
if (!process.env[varName]) {
throw new Error(`Missing required environment variable: ${varName}`);
}
});
```typescript
### Test Environment Setup
```bash
# Test AI models
curl https://api.x.ai/v1/chat/completions \
-H "Authorization: Bearer $XAI_API_KEY" \
-H "Content-Type: application/json" \
-d '{"model":"grok-4-fast-reasoning","messages":[{"role":"user","content":"test"}]}'
# Test Redis connection
curl $UPSTASH_REDIS_REST_URL/ping \
-H "Authorization: Bearer $UPSTASH_REDIS_REST_TOKEN"
# Test email sending
npm run test:email
```typescript
## Configuration Patterns
### AI Model Configuration
**Centralized Config:** `src/lib/ai/model-config.ts`
```typescript
export const AI_MODEL_CONFIG = {
primary: {
provider: "xai",
models: {
reasoning: process.env.XAI_REASONING_MODEL || "grok-4-fast-reasoning",
nonReasoning: process.env.XAI_NON_REASONING_MODEL || "grok-4-fast-non-reasoning",
},
},
fallback: {
provider: "openai",
model: process.env.OPENAI_FALLBACK_MODEL || "gpt-4o-mini",
},
embedding: {
provider: "openai",
model: process.env.OPENAI_EMBEDDING_MODEL || "text-embedding-3-small",
},
};
```typescript
### Usage
```typescript
import { PRIMARY_REASONING_MODEL } from "@/lib/ai/model-config";
const result = await generateWithFallback({
model: PRIMARY_REASONING_MODEL,
messages: [{ role: "user", content: prompt }],
});
```typescript
### Rate Limiting Configuration
**Location:** `src/lib/rate-limit.ts`
```typescript
export const rateLimits = {
collectContact: {
limit: 1, // 1 request
window: 86400, // per 24 hours
},
chat: {
limit: 100, // 100 requests
window: 3600, // per hour
},
};
```typescript
### Feature Flags
```typescript
export const features = {
episodicMemory: !!process.env.UPSTASH_VECTOR_REST_URL,
emailNotifications: !!process.env.RESEND_API_KEY,
analytics: !!process.env.NEXT_PUBLIC_POSTHOG_KEY,
errorTracking: !!process.env.NEXT_PUBLIC_SENTRY_DSN,
};
```typescript
## Security Best Practices
### API Key Management
1. **Never commit `.env` files** - Use `.env.example` as template
2. **Use environment-specific keys** - Different keys for dev/staging/prod
3. **Rotate keys regularly** - Especially after team member changes
4. **Use read-only keys** - When write access not needed
### Server-Side API Calls Only
```typescript
// ✅ GOOD: Server-side API route
export async function POST(request: Request) {
const apiKey = process.env.XAI_API_KEY; // Secure
// Make API call
}
// ❌ BAD: Client-side API call
const response = await fetch("/api/external", {
headers: { "X-API-Key": process.env.XAI_API_KEY }, // Exposed!
});
```typescript
### Input Validation
```typescript
import { z } from "zod";
const inputSchema = z.object({
email: z.string().email(),
message: z.string().max(1000),
});
// Validate all inputs
const validated = inputSchema.parse(input);
```typescript
### Rate Limiting
```typescript
import { ratelimit } from "@/lib/rate-limit";
const result = await ratelimit.limit(ip);
if (!result.success) {
return new Response("Rate limit exceeded", { status: 429 });
}
```typescript
## Vercel Deployment Configuration
### Environment Variables in Vercel
1. Go to Project Settings → Environment Variables
2. Add all variables from `.env.example`
3. Set appropriate scope (Production, Preview, Development)
4. Use Vercel CLI for bulk import: `vercel env pull`
### Vercel Cron Configuration
**File:** `vercel.json`
```json
{
"crons": [
{
"path": "/api/cron/cleanup-memory",
"schedule": "0 3 * * 0"
}
]
}
```typescript
**Security:** Endpoint validates `CRON_SECRET` header
## Troubleshooting
### Common Issues
**Issue:** "Missing environment variable: XAI_API_KEY"
**Fix:** Ensure `.env` file exists and contains `XAI_API_KEY`
**Issue:** "Redis connection failed"
**Fix:** Check `UPSTASH_REDIS_REST_URL` and `UPSTASH_REDIS_REST_TOKEN` are correct
**Issue:** "Rate limit exceeded"
**Fix:** Redis not configured - add Upstash Redis credentials
**Issue:** "Email sending failed"
**Fix:** Verify `RESEND_API_KEY` and sending domain is verified
### Debug Mode
```bash
# Enable verbose logging
NODE_ENV=development npm run dev
# Check environment variables
node -e "console.log(process.env.XAI_API_KEY ? 'XAI_API_KEY set' : 'XAI_API_KEY missing')"
```typescript
## Local Development Setup
```bash
# Install dependencies
npm install
# Set up environment
cp .env.example .env
# Edit .env with your API keys
# Run development server
npm run dev
# In another terminal, run tests
npm test -- --watch
```typescript
## Production Checklist
Before deploying to production:
- [ ] All required environment variables set in Vercel
- [ ] API keys are production keys (not development keys)
- [ ] Rate limiting configured (Redis credentials set)
- [ ] Email sending configured (Resend verified domain)
- [ ] Analytics configured (PostHog project key)
- [ ] Error tracking configured (Sentry DSN)
- [ ] Cron secret set for automated tasks
- [ ] Environment variables match `.env.example` template
1---
2name: environment-configuration
3description: Environment variables, setup procedures, API configurations, and security for the omer-akben portfolio. Use when setting up the project, configuring services, or troubleshooting environment issues.
4metadata:
5 source: https://skillmd.com/skills/aibot88/environment-configuration
6---
7
8# Environment Configuration Skill
9
10## Quick Setup
11
12```bash
13# Clone and install
14git clone <repo-url>
15cd omer-akben
16npm install
17
18# Copy environment template
19cp .env.example .env
20
21# Configure required environment variables (see below)
22
23# Run development server
24npm run dev
25```typescript
26
27## Required Environment Variables
28
29### Core Services
30
31```bash
32# AI Models (Primary: XAI Grok)
33XAI_API_KEY=your-xai-api-key
34XAI_REASONING_MODEL=grok-4-fast-reasoning
35XAI_NON_REASONING_MODEL=grok-4-fast-non-reasoning
36
37# AI Models (Fallback: OpenAI)
38OPENAI_API_KEY=your-openai-api-key
39OPENAI_FALLBACK_MODEL=gpt-4o-mini
40OPENAI_EMBEDDING_MODEL=text-embedding-3-small
41```typescript
42
43### Email Service (Resend)
44
45```bash
46RESEND_API_KEY=your-resend-api-key
47RESEND_FROM_EMAIL=noreply@omerakben.com
48```typescript
49
50### Rate Limiting & Caching (Upstash Redis)
51
52```bash
53UPSTASH_REDIS_REST_URL=https://your-redis-url.upstash.io
54UPSTASH_REDIS_REST_TOKEN=your-redis-token
55```typescript
56
57### Episodic Memory (Upstash Vector)
58
59```bash
60UPSTASH_VECTOR_REST_URL=https://your-vector-url.upstash.io
61UPSTASH_VECTOR_REST_TOKEN=your-vector-token
62```typescript
63
64### Analytics (PostHog)
65
66```bash
67NEXT_PUBLIC_POSTHOG_KEY=your-posthog-key
68NEXT_PUBLIC_POSTHOG_HOST=https://us.i.posthog.com
69```typescript
70
71### Error Tracking (Sentry)
72
73```bash
74SENTRY_AUTH_TOKEN=your-sentry-auth-token
75NEXT_PUBLIC_SENTRY_DSN=your-sentry-dsn
76```typescript
77
78### Cron Security (Vercel)
79
80```bash
81CRON_SECRET=your-random-secret-key
82```typescript
83
84## Service Setup Guides
85
86### XAI Grok Setup
87
881. Visit <https://console.x.ai/>
892. Create API key
903. Add to `.env` as `XAI_API_KEY`
914. Models: `grok-4-fast-reasoning`, `grok-4-fast-non-reasoning`
92
93**Pricing:** $2/M input tokens, $10/M output tokens
94
95### OpenAI Setup (Fallback)
96
971. Visit <https://platform.openai.com/>
982. Create API key
993. Add to `.env` as `OPENAI_API_KEY`
1004. Models: `gpt-4o-mini`, `text-embedding-3-small`
101
102**Pricing:** $0.15/M input tokens, $0.60/M output tokens
103
104### Upstash Redis Setup
105
1061. Visit <https://console.upstash.com/>
1072. Create Redis database
1083. Copy REST URL and token to `.env`
1094. Used for: Rate limiting, caching
110
111**Free Tier:** 10,000 commands/day
112
113### Upstash Vector Setup
114
1151. Visit <https://console.upstash.com/>
1162. Create Vector index (1536 dimensions for OpenAI embeddings)
1173. Copy REST URL and token to `.env`
1184. Used for: Episodic memory search
119
120**Free Tier:** 10,000 queries/month
121
122### Resend Email Setup
123
1241. Visit <https://resend.com/>
1252. Add and verify sending domain
1263. Create API key
1274. Add to `.env` as `RESEND_API_KEY` and `RESEND_FROM_EMAIL`
128
129**Free Tier:** 3,000 emails/month
130
131### PostHog Analytics Setup
132
1331. Visit <https://posthog.com/>
1342. Create project
1353. Copy project API key
1364. Add to `.env` as `NEXT_PUBLIC_POSTHOG_KEY`
137
138**Free Tier:** 1M events/month
139
140### Sentry Error Tracking Setup
141
1421. Visit <https://sentry.io/>
1432. Create Next.js project
1443. Copy DSN and auth token
1454. Add to `.env`
1465. Configure in `sentry.*.config.ts` files
147
148**Free Tier:** 5,000 errors/month
149
150## Environment Validation
151
152### Check Required Variables
153
154```typescript
155// Runtime validation
156const requiredEnvVars = [
157 'XAI_API_KEY',
158 'OPENAI_API_KEY',
159 'UPSTASH_REDIS_REST_URL',
160 'UPSTASH_REDIS_REST_TOKEN',
161 'RESEND_API_KEY',
162];
163
164requiredEnvVars.forEach((varName) => {
165 if (!process.env[varName]) {
166 throw new Error(`Missing required environment variable: ${varName}`);
167 }
168});
169```typescript
170
171### Test Environment Setup
172
173```bash
174# Test AI models
175curl https://api.x.ai/v1/chat/completions \
176 -H "Authorization: Bearer $XAI_API_KEY" \
177 -H "Content-Type: application/json" \
178 -d '{"model":"grok-4-fast-reasoning","messages":[{"role":"user","content":"test"}]}'
179
180# Test Redis connection
181curl $UPSTASH_REDIS_REST_URL/ping \
182 -H "Authorization: Bearer $UPSTASH_REDIS_REST_TOKEN"
183
184# Test email sending
185npm run test:email
186```typescript
187
188## Configuration Patterns
189
190### AI Model Configuration
191
192**Centralized Config:** `src/lib/ai/model-config.ts`
193
194```typescript
195export const AI_MODEL_CONFIG = {
196 primary: {
197 provider: "xai",
198 models: {
199 reasoning: process.env.XAI_REASONING_MODEL || "grok-4-fast-reasoning",
200 nonReasoning: process.env.XAI_NON_REASONING_MODEL || "grok-4-fast-non-reasoning",
201 },
202 },
203 fallback: {
204 provider: "openai",
205 model: process.env.OPENAI_FALLBACK_MODEL || "gpt-4o-mini",
206 },
207 embedding: {
208 provider: "openai",
209 model: process.env.OPENAI_EMBEDDING_MODEL || "text-embedding-3-small",
210 },
211};
212```typescript
213
214### Usage
215
216```typescript
217import { PRIMARY_REASONING_MODEL } from "@/lib/ai/model-config";
218
219const result = await generateWithFallback({
220 model: PRIMARY_REASONING_MODEL,
221 messages: [{ role: "user", content: prompt }],
222});
223```typescript
224
225### Rate Limiting Configuration
226
227**Location:** `src/lib/rate-limit.ts`
228
229```typescript
230export const rateLimits = {
231 collectContact: {
232 limit: 1, // 1 request
233 window: 86400, // per 24 hours
234 },
235 chat: {
236 limit: 100, // 100 requests
237 window: 3600, // per hour
238 },
239};
240```typescript
241
242### Feature Flags
243
244```typescript
245export const features = {
246 episodicMemory: !!process.env.UPSTASH_VECTOR_REST_URL,
247 emailNotifications: !!process.env.RESEND_API_KEY,
248 analytics: !!process.env.NEXT_PUBLIC_POSTHOG_KEY,
249 errorTracking: !!process.env.NEXT_PUBLIC_SENTRY_DSN,
250};
251```typescript
252
253## Security Best Practices
254
255### API Key Management
256
2571. **Never commit `.env` files** - Use `.env.example` as template
2582. **Use environment-specific keys** - Different keys for dev/staging/prod
2593. **Rotate keys regularly** - Especially after team member changes
2604. **Use read-only keys** - When write access not needed
261
262### Server-Side API Calls Only
263
264```typescript
265// ✅ GOOD: Server-side API route
266export async function POST(request: Request) {
267 const apiKey = process.env.XAI_API_KEY; // Secure
268 // Make API call
269}
270
271// ❌ BAD: Client-side API call
272const response = await fetch("/api/external", {
273 headers: { "X-API-Key": process.env.XAI_API_KEY }, // Exposed!
274});
275```typescript
276
277### Input Validation
278
279```typescript
280import { z } from "zod";
281
282const inputSchema = z.object({
283 email: z.string().email(),
284 message: z.string().max(1000),
285});
286
287// Validate all inputs
288const validated = inputSchema.parse(input);
289```typescript
290
291### Rate Limiting
292
293```typescript
294import { ratelimit } from "@/lib/rate-limit";
295
296const result = await ratelimit.limit(ip);
297if (!result.success) {
298 return new Response("Rate limit exceeded", { status: 429 });
299}
300```typescript
301
302## Vercel Deployment Configuration
303
304### Environment Variables in Vercel
305
3061. Go to Project Settings → Environment Variables
3072. Add all variables from `.env.example`
3083. Set appropriate scope (Production, Preview, Development)
3094. Use Vercel CLI for bulk import: `vercel env pull`
310
311### Vercel Cron Configuration
312
313**File:** `vercel.json`
314
315```json
316{
317 "crons": [
318 {
319 "path": "/api/cron/cleanup-memory",
320 "schedule": "0 3 * * 0"
321 }
322 ]
323}
324```typescript
325
326**Security:** Endpoint validates `CRON_SECRET` header
327
328## Troubleshooting
329
330### Common Issues
331
332**Issue:** "Missing environment variable: XAI_API_KEY"
333**Fix:** Ensure `.env` file exists and contains `XAI_API_KEY`
334
335**Issue:** "Redis connection failed"
336**Fix:** Check `UPSTASH_REDIS_REST_URL` and `UPSTASH_REDIS_REST_TOKEN` are correct
337
338**Issue:** "Rate limit exceeded"
339**Fix:** Redis not configured - add Upstash Redis credentials
340
341**Issue:** "Email sending failed"
342**Fix:** Verify `RESEND_API_KEY` and sending domain is verified
343
344### Debug Mode
345
346```bash
347# Enable verbose logging
348NODE_ENV=development npm run dev
349
350# Check environment variables
351node -e "console.log(process.env.XAI_API_KEY ? 'XAI_API_KEY set' : 'XAI_API_KEY missing')"
352```typescript
353
354## Local Development Setup
355
356```bash
357# Install dependencies
358npm install
359
360# Set up environment
361cp .env.example .env
362# Edit .env with your API keys
363
364# Run development server
365npm run dev
366
367# In another terminal, run tests
368npm test -- --watch
369```typescript
370
371## Production Checklist
372
373Before deploying to production:
374
375- [ ] All required environment variables set in Vercel
376- [ ] API keys are production keys (not development keys)
377- [ ] Rate limiting configured (Redis credentials set)
378- [ ] Email sending configured (Resend verified domain)
379- [ ] Analytics configured (PostHog project key)
380- [ ] Error tracking configured (Sentry DSN)
381- [ ] Cron secret set for automated tasks
382- [ ] Environment variables match `.env.example` template