Common Issues

Frequently encountered problems and their quick solutions for immediate troubleshooting.

Common Issues

This section covers the most frequently encountered problems and their immediate solutions. These issues typically affect users during initial setup or daily development activities.

Application Won't Start

Issue: npm run dev fails to start

Symptoms:

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

Quick 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 and reinstall
rm -rf .next
rm -rf node_modules
npm install

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

Detailed Troubleshooting:

# Check Node.js version compatibility
node --version  # Should be 18.0 or higher

# Clear all caches
npm cache clean --force
rm -rf .next
rm -rf node_modules/.cache

# Reinstall dependencies
rm package-lock.json
npm install

# Check for global package conflicts
npm list -g --depth=0

# Verbose startup for debugging
npm run dev -- --verbose

Issue: TypeScript compilation errors

Symptoms:

  • Type errors preventing compilation
  • Module resolution failures
  • Missing type definitions
  • Conflicting type declarations

Solutions:

# Check TypeScript configuration
npx tsc --noEmit

# Update TypeScript and related packages
npm update typescript @types/node @types/react @types/react-dom

# 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
rm tsconfig.tsbuildinfo

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

Common TypeScript Fixes:

// Fix: Cannot find module errors
// Add to tsconfig.json
{
  "compilerOptions": {
    "moduleResolution": "node",
    "baseUrl": ".",
    "paths": {
      "@/*": ["./src/*", "./app/*", "./components/*", "./lib/*"]
    }
  }
}

// Fix: JSX element implicitly has type 'any'
// Add to tsconfig.json
{
  "compilerOptions": {
    "jsx": "preserve",
    "lib": ["dom", "dom.iterable", "es6"]
  }
}

// Fix: Property does not exist on type errors
interface CustomUser {
  id: string
  email: string
  role?: string
  profile?: {
    name: string
    avatar?: string
  }
}

// Type guards for runtime safety
function isValidUser(user: any): user is CustomUser {
  return user && typeof user.id === 'string' && typeof user.email === 'string'
}

Environment Configuration Issues

Issue: Environment variables not loading

Symptoms:

  • Undefined environment variables in runtime
  • Configuration errors
  • API connection failures
  • Build-time variable issues

Solutions:

# Check .env files exist and are named correctly
ls -la .env*

# Verify environment variables are loaded
echo $NEXT_PUBLIC_SUPABASE_URL
echo $SUPABASE_SERVICE_ROLE_KEY

# Check variable naming (client-side variables need NEXT_PUBLIC_ prefix)

Environment File Structure:

# .env.local (local development - highest priority)
NEXT_PUBLIC_SUPABASE_URL=https://your-project.supabase.co
NEXT_PUBLIC_SUPABASE_ANON_KEY=your-anon-key
SUPABASE_SERVICE_ROLE_KEY=your-service-role-key

# .env.production (production build)
NEXT_PUBLIC_SUPABASE_URL=https://your-prod-project.supabase.co
NEXT_PUBLIC_SUPABASE_ANON_KEY=your-prod-anon-key

# .env.example (template for team)
NEXT_PUBLIC_SUPABASE_URL=your_supabase_url_here
NEXT_PUBLIC_SUPABASE_ANON_KEY=your_supabase_anon_key_here
SUPABASE_SERVICE_ROLE_KEY=your_service_role_key_here

Environment Variable Debugging:

// Debug environment variables
console.log('Environment check:', {
  NODE_ENV: process.env.NODE_ENV,
  SUPABASE_URL: process.env.NEXT_PUBLIC_SUPABASE_URL ? '✓ Set' : '✗ Missing',
  SUPABASE_ANON_KEY: process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY ? '✓ Set' : '✗ Missing',
  SERVICE_ROLE_KEY: process.env.SUPABASE_SERVICE_ROLE_KEY ? '✓ Set' : '✗ Missing'
})

// Runtime environment validation
function validateEnvironment() {
  const required = [
    'NEXT_PUBLIC_SUPABASE_URL',
    'NEXT_PUBLIC_SUPABASE_ANON_KEY'
  ]
  
  const serverRequired = [
    'SUPABASE_SERVICE_ROLE_KEY'
  ]
  
  const missing = required.filter(key => !process.env[key])
  
  if (missing.length > 0) {
    throw new Error(`Missing required environment variables: ${missing.join(', ')}`)
  }
  
  // Server-side only checks
  if (typeof window === 'undefined') {
    const serverMissing = serverRequired.filter(key => !process.env[key])
    if (serverMissing.length > 0) {
      console.warn(`Missing server environment variables: ${serverMissing.join(', ')}`)
    }
  }
}

