Troubleshooting Guide

Comprehensive troubleshooting resources organized by category to help you resolve issues quickly and effectively.

Troubleshooting Guide

Welcome to the comprehensive troubleshooting guide. This section is organized by problem categories to help you find solutions quickly and efficiently.

Quick Problem Resolution

🚨 Emergency Issues

🔍 Most Common Issues

  1. Build FailuresInstallation & Setup
  2. Component ErrorsRuntime Errors
  3. Slow PerformancePerformance Problems
  4. Login IssuesAuthentication & Authorization

Troubleshooting Categories

🛠️ Common Issues

Frequent problems and their quick solutions:

  • Quick Fixes: Simple solutions for common problems
  • Startup Issues: Getting your development environment running
  • Configuration Problems: Environment and setup issues
  • Basic Debugging: First steps in problem-solving

📦 Installation & Setup

Resolving installation and environment setup problems:

  • Package Installation: npm/yarn dependency issues
  • Environment Configuration: Node.js, development tools
  • Project Setup: Initial project configuration
  • Dependency Conflicts: Version compatibility issues

⚠️ Runtime Errors

Debugging application runtime issues:

  • Component Errors: React component problems
  • Hydration Issues: SSR/CSR mismatches
  • API Route Errors: Server-side endpoint problems
  • Memory Leaks: Performance and resource issues

🗄️ Database Issues

Database connection and query troubleshooting:

  • Connection Problems: Supabase connectivity issues
  • Query Optimization: Slow or failing database queries
  • RLS Policies: Row Level Security configuration
  • Migration Issues: Database schema updates

Performance Problems

Performance optimization and monitoring:

  • Bundle Size: JavaScript optimization strategies
  • Loading Speed: Core Web Vitals improvement
  • Memory Usage: Resource management
  • Database Performance: Query optimization

🔐 Authentication & Authorization

User authentication and permission issues:

  • Login Problems: Sign-in flow troubleshooting
  • Session Management: Token and session handling
  • Role-Based Access: Permission configuration
  • Security Issues: Authentication security

🚀 Deployment Issues

Production deployment troubleshooting:

  • Build Failures: Compilation and build problems
  • Environment Variables: Production configuration
  • Platform Issues: Vercel, Netlify, Docker deployment
  • Performance in Production: Production optimization

💻 Development Environment

Local development setup and configuration:

  • IDE Setup: VS Code configuration and extensions
  • Local Database: Supabase local development
  • Development Tools: Debugging and profiling tools
  • Git Workflow: Version control best practices

🔧 Debugging Tools & Techniques

Advanced debugging methodologies:

  • Browser DevTools: Chrome/Firefox debugging
  • React DevTools: Component and state debugging
  • Performance Profiling: Performance analysis tools
  • Logging Systems: Error tracking and monitoring

🆘 Support Resources

Finding help and community support:

  • Documentation: Official guides and references
  • Community Support: Forums, Discord, Stack Overflow
  • Professional Help: Consulting and paid support
  • Learning Resources: Tutorials and educational content

For specialized troubleshooting in specific domains, also check these focused guides:

📦 Installation Troubleshooting

Detailed installation and setup troubleshooting specifically for:

  • Environment setup issues
  • Supabase configuration problems
  • Dependency conflicts
  • Initial project setup

Performance Troubleshooting

In-depth performance debugging covering:

  • Database query optimization
  • Memory leak detection
  • Bundle size analysis
  • Runtime performance issues

🚀 Deployment Troubleshooting

Production deployment specific issues:

  • Build pipeline problems
  • Environment configuration
  • Platform-specific issues
  • Production monitoring

Troubleshooting Methodology

Step-by-Step Approach

graph TD
    A[Problem Identified] --> B[Reproduce the Issue]
    B --> C[Check Error Messages]
    C --> D[Search Documentation]
    D --> E[Check Community Resources]
    E --> F[Create Minimal Reproduction]
    F --> G[Debug Systematically]
    G --> H{Issue Resolved?}
    H -->|Yes| I[Document Solution]
    H -->|No| J[Seek Community Help]
    J --> K[Contact Professional Support]

