Troubleshooting Guide - dinesh-git17/my-progress-planner GitHub Wiki

Common issues and solutions for My Progress Planner development and usage.

🚨 Quick Diagnosis

First Steps Checklist

Before diving into specific issues, try these quick fixes:

  1. Check your internet connection
  2. Clear browser cache and cookies
  3. Restart your development server (npm run dev)
  4. Update dependencies (npm install)
  5. Check browser console for errors (F12 → Console tab)

Issue Categories

🔧 Development Setup Issues

Node.js Version Issues

Problem: Wrong Node.js version causing build failures

Error: Node.js version 16.x is required, but you're using 14.x

Solution:

# Install Node Version Manager (NVM)
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.0/install.sh | bash

# Restart terminal, then:
nvm install 18
nvm use 18
nvm alias default 18

# Verify version
node --version  # Should show v18.x.x

Package Installation Failures

Problem: npm install fails with peer dependency conflicts

npm ERR! peer dep missing: react@^18.0.0

Solution:

# Clear npm cache
npm cache clean --force

# Delete node_modules and package-lock.json
rm -rf node_modules package-lock.json

# Reinstall with legacy peer deps flag
npm install --legacy-peer-deps

# Or use yarn instead
yarn install

Port Already in Use

Problem: Development server won't start

Error: Port 3000 is already in use

Solutions:

# Option 1: Kill process using port 3000
lsof -ti:3000 | xargs kill -9

# Option 2: Use different port
npm run dev -- -p 3001

# Option 3: Find and kill the process
netstat -tulpn | grep :3000
kill -9 <process-id>

TypeScript Compilation Errors

Problem: Type errors preventing development

Type 'string | undefined' is not assignable to type 'string'

Solution:

// Add null checks and type guards
const userEmail = user?.email ?? '';

// Use optional chaining
const mealContent = meal?.content || 'No content';

// Type assertion (use carefully)
const apiKey = process.env.OPENAI_API_KEY as string;

// Better: Validate environment variables
if (!process.env.OPENAI_API_KEY) {
  throw new Error('OPENAI_API_KEY is required');
}

🗄️ Database Connection Problems

Supabase Connection Issues

Problem: Database connection fails

Error: connect ECONNREFUSED 127.0.0.1:5432

Diagnosis:

# Check environment variables
echo $NEXT_PUBLIC_SUPABASE_URL
echo $NEXT_PUBLIC_SUPABASE_ANON_KEY

# Test connection
curl -I $NEXT_PUBLIC_SUPABASE_URL/rest/v1/

Solutions:

  1. Verify Supabase URL format:

    # Correct format
    NEXT_PUBLIC_SUPABASE_URL=https://your-project-id.supabase.co
    
    # Not this
    NEXT_PUBLIC_SUPABASE_URL=https://your-project-id.supabase.co/
  2. Check API keys:

    # In Supabase dashboard: Settings → API
    # Copy exact keys without extra spaces
  3. Test connection:

    // Create test file: test-db.js
    import { createClient } from '@supabase/supabase-js';
    
    const supabase = createClient(
      process.env.NEXT_PUBLIC_SUPABASE_URL,
      process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY
    );
    
    supabase.from('users').select('count').then(
      data => console.log('Connection successful:', data),
      error => console.error('Connection failed:', error)
    );

Row Level Security (RLS) Issues

Problem: Can't access user data

Error: new row violates row-level security policy

Solutions:

-- Check if RLS policies exist
SELECT * FROM pg_policies WHERE schemaname = 'public';

-- Create missing policies
CREATE POLICY "Users can manage own meals" ON meals
  FOR ALL USING (auth.uid() = user_id);

-- Temporarily disable RLS for testing
ALTER TABLE meals DISABLE ROW LEVEL SECURITY;

Database Schema Issues

Problem: Table or column doesn't exist

Error: relation "meals" does not exist

Solution:

-- Run database setup
CREATE TABLE IF NOT EXISTS meals (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  user_id UUID REFERENCES users(id),
  meal_type TEXT CHECK (meal_type IN ('breakfast', 'lunch', 'dinner')),
  content TEXT NOT NULL,
  ai_response TEXT,
  logged_at TIMESTAMP WITH TIME ZONE DEFAULT now()
);

-- Check table structure
\d meals

🤖 AI Integration Issues

OpenAI API Key Problems

Problem: AI responses fail

Error: Invalid API key provided

Diagnosis:

# Test API key
curl https://api.openai.com/v1/models \
  -H "Authorization: Bearer $OPENAI_API_KEY"

