Common Issues & Solutions
DeprecatedHiddenIntroduced in legacy
Owner
@engineering
Last verified
2024-05-01
Sources of truth
- doc: docs/getting-started/installation.md
> ⚠️ This troubleshooting guide references the legacy Prisma-based stack and will be replaced. Prefer the tips embedded in docs/getting-started/installation.md
until the updated diagnostics guide ships.
Installation Issues
Cannot Install Dependencies
Error:ERR_PNPM_PEER_DEP_ISSUES Unmet peer dependencies
Solution:
# Force install with legacy peer deps
pnpm install --legacy-peer-deps
# Or clean install
rm -rf node_modules pnpm-lock.yaml
pnpm install
Node Version Mismatch
Error:Error: The engine "node" is incompatible with this module
Solution:
# Check current version
node --version
# Install correct version with nvm
nvm install 20
nvm use 20
# Or update package.json engines
Database Issues
Cannot Connect to Database
Error:Error: P1001: Can't reach database server at localhost:5432
Solutions:
Check PostgreSQL is running:
# macOS
brew services list | grep postgresql
# Linux
systemctl status postgresql
# Docker
docker ps | grep postgres
# Test connection
psql $DATABASE_URL -c "SELECT 1"
# Check format
# Should be: postgresql://user:pass@host:port/db
# Allow PostgreSQL port
sudo ufw allow 5432
Migration Failures
Error:Error: P3005: The database schema for `postgres` is not empty
Solution:
# Reset database (CAUTION: Deletes all data)
pnpm prisma migrate reset
# Or manually
pnpm prisma db push --force-reset
Prisma Client Issues
Error:Error: @prisma/client did not initialize yet
Solution:
# Generate Prisma Client
pnpm prisma generate
# Ensure postinstall script runs
pnpm install
OpenRouter API Issues
Invalid API Key
Error:Error: Invalid API key provided
Solutions:
Verify API key:
# Check environment variable
echo $OPENROUTER_API_KEY
# Should start with sk-or-v1-
# Ensure no quotes or spaces
OPENROUTER_API_KEY=sk-or-v1-xxxxx
Rate Limiting
Error:Error: Rate limit exceeded. Please try again later.
Solutions:
Add credits to account
Implement retry logic:
async function retryWithBackoff(fn, retries = 3) {
for (let i = 0; i < retries; i++) {
try {
return await fn()
} catch (error) {
if (i === retries - 1) throw error
await new Promise(r => setTimeout(r, 2 ** i * 1000))
}
}
}
// Fallback to cheaper model
const model = rateLimited ? 'openai/gpt-3.5-turbo' : 'anthropic/claude-3.5-sonnet'
Chat Interface Issues
Messages Not Streaming
Problem: Chat responses appear all at once instead of streaming Solutions:// Ensure using streaming endpoint
fetch('/api/chat', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ message })
})
// API route should return:
return new Response(stream, {
headers: {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive',
}
})
Chat History Not Persisting
Problem: Messages disappear on refresh Solutions:// Ensure user is logged in
const session = await auth()
if (!session) {
// Guest mode - use localStorage
}
-- Check messages are saved
SELECT * FROM "Message" WHERE "chatId" = 'xxx';
// Force refetch
queryClient.invalidateQueries(['chat', chatId])
DSL Extraction Issues
DSL Not Updating
Problem: DSL panel doesn't reflect conversation Solutions:// Browser console
console.log(eventSource.readyState)
// Should be 1 (OPEN)
// Check API response includes DSL
const response = await fetch('/api/chat')
const data = await response.json()
console.log(data.dsl) // Should have DSL data
// Ensure DSL events are stored
const events = await db.query.dslEvent.findMany({
where: eq(dslEvent.chatId, chatId)
})
Low Confidence Scores
Problem: AI shows low confidence in extraction Solutions:❌ "I need a system"
✅ "I need a task management system with projects, tasks, and users"
❌ "Users and tasks are related"
✅ "Each user can have many tasks, tasks belong to one user"
❌ "Tasks have some fields"
✅ "Tasks have title (required), description, status (todo/done), and due date"
Code Generation Issues
Generation Button Not Appearing
Problem: Can't see generate button at 75%+ readiness Solutions:console.log('DSL Readiness:', dsl.readiness)
// Should be >= 75
// Should be 'confirming' or 'building'
console.log('Current phase:', dsl.phase)
// components/code-generation-panel.tsx
const canGenerate = readiness >= 75 && entityCount > 0
Generated Code Has Errors
Problem: Generated code doesn't compile Solutions:# Ensure all required packages installed
pnpm install
// tsconfig.json
{
"compilerOptions": {
"strict": true,
"skipLibCheck": true
}
}
// Use @ alias consistently
import { prisma } from '@/lib/prisma'
// Not: import { prisma } from '../../lib/prisma'
Performance Issues
Slow Response Times
Solutions:// Use select to limit fields
const posts = await prisma.post.findMany({
select: {
id: true,
title: true,
// Don't fetch content if not needed
}
})
// Cache frequently accessed data
const cached = await redis.get(key)
if (cached) return JSON.parse(cached)
// Limit results
const posts = await prisma.post.findMany({
take: 20,
skip: page * 20
})
High Memory Usage
Solutions:// Use streaming for large data
const stream = new ReadableStream({
async start(controller) {
for (const chunk of data) {
controller.enqueue(chunk)
}
controller.close()
}
})
# Analyze bundle
ANALYZE=true pnpm build
# Remove unused dependencies
pnpm prune --production
Authentication Issues
Cannot Login
Solutions:# Generate new secret
openssl rand -base64 32
# Update .env.local
AUTH_SECRET=new_secret_here
// Browser console
document.cookie.split(";").forEach(c => {
document.cookie = c.replace(/^ +/, "").replace(/=.*/, "=;expires=" + new Date().toUTCString() + ";path=/")
})
-- Verify user exists
SELECT * FROM "User" WHERE email = 'user@example.com';
Session Expires Too Quickly
Solutions:// auth.config.ts
export const authConfig = {
session: {
strategy: 'jwt',
maxAge: 30 * 24 * 60 * 60, // 30 days
}
}
// Refresh session before expiry
if (session.expires - Date.now() < 3600000) {
await refreshSession()
}
Deployment Issues
Vercel Build Failures
Solutions:vercel logs [deployment-url]
# Simulate production build
pnpm build
pnpm start
vercel --force
Environment Variable Issues
Solutions:vercel env pull .env.local
// Common mistake: NEXT_PUBLIC_ prefix
// Client-side needs: NEXT_PUBLIC_APP_URL
// Server-side needs: APP_URL
Browser Issues
Works in Chrome but not Safari
Solutions:// Polyfill for Safari
if (!window.TextEncoder) {
window.TextEncoder = TextEncoder
}
// Fallback for older browsers
if (!window.EventSource) {
// Use polling instead
}
CORS Errors
Solutions:// middleware.ts
export function middleware(request: NextRequest) {
const response = NextResponse.next()
response.headers.set('Access-Control-Allow-Origin', '*')
response.headers.set('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
return response
}
// Ensure OPTIONS handled
export async function OPTIONS() {
return new Response(null, { status: 200 })
}
Getting Help
Debug Mode
# Enable debug logging
DEBUG=* pnpm dev
# Specific module
DEBUG=prisma:query pnpm dev