1. Problem Identification

  • Describe the Issue: What exactly is not working?
  • Expected vs Actual: What should happen vs what actually happens?
  • Context: When did this start? What changed recently?

2. Information Gathering

// Collect this information before seeking help
const troubleshootingInfo = {
  environment: {
    nodeVersion: process.version,
    nextjsVersion: '14.0.0', // Check package.json
    browserInfo: navigator.userAgent,
    operatingSystem: 'Windows/macOS/Linux',
  },
  errorDetails: {
    errorMessage: 'Full error message',
    stackTrace: 'Complete stack trace',
    errorLocation: 'File and line number',
    reproducible: true, // Can you reproduce it?
  },
  recentChanges: [
    'What was changed recently?',
    'New packages installed?',
    'Configuration updates?',
  ],
}

3. Systematic Debugging

  1. Start Simple: Begin with the most basic case
  2. Isolate the Problem: Remove complexity until issue is isolated
  3. Check One Thing at a Time: Make single changes and test
  4. Use Debug Tools: Leverage browser DevTools and logging
  5. Read Error Messages Carefully: They often contain the solution

Best Practices

Before You Debug

  • Save Your Work: Commit or backup current state
  • Read Error Messages: Don't skip the details
  • Check Documentation: Search official docs first
  • Verify Environment: Ensure all dependencies are correct

During Debugging

  • 🔍 Use Browser DevTools: Network, Console, Sources tabs
  • 📝 Keep Notes: Document what you try and results
  • 🧪 Test Incrementally: Make small changes and test
  • 💡 Think Logically: Follow the data flow and execution path

After Resolution

  • 📚 Document the Solution: Help your future self and others
  • 🧹 Clean Up Debug Code: Remove temporary debugging code
  • 🔄 Review Root Cause: Understand why it happened
  • 📈 Improve Prevention: How can you avoid this in the future?

Emergency Protocols

Production Issues

  1. Assess Impact: How many users affected?
  2. Quick Mitigation: Can you rollback or implement a hotfix?
  3. Communicate: Inform stakeholders about the issue
  4. Fix and Deploy: Implement proper fix and deploy
  5. Post-Mortem: Analyze what happened and improve processes

Development Blockers

  1. Try Alternative Approach: Is there another way to achieve the goal?
  2. Seek Help Quickly: Don't spend too long stuck
  3. Document the Blocker: Help others who might face the same issue
  4. Update Timeline: Communicate delays if working with a team

Getting Help

Information to Include When Asking for Help

  • Clear Problem Description: What you're trying to do and what's failing
  • Environment Details: Versions, OS, browser information
  • Code Sample: Minimal reproduction of the issue
  • Error Messages: Complete error messages and stack traces
  • Steps Taken: What you've already tried

Where to Get Help

  • Official Documentation: Always check docs first
  • GitHub Issues: Search existing issues in relevant repositories
  • Stack Overflow: Use appropriate tags ([nextjs], [reactjs], [supabase])
  • Discord Communities: Real-time help from community members
  • Professional Support: For critical business applications

Remember: Effective troubleshooting is a skill that improves with practice. Start with the basics, be systematic in your approach, and don't hesitate to seek help when needed. The development community is generally very helpful and supportive!

Common Issues

Application Won't Start

Issue: npm run dev fails to start

Symptoms:

  • Command fails with errors
  • Port already in use
  • Module not found errors

Solutions:

# Check if port is in use
lsof -i :3000  # macOS/Linux
netstat -ano | findstr :3000  # Windows

# Kill process using port
kill -9 <PID>  # macOS/Linux
taskkill /PID <PID> /F  # Windows

# Clear Next.js cache
rm -rf .next
rm -rf node_modules
npm install

# Try different port
npm run dev -- --port 3001

Issue: TypeScript compilation errors

Symptoms:

  • Type errors preventing compilation
  • Module resolution failures

Solutions:

# Check TypeScript configuration
npx tsc --noEmit

# Update dependencies
npm update

# Check for type definition issues
npm install --save-dev @types/node @types/react @types/react-dom