Issue: Supabase connection fails

Symptoms:

  • Database connection errors
  • Authentication failures
  • API request timeouts
  • Invalid project URL errors

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!
)

// Connection test function
async function testSupabaseConnection() {
  try {
    console.log('Testing Supabase connection...')
    
    // Test basic connectivity
    const { data, error } = await supabase
      .from('products')
      .select('count')
      .limit(1)
    
    if (error) {
      console.error('Supabase query error:', error)
      return false
    }
    
    console.log('✓ Supabase connection successful')
    return true
    
  } catch (error) {
    console.error('✗ Supabase connection failed:', error)
    return false
  }
}

// Test authentication
async function testSupabaseAuth() {
  try {
    const { data: { user }, error } = await supabase.auth.getUser()
    
    if (error) {
      console.log('No authenticated user (expected if not logged in)')
    } else {
      console.log('Current user:', user?.email || 'Anonymous')
    }
    
    return true
  } catch (error) {
    console.error('Auth test failed:', error)
    return false
  }
}

// Comprehensive connection test
export async function diagnoseSupabase() {
  console.log('🔍 Supabase Diagnostics')
  console.log('========================')
  
  // Check environment variables
  const url = process.env.NEXT_PUBLIC_SUPABASE_URL
  const anonKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY
  
  console.log('Environment Variables:')
  console.log(`  URL: ${url ? '✓ Set' : '✗ Missing'}`)
  console.log(`  Anon Key: ${anonKey ? '✓ Set' : '✗ Missing'}`)
  
  if (!url || !anonKey) {
    console.error('❌ Missing required Supabase environment variables')
    return false
  }
  
  // Validate URL format
  try {
    new URL(url)
    console.log('  URL Format: ✓ Valid')
  } catch {
    console.error('  URL Format: ✗ Invalid')
    return false
  }
  
  // Test connection
  const connectionOk = await testSupabaseConnection()
  const authOk = await testSupabaseAuth()
  
  console.log('\nResults:')
  console.log(`  Connection: ${connectionOk ? '✓' : '✗'}`)
  console.log(`  Auth: ${authOk ? '✓' : '✗'}`)
  
  return connectionOk && authOk
}

Module Resolution Issues

Issue: "Cannot resolve module" errors

Symptoms:

  • Import statements failing
  • Path resolution errors
  • Missing dependency errors
  • Alias resolution failures

Solutions:

// Check tsconfig.json paths configuration
{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@/*": ["./src/*"],
      "@/components/*": ["./components/*"],
      "@/lib/*": ["./lib/*"],
      "@/types/*": ["./types/*"]
    }
  }
}

// Check Next.js configuration for path aliases
// next.config.mjs
/** @type {import('next').NextConfig} */
const nextConfig = {
  webpack: (config) => {
    config.resolve.alias = {
      ...config.resolve.alias,
      '@': path.resolve(__dirname, './src'),
      '@/components': path.resolve(__dirname, './components'),
      '@/lib': path.resolve(__dirname, './lib'),
    }
    return config
  }
}

export default nextConfig

Common Module Fixes:

# Install missing peer dependencies
npm ls # Check for missing dependencies
npm install @types/react @types/react-dom

# Fix specific module issues
npm install --save-dev @types/node

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

# Check for duplicate dependencies
npm ls --depth=0 | grep -E "UNMET|invalid"

Build and Compilation Issues

Issue: Build fails with memory errors

Symptoms:

  • Out of memory errors during build
  • Build process hanging
  • Webpack compilation failures

Solutions:

# Increase Node.js memory limit
export NODE_OPTIONS="--max-old-space-size=4096"
npm run build

# Or set in package.json
{
  "scripts": {
    "build": "NODE_OPTIONS='--max-old-space-size=4096' next build"
  }
}

# Optimize build configuration
# next.config.mjs
const nextConfig = {
  // Reduce memory usage
  experimental: {
    // Reduce bundle size
    optimizeCss: true,
    // Enable SWC minification
    swcMinify: true
  },
  
  // Webpack optimizations
  webpack: (config, { dev }) => {
    if (!dev) {
      // Production optimizations
      config.optimization.splitChunks = {
        chunks: 'all',
        cacheGroups: {
          vendor: {
            test: /[\\/]node_modules[\\/]/,
            name: 'vendors',
            chunks: 'all',
          }
        }
      }
    }
    return config
  }
}

Issue: Linting and formatting errors

Symptoms:

  • ESLint errors blocking builds
  • Formatting inconsistencies
  • Pre-commit hooks failing

Solutions:

# Fix ESLint errors automatically
npm run lint -- --fix

# Check specific files
npx eslint . --ext .ts,.tsx,.js,.jsx

# Fix Prettier formatting
npx prettier --write .

# Check for formatting issues
npx prettier --check .

# Setup pre-commit hooks
npm install --save-dev husky lint-staged

# package.json
{
  "husky": {
    "hooks": {
      "pre-commit": "lint-staged"
    }
  },
  "lint-staged": {
    "*.{ts,tsx,js,jsx}": [
      "eslint --fix",
      "prettier --write"
    ]
  }
}

Quick Diagnostic Commands

System Information

# Node.js and npm versions
node --version
npm --version

# Check global packages
npm list -g --depth=0

# Check project dependencies
npm list --depth=0

# Check for outdated packages
npm outdated

# Check for security vulnerabilities
npm audit

# System information
uname -a  # macOS/Linux
systeminfo  # Windows

Development Server Health Check

# Check port availability
netstat -tulpn | grep :3000  # Linux
lsof -i :3000  # macOS
netstat -ano | findstr :3000  # Windows

# Check process information
ps aux | grep node  # macOS/Linux
tasklist | findstr node  # Windows

# Monitor resource usage
top -p $(pgrep node)  # Linux
htop  # Linux (if installed)
Activity Monitor  # macOS (GUI)
Task Manager  # Windows (GUI)

Quick Reset Commands

# Complete project reset
rm -rf node_modules
rm -rf .next
rm package-lock.json
npm cache clean --force
npm install

# Next.js specific reset
rm -rf .next
npm run dev

# TypeScript reset
rm tsconfig.tsbuildinfo
npx tsc --build --clean

Emergency Fixes

When everything is broken

#!/bin/bash
# emergency-reset.sh

echo "🚨 Emergency Reset Starting..."

# Stop all Node processes
pkill -f node || true

# Clear all caches
echo "Clearing caches..."
npm cache clean --force
rm -rf node_modules/.cache
rm -rf .next
rm -rf dist
rm -rf build

# Remove lock files
echo "Removing lock files..."
rm -f package-lock.json
rm -f yarn.lock
rm -f pnpm-lock.yaml

# Remove node_modules
echo "Removing node_modules..."
rm -rf node_modules

# Reinstall dependencies
echo "Reinstalling dependencies..."
npm install

# Clear TypeScript cache
echo "Clearing TypeScript cache..."
rm -f tsconfig.tsbuildinfo

echo "✅ Emergency reset complete!"
echo "Try running: npm run dev"

Preventive Measures

Regular Maintenance

# Weekly maintenance script
#!/bin/bash
# weekly-maintenance.sh

echo "🔧 Weekly Maintenance Starting..."

# Update dependencies
npm update

# Security audit
npm audit fix

# Clear caches
npm cache clean --force

# Check for unused dependencies
npx depcheck

# Check bundle size
npm run build
npx bundlesize

echo "✅ Weekly maintenance complete!"

Health Check Function

// lib/health-check.ts
export async function healthCheck() {
  const checks = {
    environment: checkEnvironmentVariables(),
    database: await checkDatabaseConnection(),
    auth: await checkAuthenticationService(),
    api: await checkApiEndpoints(),
    dependencies: checkDependencies()
  }
  
  const passed = Object.values(checks).every(check => check.status === 'ok')
  
  return {
    status: passed ? 'healthy' : 'unhealthy',
    checks,
    timestamp: new Date().toISOString()
  }
}

function checkEnvironmentVariables() {
  const required = ['NEXT_PUBLIC_SUPABASE_URL', 'NEXT_PUBLIC_SUPABASE_ANON_KEY']
  const missing = required.filter(key => !process.env[key])
  
  return {
    status: missing.length === 0 ? 'ok' : 'error',
    message: missing.length === 0 ? 'All required variables set' : `Missing: ${missing.join(', ')}`
  }
}

async function checkDatabaseConnection() {
  try {
    const { data, error } = await supabase
      .from('products')
      .select('count')
      .limit(1)
    
    return {
      status: error ? 'error' : 'ok',
      message: error ? error.message : 'Database connection successful'
    }
  } catch (error) {
    return {
      status: 'error',
      message: `Database connection failed: ${error.message}`
    }
  }
}

This comprehensive common issues guide provides immediate solutions for the most frequent problems developers encounter, along with preventive measures and diagnostic tools.