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