# Clear TypeScript cache
rm -rf .next
rm -rf node_modules/.cache

Environment Configuration Issues

Issue: Environment variables not loading

Symptoms:

  • Undefined environment variables
  • Configuration errors

Solutions:

# Check .env.local file exists
ls -la .env*

# Verify environment variables
echo $NEXT_PUBLIC_SUPABASE_URL
echo $SUPABASE_SERVICE_ROLE_KEY

# Check variable naming (must start with NEXT_PUBLIC_ for client-side)
# .env.local
NEXT_PUBLIC_SUPABASE_URL=https://your-project.supabase.co
SUPABASE_SERVICE_ROLE_KEY=your-service-role-key

Issue: Supabase connection fails

Symptoms:

  • Database connection errors
  • Authentication failures

Solutions:

// Test Supabase connection
import { createClient } from '@supabase/supabase-js'

const supabase = createClient(
  process.env.NEXT_PUBLIC_SUPABASE_URL!,
  process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!
)

// Test connection
async function testConnection() {
  try {
    const { data, error } = await supabase
      .from('products')
      .select('count')
      .limit(1)
    
    if (error) {
      console.error('Supabase error:', error)
    } else {
      console.log('Supabase connection successful')
    }
  } catch (error) {
    console.error('Connection failed:', error)
  }
}

Installation Problems

Node.js Version Issues

Issue: Node.js version incompatibility

Symptoms:

  • Installation fails with version errors
  • Runtime errors due to unsupported features

Solutions:

# Check Node.js version
node --version

# Install correct version (18.0 or higher)
# Using nvm (recommended)
nvm install 18
nvm use 18

# Or download from nodejs.org

Package Manager Issues

Issue: npm/pnpm installation fails

Symptoms:

  • Package installation errors
  • Dependency resolution conflicts

Solutions:

# Clear npm cache
npm cache clean --force

# Delete node_modules and reinstall
rm -rf node_modules
rm package-lock.json
npm install

# Or use pnpm (recommended)
npm install -g pnpm
pnpm install

# Force reinstall
pnpm install --force

Permission Issues

Issue: Permission denied errors

Symptoms:

  • EACCES errors during installation
  • File system permission errors

Solutions:

# Fix npm permissions (macOS/Linux)
sudo chown -R $(whoami) ~/.npm

# Or use nvm to avoid permission issues
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.0/install.sh | bash

# Windows: Run as administrator
# Right-click command prompt -> "Run as administrator"

Runtime Errors

Component Errors

Issue: Hydration mismatch

Symptoms:

  • Console warnings about hydration
  • Different server/client rendering

Solutions:

// Use dynamic imports with ssr: false
const DynamicComponent = dynamic(() => import('./component'), {
  ssr: false
})

// Use useEffect for client-only code
useEffect(() => {
  // Client-only code here
}, [])

// Suppress hydration warnings (use sparingly)
<div suppressHydrationWarning={true}>
  {/* Content that might differ */}
</div>

Issue: "Cannot read properties of undefined"

Symptoms:

  • Runtime errors accessing undefined properties
  • Application crashes

Solutions:

// Use optional chaining
const name = user?.profile?.name

// Use nullish coalescing
const displayName = user?.name ?? 'Unknown'

// Add proper type guards
if (user && user.profile) {
  console.log(user.profile.name)
}

// Use default values
const { name = 'Default' } = user || {}

API Route Errors

Issue: API routes returning 404

Symptoms:

  • API endpoints not found
  • Routing issues

Solutions:

// Check file structure
app/
├── api/
│   ├── products/
│   │   ├── route.ts  // /api/products
│   │   └── [id]/
│   │       └── route.ts  // /api/products/[id]

// Verify export names
export async function GET(request: Request) {
  // GET handler
}

export async function POST(request: Request) {
  // POST handler
}

// Check for TypeScript errors
npx tsc --noEmit

Issue: CORS errors

Symptoms:

  • Cross-origin request blocked
  • Preflight request failures

Solutions:

// Add CORS headers
export async function GET(request: Request) {
  const response = await fetch(/* ... */)
  
  return new Response(response.body, {
    status: response.status,
    headers: {
      'Access-Control-Allow-Origin': '*',
      'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE',
      'Access-Control-Allow-Headers': 'Content-Type, Authorization',
    }
  })
}

// Or use Next.js middleware
// 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, PUT, DELETE')
  response.headers.set('Access-Control-Allow-Headers', 'Content-Type, Authorization')
  
  return response
}

Database Issues

Connection Problems

Issue: Database connection timeout

Symptoms:

  • Connection timeout errors
  • Slow database responses

Solutions:

// Increase timeout in Supabase client
const supabase = createClient(url, key, {
  db: {
    schema: 'public',
  },
  global: {
    headers: {
      'X-Client-Info': 'smart-shelf',
    },
  },
  // Increase timeout
  realtime: {
    params: {
      timeout: 30000,
    },
  },
})

// Add retry logic
async function withRetry<T>(
  operation: () => Promise<T>,
  maxRetries: number = 3
): Promise<T> {
  for (let i = 0; i < maxRetries; i++) {
    try {
      return await operation()
    } catch (error) {
      if (i === maxRetries - 1) throw error
      await new Promise(resolve => setTimeout(resolve, 1000 * Math.pow(2, i)))
    }
  }
  throw new Error('Max retries exceeded')
}

Query Issues

Issue: Slow database queries

Symptoms:

  • Long response times
  • Timeout errors

Solutions:

-- Add indexes for frequently queried columns
CREATE INDEX CONCURRENTLY idx_products_name ON products(name);
CREATE INDEX CONCURRENTLY idx_inventory_product_warehouse ON inventory(product_id, warehouse_id);

-- Optimize queries
EXPLAIN ANALYZE SELECT * FROM products WHERE name ILIKE '%search%';

-- Use proper LIMIT and OFFSET
SELECT * FROM products 
ORDER BY created_at DESC 
LIMIT 20 OFFSET 0;

Issue: Row Level Security (RLS) blocking queries

Symptoms:

  • No data returned from queries
  • Permission denied errors

Solutions:

-- Check RLS policies
SELECT * FROM pg_policies WHERE tablename = 'products';

-- Create proper RLS policies
CREATE POLICY "Users can view products" ON products
  FOR SELECT USING (true);

CREATE POLICY "Users can insert products" ON products
  FOR INSERT WITH CHECK (auth.role() = 'authenticated');

-- Temporarily disable RLS for debugging (not recommended for production)
ALTER TABLE products DISABLE ROW LEVEL SECURITY;

Migration Issues

Issue: Migration fails

Symptoms:

  • Database schema out of sync
  • Migration errors

Solutions:

# Reset database migrations
supabase db reset

# Apply specific migration
supabase db migrate up --file 20240101000000_initial_schema.sql

# Check migration status
supabase migration list

# Generate new migration
supabase migration new add_products_table

Performance Problems

Slow Page Loading

Issue: Long initial page load times

Symptoms:

  • Slow Time to First Byte (TTFB)
  • Large bundle sizes

Solutions:

// Implement code splitting
const DynamicComponent = dynamic(() => import('./heavy-component'), {
  loading: () => <div>Loading...</div>
})

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

<Image
  src="/product-image.jpg"
  alt="Product"
  width={300}
  height={200}
  priority={true}
/>

// Use Suspense for data fetching
<Suspense fallback={<Loading />}>
  <AsyncComponent />
</Suspense>

Issue: Memory leaks

Symptoms:

  • Increasing memory usage over time
  • Browser becomes unresponsive

Solutions:

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

// Clean up subscriptions
useEffect(() => {
  const subscription = supabase
    .channel('products')
    .on('postgres_changes', { event: '*', schema: 'public', table: 'products' }, handleChange)
    .subscribe()
  
  return () => {
    subscription.unsubscribe()
  }
}, [])

// Avoid creating objects in render
// Bad
const styles = { color: 'red' }
return <div style={styles}>Content</div>

// Good
const styles = useMemo(() => ({ color: 'red' }), [])
return <div style={styles}>Content</div>

