A comprehensive guide for debugging issues in the Yemaya platform.
Table of Contents#
- Development Environment
- Debugging the API
- Debugging the Web App
- Debugging the Desktop App
- Database Issues
- Common Issues
- Performance Debugging
- Logging
- Tools and Techniques
Development Environment#
Quick Health Check#
Run these commands to verify your environment:
# Check Node version
node -v # Should be v20+
# Check pnpm version
pnpm -v # Should be v10+
# Check Docker is running
docker ps
# Verify infrastructure services
docker compose ps
Infrastructure Not Starting#
If docker compose up fails:
# Check for port conflicts
lsof -i :5432 # PostgreSQL
lsof -i :6379 # Redis
lsof -i :9000 # MinIO
# View container logs
docker compose logs postgres
docker compose logs redis
# Restart fresh
docker compose down -v
docker compose up -d
Dependency Issues#
# Clear node_modules and reinstall
rm -rf node_modules
rm -rf apps/*/node_modules
rm -rf packages/*/node_modules
pnpm install
# Clear pnpm cache if needed
pnpm store prune
# Rebuild native dependencies
pnpm rebuild
TypeScript Errors After Pull#
# Rebuild all packages in order
pnpm build
# Or rebuild specific package
pnpm --filter @yemaya/types build
pnpm --filter @yemaya/core build
Debugging the API#
Enable Debug Logging#
Set environment variables in .env:
# Enable verbose logging
LOG_LEVEL=debug
# Log all database queries
DATABASE_LOG_QUERIES=true
# Log HTTP requests
DEBUG=hono:*
VS Code Launch Configuration#
Create .vscode/launch.json:
{
"version": "0.2.0",
"configurations": [
{
"name": "Debug API",
"type": "node",
"request": "launch",
"runtimeExecutable": "pnpm",
"runtimeArgs": ["--filter", "@yemaya/api", "dev"],
"cwd": "${workspaceFolder}",
"console": "integratedTerminal",
"env": {
"NODE_ENV": "development",
"LOG_LEVEL": "debug"
}
}
]
}
Debugging with Breakpoints#
- Add
debuggerstatement in code:
async function handleRequest(c: Context) {
debugger; // Execution pauses here
const user = await getUser(c.get('userId'));
return c.json({ user });
}
- Or use VS Code breakpoints with source maps
Inspect API Requests#
Use the built-in request logger:
// In development, all requests are logged
// Output: <-- GET /v1/projects
// --> GET /v1/projects 200 45ms
For detailed request/response inspection:
# Use curl with verbose output
curl -v http://localhost:3000/v1/projects \
-H "Authorization: Bearer $TOKEN"
# Use httpie for cleaner output
http GET localhost:3000/v1/projects Authorization:"Bearer $TOKEN"
API Error Investigation#
When you receive an error response:
{
"success": false,
"error": {
"code": "VALIDATION_ERROR",
"message": "Invalid input",
"details": { "name": ["Required"] }
}
}
- Check the error code in
packages/core/src/errors/ - Search codebase for where error is thrown
- Add logging before the throw statement
// Add temporary logging
console.log('Validation input:', JSON.stringify(input, null, 2));
throw new ValidationError('Invalid input', details);
Debugging the Web App#
React DevTools#
Install the React DevTools browser extension for:
- Component tree inspection
- Props and state examination
- Performance profiling
- Hooks debugging
TanStack Query DevTools#
Already included in development mode. Access via the floating button in bottom-right corner.
Features:
- View all queries and their status
- Inspect cached data
- Trigger refetches
- View query timelines
Console Debugging#
// Log component renders
function ProjectList() {
console.log('ProjectList rendered');
// ...
}
// Log state changes
useEffect(() => {
console.log('Projects changed:', projects);
}, [projects]);
// Log with component name
console.log('[ProjectList]', 'Loading projects...');
Network Tab#
Use browser DevTools Network tab to:
- Filter by
Fetch/XHRto see API calls - Check request headers (especially Authorization)
- Examine response bodies
- Look for failed requests (red)
Source Maps#
Source maps are enabled in development. To debug:
- Open browser DevTools > Sources
- Navigate to
webpack://orvite://sources - Set breakpoints in original TypeScript files
State Debugging#
For Zustand stores:
// Enable devtools
import { devtools } from 'zustand/middleware';
const useStore = create(
devtools(
(set) => ({
// ...
}),
{ name: 'ProjectStore' }
)
);
View in Redux DevTools browser extension.
Debugging the Desktop App#
Main Process#
The main process runs in Node.js. Debug with:
# Start with inspector
pnpm desktop dev --inspect
# Or with specific port
pnpm desktop dev --inspect=9229
Then in Chrome:
- Navigate to
chrome://inspect - Click "Open dedicated DevTools for Node"
- Set breakpoints in main process code
Renderer Process#
The renderer is a Chromium window:
- In the app, press
Cmd+Option+I(Mac) orCtrl+Shift+I(Windows/Linux) - DevTools opens with full debugging capabilities
IPC Communication#
Debug IPC messages:
// In main process
ipcMain.handle('get-project', async (event, projectId) => {
console.log('[IPC Main] get-project:', projectId);
const result = await getProject(projectId);
console.log('[IPC Main] result:', result);
return result;
});
// In renderer process
const result = await window.api.getProject(projectId);
console.log('[IPC Renderer] result:', result);
Production Builds#
Debug production builds locally:
# Build the app
pnpm desktop build
# Run the built app with console output
# macOS
./dist/mac/Yemaya.app/Contents/MacOS/Yemaya --enable-logging
# Windows
.\dist\win-unpacked\Yemaya.exe --enable-logging
# Linux
./dist/linux-unpacked/yemaya --enable-logging
Database Issues#
Connection Problems#
# Test PostgreSQL connection
docker compose exec postgres psql -U postgres -d yemaya -c "SELECT 1"
# Check connection string
echo $DATABASE_URL
# Verify from Node.js
pnpm --filter @yemaya/database db:test-connection
Migration Issues#
# Check migration status
pnpm --filter @yemaya/database db:migrate:status
# Reset database (WARNING: destroys data)
pnpm --filter @yemaya/database db:reset
# Generate migration from schema changes
pnpm --filter @yemaya/database db:migrate:dev
# Apply pending migrations
pnpm --filter @yemaya/database db:migrate
Query Debugging#
Enable query logging in Prisma:
// packages/database/src/client.ts
const prisma = new PrismaClient({
log: [
{ emit: 'event', level: 'query' },
{ emit: 'stdout', level: 'error' },
{ emit: 'stdout', level: 'warn' },
],
});
prisma.$on('query', (e) => {
console.log('Query:', e.query);
console.log('Params:', e.params);
console.log('Duration:', e.duration, 'ms');
});
Prisma Studio#
Visual database browser:
pnpm --filter @yemaya/database db:studio
Opens at http://localhost:5555
Data Inspection#
# Connect to database
docker compose exec postgres psql -U postgres -d yemaya
# Common queries
\dt # List tables
\d users # Describe users table
SELECT * FROM users LIMIT 5; # Sample data
SELECT count(*) FROM projects;
Common Issues#
"Cannot find module"#
# Ensure all packages are built
pnpm build
# Check package exports in package.json
cat packages/core/package.json | jq '.exports'
# Verify the file exists
ls packages/core/dist/
"Port already in use"#
# Find process using port
lsof -i :3000
# Kill process
kill -9 <PID>
# Or use different port
PORT=3001 pnpm --filter @yemaya/api dev
TypeScript Errors#
# Check specific package
pnpm --filter @yemaya/core typecheck
# Clear TypeScript cache
rm -rf node_modules/.cache/typescript
pnpm typecheck
"Hydration mismatch" (React)#
This occurs when server/client HTML differs:
- Check for
typeof window !== 'undefined'guards - Avoid reading
localStorageduring render - Use
useEffectfor client-only code
// Bad - causes hydration mismatch
function Component() {
const theme = localStorage.getItem('theme'); // Runs on server too
return <div className={theme}>...</div>;
}
// Good - client-only
function Component() {
const [theme, setTheme] = useState('light');
useEffect(() => {
setTheme(localStorage.getItem('theme') || 'light');
}, []);
return <div className={theme}>...</div>;
}
"CORS error"#
Check API CORS configuration:
// apps/api/src/app.ts
app.use(
cors({
origin: ['http://localhost:5173'], // Add your frontend URL
credentials: true,
})
);
Authentication Issues#
Debug token flow:
// Check token contents
const token = localStorage.getItem('accessToken');
const payload = JSON.parse(atob(token.split('.')[1]));
console.log('Token payload:', payload);
console.log('Expires:', new Date(payload.exp * 1000));
Performance Debugging#
API Performance#
// Add timing middleware
app.use('*', async (c, next) => {
const start = performance.now();
await next();
const duration = performance.now() - start;
if (duration > 100) {
console.warn(`Slow request: ${c.req.method} ${c.req.path} - ${duration}ms`);
}
});
Database Query Performance#
# Enable slow query logging
docker compose exec postgres psql -U postgres -d yemaya -c "
ALTER SYSTEM SET log_min_duration_statement = 100;
SELECT pg_reload_conf();
"
# View slow queries
docker compose logs postgres | grep duration
React Performance#
Use React DevTools Profiler:
- Open React DevTools
- Go to "Profiler" tab
- Click "Record"
- Perform action
- Click "Stop"
- Analyze flame graph
Look for:
- Components re-rendering unnecessarily
- Expensive computations in render
- Missing memoization
Memory Leaks#
// Watch for growing heap
setInterval(() => {
const used = process.memoryUsage();
console.log({
heapUsed: Math.round(used.heapUsed / 1024 / 1024) + 'MB',
heapTotal: Math.round(used.heapTotal / 1024 / 1024) + 'MB',
});
}, 10000);
For React, check for:
- Uncleared intervals/timeouts
- Event listeners not removed
- Subscriptions not unsubscribed
useEffect(() => {
const interval = setInterval(fetchData, 5000);
return () => clearInterval(interval); // Cleanup!
}, []);
Logging#
Structured Logging#
import { logger } from '@yemaya/core';
// Log levels: debug, info, warn, error
logger.info('User logged in', {
userId: user.id,
email: user.email,
method: 'password',
});
logger.error('Failed to process upload', {
error: err.message,
stack: err.stack,
fileId,
userId,
});
Log Output Format#
Development (pretty):
2024-01-15T10:30:00.000Z INFO User logged in
userId: usr_abc123
email: user@example.com
Production (JSON):
{
"timestamp": "2024-01-15T10:30:00.000Z",
"level": "info",
"message": "User logged in",
"userId": "usr_abc123",
"email": "user@example.com"
}
Log Filtering#
# Filter by level
LOG_LEVEL=warn pnpm --filter @yemaya/api dev
# Filter by module (using DEBUG)
DEBUG=yemaya:auth,yemaya:database pnpm --filter @yemaya/api dev
Tools and Techniques#
Interactive REPL#
# Start Node REPL with project loaded
node --experimental-repl-await
# Then import modules
> const { db } = await import('@yemaya/database')
> const users = await db.user.findMany({ take: 5 })
Postman/Insomnia#
Import OpenAPI spec for easy API testing:
# Export OpenAPI spec
curl http://localhost:3000/openapi.json > openapi.json
Then import into Postman or Insomnia.
Database GUI#
- TablePlus: Clean interface for PostgreSQL
- DBeaver: Free, cross-platform
- pgAdmin: Official PostgreSQL tool
Network Debugging#
# Capture network traffic
sudo tcpdump -i lo0 port 3000 -w capture.pcap
# Analyze with Wireshark
wireshark capture.pcap
Git Bisect#
Find the commit that introduced a bug:
# Start bisecting
git bisect start
# Mark current commit as bad
git bisect bad
# Mark known good commit
git bisect good v1.0.0
# Git checks out a commit - test it
pnpm test
# Mark result and continue
git bisect good # or git bisect bad
# When done
git bisect reset
Getting Help#
If you're stuck:
- Search existing issues on GitHub
- Check the FAQ in docs
- Ask in Discord #help channel
- Create a GitHub issue with:
- Steps to reproduce
- Expected behavior
- Actual behavior
- Environment details
- Relevant logs
Include debug output:
# Gather environment info
node -v
pnpm -v
docker --version
cat .env | grep -v KEY | grep -v SECRET