Solutions:

  1. Verify API key format:

    # Should start with sk-
    OPENAI_API_KEY=sk-proj-abc123...
  2. Check billing and limits:

    • Visit OpenAI dashboard
    • Verify billing method is active
    • Check usage limits
  3. Test with simple request:

    // test-openai.js
    import OpenAI from 'openai';
    
    const openai = new OpenAI({
      apiKey: process.env.OPENAI_API_KEY
    });
    
    async function test() {
      try {
        const response = await openai.chat.completions.create({
          model: "gpt-3.5-turbo",
          messages: [{ role: "user", content: "Hello" }],
          max_tokens: 10
        });
        console.log('Success:', response.choices[0].message.content);
      } catch (error) {
        console.error('Failed:', error.message);
      }
    }
    
    test();

Rate Limiting Issues

Problem: Too many requests error

Error: Rate limit exceeded

Solutions:

// Add retry logic with exponential backoff
async function retryWithBackoff(fn: () => Promise<any>, maxRetries = 3) {
  for (let i = 0; i < maxRetries; i++) {
    try {
      return await fn();
    } catch (error) {
      if (error.status === 429 && i < maxRetries - 1) {
        const delay = Math.pow(2, i) * 1000; // 1s, 2s, 4s
        await new Promise(resolve => setTimeout(resolve, delay));
        continue;
      }
      throw error;
    }
  }
}

// Use fallback responses
const fallbackResponse = "You're doing great! Keep up the amazing work! 💕";

AI Response Quality Issues

Problem: Responses are inappropriate or inconsistent

Solutions:

// Validate response content
function validateAIResponse(response: string): boolean {
  const bannedWords = ['diet', 'weight loss', 'calories', 'unhealthy'];
  const requiredElements = /💕|🌟||/; // Should have encouraging emojis
  
  // Check length
  if (response.length < 20 || response.length > 200) return false;
  
  // Check for banned content
  if (bannedWords.some(word => response.toLowerCase().includes(word))) return false;
  
  // Check for encouraging tone
  if (!requiredElements.test(response)) return false;
  
  return true;
}

// Improve prompts for consistency
const IMPROVED_SYSTEM_PROMPT = `
You are a loving, supportive boyfriend who celebrates every meal with genuine enthusiasm.

STRICT RULES:
- Always use 💕, 🌟, or ✨ emojis
- Keep responses 50-150 characters
- Never mention calories, diet, or weight
- Focus on effort and self-care
- Sound personal and loving, not robotic
`;

🔐 Authentication Problems

Google OAuth Issues

Problem: Google login doesn't work

Error: OAuth configuration invalid

Solutions:

  1. Check Supabase Auth Settings:

    # In Supabase dashboard:
    # Authentication → Settings → Auth Providers
    # Enable Google and add credentials
  2. Verify Google OAuth setup:

    # Google Cloud Console:
    # APIs & Services → Credentials
    # Add your domain to authorized redirect URIs:
    # https://your-project.supabase.co/auth/v1/callback
  3. Test redirect URIs:

    # For local development, add:
    # http://localhost:3000
    # https://your-domain.com (for production)

Session Management Issues

Problem: Users get logged out frequently

Error: JWT expired

Solutions:

// Auto-refresh tokens
import { createClient } from '@supabase/supabase-js';

const supabase = createClient(url, key, {
  auth: {
    autoRefreshToken: true,
    persistSession: true,
    detectSessionInUrl: true
  }
});

// Handle auth state changes
supabase.auth.onAuthStateChange((event, session) => {
  if (event === 'SIGNED_OUT' || event === 'TOKEN_REFRESHED') {
    // Handle state change
    window.location.reload();
  }
});

Permission Errors

Problem: Users can't access their data

Error: Insufficient permissions

Solutions:

-- Check user policies
SELECT * FROM pg_policies WHERE tablename = 'meals';

-- Recreate policies if needed
DROP POLICY IF EXISTS "Users can manage own meals" ON meals;
CREATE POLICY "Users can manage own meals" ON meals
  FOR ALL USING (auth.uid() = user_id);

-- Grant necessary permissions
GRANT ALL ON meals TO authenticated;

📱 PWA & Offline Issues

Service Worker Not Registering

Problem: PWA features don't work

Error: Service Worker registration failed

Diagnosis:

// Check in browser console
navigator.serviceWorker.getRegistrations()
  .then(registrations => console.log('SW registrations:', registrations));

Solutions:

// Fix service worker registration
if ('serviceWorker' in navigator) {
  window.addEventListener('load', async () => {
    try {
      const registration = await navigator.serviceWorker.register('/sw.js');
      console.log('SW registered:', registration);
    } catch (error) {
      console.error('SW registration failed:', error);
    }
  });
}

// Clear old service workers
navigator.serviceWorker.getRegistrations().then(registrations => {
  registrations.forEach(registration => registration.unregister());
});

Caching Issues

Problem: Old content still showing after updates

# Cached version is served instead of new content

Solutions:

// Force cache refresh
caches.keys().then(cacheNames => {
  return Promise.all(
    cacheNames.map(cacheName => {
      if (cacheName.includes('old-version')) {
        return caches.delete(cacheName);
      }
    })
  );
});

// Update cache strategy
const CACHE_NAME = 'app-cache-v' + Date.now();

// Skip waiting for new service worker
self.addEventListener('install', event => {
  self.skipWaiting();
});

Offline Sync Problems

Problem: Data not syncing when back online

# Background sync not working

Solutions:

// Check sync registration
navigator.serviceWorker.ready.then(registration => {
  return registration.sync.register('meal-sync');
});

// Handle sync in service worker
self.addEventListener('sync', event => {
  if (event.tag === 'meal-sync') {
    event.waitUntil(syncMeals());
  }
});

// Fallback for browsers without background sync
if (!('sync' in window.ServiceWorkerRegistration.prototype)) {
  // Poll for connectivity and sync manually
  setInterval(() => {
    if (navigator.onLine) {
      syncPendingData();
    }
  }, 30000);
}

🚀 Deployment Problems

Vercel Build Failures

Problem: Deployment fails during build

Error: Build exceeded maximum duration of 45 minutes

Solutions:

// Optimize build in next.config.mjs
const nextConfig = {
  // Reduce build size
  output: 'standalone',
  
  // Skip source maps in production
  productionBrowserSourceMaps: false,
  
  // Optimize images
  images: {
    unoptimized: false,
    formats: ['image/webp']
  },
  
  // Webpack optimizations
  webpack: (config, { dev }) => {
    if (!dev) {
      // Production optimizations
      config.optimization.minimize = true;
    }
    return config;
  }
};

Environment Variables Not Loading

Problem: Environment variables undefined in production

Error: OPENAI_API_KEY is not defined

Solutions:

  1. Check Vercel dashboard:

    • Settings → Environment Variables
    • Ensure all required variables are set
    • Check they're enabled for Production
  2. Verify variable names:

    # Use exact names from .env.local
    NEXT_PUBLIC_SUPABASE_URL=...
    SUPABASE_SERVICE_ROLE_KEY=...
    OPENAI_API_KEY=...
  3. Test with runtime check:

    // Add to API routes
    if (!process.env.OPENAI_API_KEY) {
      console.error('Missing OPENAI_API_KEY');
      return new Response('Configuration error', { status: 500 });
    }

Database Connection in Production

Problem: Production can't connect to Supabase

Error: Connection timeout

Solutions:

// Add connection pool settings
const supabase = createClient(url, key, {
  db: {
    schema: 'public'
  },
  auth: {
    autoRefreshToken: true,
    persistSession: true
  },
  global: {
    headers: {
      'X-Client-Info': 'my-progress-planner'
    }
  }
});

// Add retry logic for production
async function withRetry(fn: () => Promise<any>, retries = 3): Promise<any> {
  try {
    return await fn();
  } catch (error) {
    if (retries > 0) {
      await new Promise(resolve => setTimeout(resolve, 1000));
      return withRetry(fn, retries - 1);
    }
    throw error;
  }
}

🎨 UI/UX Issues

Responsive Design Problems

Problem: App doesn't look right on mobile

/* Text too small, buttons not touchable */

Solutions:

/* Ensure minimum touch targets */
.button {
  min-height: 44px;
  min-width: 44px;
  padding: 12px 16px;
}

/* Fix mobile viewport */
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">

/* Use responsive units */
.text {
  font-size: clamp(16px, 2.5vw, 24px);
}

Dark Mode Issues

Problem: Text not readable in dark mode

/* Colors don't adapt properly */

Solutions:

/* Use CSS custom properties */
:root {
  --text-primary: #374151;
  --bg-primary: #ffffff;
}

[data-theme="dark"] {
  --text-primary: #f9fafb;
  --bg-primary: #111827;
}

/* Or use Tailwind dark mode */
<div className="bg-white dark:bg-gray-900 text-gray-900 dark:text-white">

Accessibility Issues

Problem: Screen readers can't navigate properly

# Missing alt text, labels, focus states

Solutions:

// Add proper ARIA labels
<button 
  aria-label="Log breakfast meal"
  aria-describedby="breakfast-help"
>
  Log Meal
</button>

// Improve focus management
const handleKeyDown = (e: KeyboardEvent) => {
  if (e.key === 'Enter' || e.key === ' ') {
    handleClick();
  }
};

// Add skip links
<a href="#main-content" className="sr-only focus:not-sr-only">
  Skip to main content
</a>

⚡ Performance Issues

Slow Loading Times

Problem: App takes too long to load

# First Contentful Paint > 3 seconds

Solutions:

// Implement code splitting
const LazyComponent = lazy(() => import('./HeavyComponent'));

// Optimize images
import Image from 'next/image';