API Performance Issues

Issue: Slow API responses

Symptoms:

  • High response times
  • Timeout errors

Solutions:

// Add response caching
export async function GET(request: Request) {
  const { searchParams } = new URL(request.url)
  const cacheKey = `products:${searchParams.toString()}`
  
  // Check cache
  const cached = await redis.get(cacheKey)
  if (cached) {
    return Response.json(JSON.parse(cached))
  }
  
  // Fetch data
  const data = await fetchProducts()
  
  // Cache result
  await redis.setex(cacheKey, 300, JSON.stringify(data))
  
  return Response.json(data)
}

// Optimize database queries
const { data } = await supabase
  .from('products')
  .select(`
    id,
    name,
    sku,
    inventory!inner(quantity_on_hand)
  `)
  .eq('is_active', true)
  .limit(20)

Authentication & Authorization

Login Issues

Issue: Users cannot log in

Symptoms:

  • Authentication failures
  • Redirect loops

Solutions:

// Check authentication configuration
const supabase = createClient(
  process.env.NEXT_PUBLIC_SUPABASE_URL!,
  process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
  {
    auth: {
      redirectTo: `${location.origin}/auth/callback`,
      autoRefreshToken: true,
      persistSession: true,
    },
  }
)

// Debug authentication
async function debugAuth() {
  const { data: { user }, error } = await supabase.auth.getUser()
  console.log('Current user:', user)
  console.log('Auth error:', error)
}

// Check callback URL
// app/auth/callback/route.ts
export async function GET(request: Request) {
  const { searchParams } = new URL(request.url)
  const code = searchParams.get('code')
  
  if (code) {
    const supabase = createClient()
    await supabase.auth.exchangeCodeForSession(code)
  }
  
  return redirect('/dashboard')
}

Authorization Issues

Issue: Users see content they shouldn't

Symptoms:

  • Unauthorized access to features
  • Missing role checks

Solutions:

// Implement role guards
export function RoleGuard({ 
  children, 
  requiredRole 
}: { 
  children: React.ReactNode
  requiredRole: string 
}) {
  const user = useCurrentUser()
  
  if (!user || user.role !== requiredRole) {
    return <div>Access denied</div>
  }
  
  return <>{children}</>
}

// Check permissions in API routes
export async function POST(request: Request) {
  const supabase = await createClient()
  const { data: { user } } = await supabase.auth.getUser()
  
  if (!user) {
    return Response.json({ error: 'Unauthorized' }, { status: 401 })
  }
  
  // Check user role
  if (user.user_metadata?.role !== 'admin') {
    return Response.json({ error: 'Forbidden' }, { status: 403 })
  }
  
  // Proceed with request
}

Deployment Issues

Build Failures

Issue: Production build fails

Symptoms:

  • Build errors in CI/CD
  • TypeScript errors

Solutions:

# Test build locally
npm run build

# Check for TypeScript errors
npx tsc --noEmit

# Check for ESLint errors
npm run lint

# Check for unused dependencies
npx depcheck

# Fix common issues
npm install --save-dev @types/node @types/react @types/react-dom

Environment Variables

Issue: Environment variables not available in production

Symptoms:

  • Configuration errors in production
  • API connections failing

Solutions:

# Vercel: Set environment variables in dashboard
vercel env add NEXT_PUBLIC_SUPABASE_URL
vercel env add SUPABASE_SERVICE_ROLE_KEY

# Check environment variables
vercel env ls

# Pull environment variables locally
vercel env pull .env.local

SSL/HTTPS Issues

Issue: Mixed content warnings

Symptoms:

  • HTTPS warnings
  • Blocked content

Solutions:

// Ensure all URLs use HTTPS
const apiUrl = process.env.NODE_ENV === 'production' 
  ? 'https://api.example.com'
  : 'http://localhost:3000'

// Update Supabase URL to use HTTPS
NEXT_PUBLIC_SUPABASE_URL=https://your-project.supabase.co

Development Environment

IDE Issues

Issue: TypeScript IntelliSense not working

Symptoms:

  • No autocomplete
  • Missing type information

Solutions:

# Restart TypeScript server in VS Code
# Cmd/Ctrl + Shift + P -> "TypeScript: Restart TS Server"

# Check TypeScript configuration
{
  "compilerOptions": {
    "target": "es5",
    "lib": ["dom", "dom.iterable", "es6"],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve",
    "incremental": true,
    "plugins": [
      {
        "name": "next"
      }
    ],
    "paths": {
      "@/*": ["./src/*"]
    }
  }
}

Hot Reload Issues

Issue: Hot reload not working

Symptoms:

  • Changes not reflected
  • Page requires manual refresh

Solutions:

# Check if files are being watched
npm run dev -- --verbose

# Clear Next.js cache
rm -rf .next

# Check file system watching limits (Linux)
echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf
sudo sysctl -p

# Use polling (if file watching fails)
npm run dev -- --turbo

Debugging Tools

Browser Developer Tools

Network Tab

  • Monitor API requests and responses
  • Check for failed requests
  • Analyze request/response headers
  • Measure loading times

Console

  • View error messages and warnings
  • Test JavaScript code
  • Monitor performance metrics
  • Debug React components

Performance Tab

  • Analyze page load performance
  • Identify performance bottlenecks
  • Monitor memory usage
  • Profile JavaScript execution

React Developer Tools

# Install React DevTools browser extension
# Chrome: https://chrome.google.com/webstore/detail/react-developer-tools/fmkadmapgofadopljbjfkapdkoienihi
# Firefox: https://addons.mozilla.org/en-US/firefox/addon/react-devtools/

# Debug React components
console.log(React.version) // Check React version

Database Debugging

-- Enable query logging
ALTER SYSTEM SET log_statement = 'all';
SELECT pg_reload_conf();

-- Monitor active queries
SELECT 
  pid,
  now() - pg_stat_activity.query_start AS duration,
  query 
FROM pg_stat_activity 
WHERE state = 'active';

-- Check locks
SELECT 
  blocked_locks.pid AS blocked_pid,
  blocked_activity.usename AS blocked_user,
  blocking_locks.pid AS blocking_pid,
  blocking_activity.usename AS blocking_user,
  blocked_activity.query AS blocked_statement,
  blocking_activity.query AS current_statement_in_blocking_process
FROM pg_catalog.pg_locks blocked_locks
JOIN pg_catalog.pg_stat_activity blocked_activity ON blocked_activity.pid = blocked_locks.pid
JOIN pg_catalog.pg_locks blocking_locks ON blocking_locks.locktype = blocked_locks.locktype
JOIN pg_catalog.pg_stat_activity blocking_activity ON blocking_activity.pid = blocking_locks.pid
WHERE NOT blocked_locks.granted;

Application Logging

// lib/logger.ts
export const logger = {
  debug: (message: string, data?: any) => {
    if (process.env.NODE_ENV === 'development') {
      console.log(`[DEBUG] ${message}`, data)
    }
  },
  
  info: (message: string, data?: any) => {
    console.log(`[INFO] ${message}`, data)
  },
  
  warn: (message: string, data?: any) => {
    console.warn(`[WARN] ${message}`, data)
  },
  
  error: (message: string, error?: Error, data?: any) => {
    console.error(`[ERROR] ${message}`, {
      error: error?.message,
      stack: error?.stack,
      ...data
    })
  }
}

// Usage
logger.debug('User authenticated', { userId: user.id })
logger.error('Database query failed', error, { query: 'SELECT * FROM products' })

Support Resources

Documentation

Community Support

Professional Support

Reporting Issues

When reporting issues, please include:

  1. Environment Information

    • Node.js version
    • Browser version
    • Operating system
    • Package versions
  2. Error Details

    • Complete error message
    • Stack trace
    • Steps to reproduce
  3. Context

    • What you were trying to do
    • What you expected to happen
    • What actually happened
  4. Code Examples

    • Minimal reproducible example
    • Relevant configuration files
    • Environment variables (sanitized)

This troubleshooting guide covers common issues and their solutions. For additional help, refer to the official documentation or contact support.