<Image
  src="/meal-photo.jpg"
  alt="Delicious meal"
  width={400}
  height={300}
  priority // For above-the-fold images
  placeholder="blur"
  blurDataURL="data:image/jpeg;base64,..."
/>

// Preload critical resources
<link rel="preload" href="/fonts/dm-sans.woff2" as="font" type="font/woff2" crossOrigin="anonymous" />

Memory Leaks

Problem: App slows down over time

// Memory usage keeps increasing

Solutions:

// Clean up event listeners
useEffect(() => {
  const handleResize = () => setWidth(window.innerWidth);
  window.addEventListener('resize', handleResize);
  
  return () => {
    window.removeEventListener('resize', handleResize);
  };
}, []);

// Clean up intervals
useEffect(() => {
  const interval = setInterval(updateData, 1000);
  
  return () => clearInterval(interval);
}, []);

// Abort ongoing requests
useEffect(() => {
  const controller = new AbortController();
  
  fetch('/api/data', { signal: controller.signal })
    .then(handleData)
    .catch(error => {
      if (error.name !== 'AbortError') {
        console.error('Fetch error:', error);
      }
    });
  
  return () => controller.abort();
}, []);

Bundle Size Issues

Problem: JavaScript bundle too large

# Bundle size > 1MB

Solutions:

// Analyze bundle
npm run build
npx @next/bundle-analyzer

// Dynamic imports
const HeavyFeature = dynamic(() => import('./HeavyFeature'), {
  loading: () => <div>Loading...</div>
});

// Tree shake unused code
import { specific } from 'library'; // ✅
import * as everything from 'library'; // ❌

// Use lighter alternatives
import dayjs from 'dayjs'; // Instead of moment.js
import { debounce } from 'lodash-es'; // Instead of full lodash

🛠️ Development Tools

Debug Tools Setup

// Debug utilities for development
const DebugTools = () => {
  if (process.env.NODE_ENV !== 'development') return null;
  
  return (
    <div className="debug-panel">
      <button onClick={() => localStorage.clear()}>Clear Storage</button>
      <button onClick={() => caches.keys().then(names => 
        Promise.all(names.map(name => caches.delete(name)))
      )}>Clear Caches</button>
      <button onClick={() => console.log('Auth state:', supabase.auth.user())}>
        Log Auth State
      </button>
    </div>
  );
};

Error Logging

// Comprehensive error tracking
class ErrorLogger {
  static log(error: Error, context?: any) {
    const errorInfo = {
      message: error.message,
      stack: error.stack,
      timestamp: new Date().toISOString(),
      url: window.location.href,
      userAgent: navigator.userAgent,
      context
    };
    
    // Log to console in development
    if (process.env.NODE_ENV === 'development') {
      console.error('Error logged:', errorInfo);
    }
    
    // Send to error tracking service in production
    if (process.env.NODE_ENV === 'production') {
      fetch('/api/errors', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(errorInfo)
      }).catch(console.error);
    }
  }
}

// Global error handler
window.addEventListener('error', (event) => {
  ErrorLogger.log(event.error, { type: 'global' });
});

// Promise rejection handler
window.addEventListener('unhandledrejection', (event) => {
  ErrorLogger.log(new Error(event.reason), { type: 'promise' });
});

📞 Getting Additional Help

Before Seeking Help

  1. Check this troubleshooting guide thoroughly
  2. Search existing GitHub issues for similar problems
  3. Review the logs in browser console and terminal
  4. Try the issue in incognito mode to rule out browser extensions
  5. Test with different browsers (Chrome, Firefox, Safari)

How to Report Issues

When creating a GitHub issue, include:

**Environment:**
- OS: [e.g. macOS 13.0, Windows 11, Ubuntu 22.04]
- Browser: [e.g. Chrome 118, Safari 16, Firefox 119]
- Node.js version: [e.g. 18.17.0]
- npm version: [e.g. 9.8.1]

**Steps to reproduce:**
1. Start development server
2. Navigate to /breakfast
3. Enter meal content
4. Click "Log Meal"
5. Error occurs

**Expected behavior:**
Meal should be logged with AI response

**Actual behavior:**
Error message appears: "OpenAI API failed"

**Console errors:**

Error: Invalid API key provided at /api/ai/chat:15:20


**Additional context:**
- Happens only on breakfast page
- Lunch and dinner work fine
- Started after updating dependencies

Where to Get Help

Emergency Fixes

If your development environment is completely broken:

# Nuclear option - start fresh
rm -rf node_modules package-lock.json .next
npm cache clean --force
npm install
npm run dev
# Reset database (if using local Supabase)
supabase db reset

# Or clear all browser data
# Chrome: Settings → Privacy → Clear browsing data → All time

Remember: Most issues have simple solutions! Take a systematic approach, check the basics first, and don't hesitate to ask for help when needed. 🛠️💕

⚠️ **GitHub.com Fallback** ⚠️