Skip to main content
Back to Elite Events

Elite Events Documentation

Technical documentation, guides, and API references for the Elite Events platform.

Architecture/Troubleshooting

Troubleshooting Guide

Common issues and their solutions for Elite Events development.


Table of Contents


Setup & Installation

Port 3000 Already in Use

Symptoms:

Error: listen EADDRINUSE: address already in use :::3000

Solutions:

Windows:

# Find process using port 3000
netstat -ano | findstr :3000

# Kill the process (replace PID with actual process ID)
taskkill /PID <PID> /F

Mac/Linux:

# Find and kill process
lsof -ti:3000 | xargs kill

# Or use different port
PORT=3001 npm run dev

Module Not Found Errors

Symptoms:

Error: Cannot find module '@/lib/utils'

Solutions:

  1. Clear cache and reinstall:

    rm -rf node_modules package-lock.json
    npm install
    
  2. Verify path aliases in tsconfig.json:

    {
      "compilerOptions": {
        "paths": {
          "@/*": ["./src/*"]
        }
      }
    }
    
  3. Restart dev server:

    # Stop server (Ctrl+C)
    npm run dev
    

Environment Variables Not Loading

Symptoms:

  • Database connection fails
  • "NEXTAUTH_SECRET not set" error
  • Features not working

Solutions:

  1. Verify .env exists in project root (not in src/)

  2. Check variable names match exactly:

    DATABASE_URL="mysql://..."
    NEXTAUTH_SECRET="..."
    NEXTAUTH_URL="http://localhost:3000"
    
  3. Restart dev server after changing .env:

    # Stop (Ctrl+C) and restart
    npm run dev
    
  4. Verify .env is not in .gitignore... wait, it SHOULD be in .gitignore! Never commit .env.


Database Issues

Connection Refused / Can't Connect

Symptoms:

Error: Can't reach database server at `localhost:3306`

Solutions:

  1. Verify MySQL is running:

    # Windows
    net start MySQL80
    
    # Mac
    brew services start mysql
    
    # Linux
    sudo systemctl start mysql
    
  2. Check DATABASE_URL format:

    mysql://USERNAME:PASSWORD@HOST:PORT/DATABASE_NAME
    
  3. Test connection:

    npx prisma db push
    
  4. Verify credentials are correct


Prisma Client Out of Sync

Symptoms:

Error: Prisma Client is not generated

Solutions:

# Generate Prisma Client
npx prisma generate

# If still failing, reinstall
npm install @prisma/client
npx prisma generate

Migration Errors (P3018)

Symptoms:

Error code: P3018
Migration `XXX` failed to apply cleanly to the shadow database

Solutions:

  1. Reset database (⚠️ deletes all data):

    npx prisma migrate reset --force
    
  2. Re-seed database:

    npx prisma db seed
    
  3. Alternative: Push schema without migration:

    npx prisma db push
    

See Also: docs/issues/ISSUE_2025_11_20_MIGRATION_P3018.md


Seed Script Failing

Symptoms:

Error running seed command

Solutions:

  1. Check database is empty or reset it:

    npx prisma migrate reset --force
    
  2. Run seed manually:

    npx tsx prisma/seed.ts
    
  3. Check for unique constraint violations in seed data

  4. Verify relationships match schema


Authentication & Session

"Unauthorized" on All Requests

Symptoms:

  • All protected endpoints return 401
  • Can't access cart/wishlist
  • Admin panel redirects to signin

Solutions:

  1. Verify you're logged in:

    • Check header shows your name
    • Open DevTools → Application → Cookies
    • Look for next-auth.session-token
  2. Clear cookies and re-login:

    • DevTools → Application → Cookies → Clear All
    • Sign in again
  3. Verify NEXTAUTH_SECRET is set in .env

  4. Restart dev server


Header Not Showing Username

Symptoms:

  • Logged in but header still shows "Sign In"
  • Session seems active but UI doesn't update

Solutions:

  1. Hard refresh the page (Ctrl+F5 or Cmd+Shift+R)

  2. Check session:

    # Visit in browser
    http://localhost:3000/api/auth/session
    
  3. Verify NextAuth configuration in src/app/api/auth/[...nextauth]/route.ts

  4. Check browser console for errors


"Email Already Registered"

Symptoms:

  • Can't create account with email

Solutions:

  1. Use different email

  2. Or reset database:

    npx prisma migrate reset --force
    npx prisma db seed
    
  3. Or delete specific user in Prisma Studio:

    npx prisma studio
    # Navigate to User table, delete user
    

Invalid Credentials on Login

Symptoms:

  • Correct email/password but login fails

Solutions:

  1. Verify user exists:

    npx prisma studio
    # Check User table
    
  2. Check password is hashed (should start with $2b$)

  3. Re-seed database if demo users missing:

    npx prisma db seed
    
  4. Try demo credentials:

    • demo@dcsuniverse.com / demo123
    • admin@dcsuniverse.com / admin123

API Errors

404 Not Found on API Routes

Symptoms:

GET /api/products → 404

Solutions:

  1. Verify route file exists:

    • Check src/app/api/products/route.ts
  2. Verify export names:

    // Correct
    export async function GET(req: NextRequest) { ... }
    
    // Wrong
    export default function handler() { ... }
    
  3. Restart dev server

  4. Check file structure matches route


CORS Errors

Symptoms:

Access to fetch at 'http://localhost:3000/api/...' from origin 'http://localhost:3001' has been blocked by CORS

Solutions:

  1. Use same origin for frontend and API

  2. Or add CORS headers in API route:

    const response = NextResponse.json(data);
    response.headers.set('Access-Control-Allow-Origin', '*');
    return response;
    

Zod Validation Errors

Symptoms:

ZodError: Invalid input

Solutions:

  1. Check request body matches schema

  2. Use .safeParse() for better error messages:

    const result = schema.safeParse(data);
    if (!result.success) {
      console.log(result.error);
    }
    
  3. Verify field types (string vs number, etc.)


Build & Deployment

Build Failing with Type Errors

Symptoms:

npm run build
✗ Type error: ...

Solutions:

  1. Run type check:

    npm run type-check
    
  2. Fix errors one by one

  3. Common fixes:

    • Add missing type imports
    • Fix any types
    • Add ! for non-null assertions (use cautiously)

See Also: Resolved in commit 037ef58


Lint Errors on Build

Symptoms:

Error: ESLint errors found

Solutions:

  1. Run lint:

    npm run lint
    
  2. Auto-fix where possible:

    npm run lint -- --fix
    
  3. Fix remaining errors manually

See Also: Resolved in commit 2258179


Out of Memory During Build

Symptoms:

FATAL ERROR: Reached heap limit Allocation failed

Solutions:

  1. Increase Node memory:

    NODE_OPTIONS="--max-old-space-size=4096" npm run build
    
  2. Or in package.json:

    {
      "scripts": {
        "build": "NODE_OPTIONS='--max-old-space-size=4096' next build"
      }
    }
    

Testing

Tests Failing After Code Changes

Symptoms:

  • Tests that previously passed now fail

Solutions:

  1. Update snapshots if UI changed:

    npm test -- -u
    
  2. Check mocks are still valid

  3. Verify test data matches new schema

  4. Run specific test to debug:

    npm test -- cart-slice.test.ts
    

Test Timeout Errors

Symptoms:

Timeout - Async callback was not invoked within the 5000 ms timeout

Solutions:

  1. Increase timeout:

    it('slow test', async () => {
      // ...
    }, 10000); // 10 second timeout
    
  2. Or globally:

    jest.setTimeout(10000);
    
  3. Fix async/await issues:

    // Make sure to await
    await waitFor(() => {
      expect(element).toBeInTheDocument();
    });
    

Mock Not Working

Symptoms:

  • Real API called instead of mock
  • Mock data not returned

Solutions:

  1. Verify mock is defined before test:

    jest.mock('@/lib/api');
    
  2. Check mock setup:

    const mockFn = jest.fn();
    mockFn.mockResolvedValue({ data: [...] });
    
  3. Clear mocks between tests:

    afterEach(() => {
      jest.clearAllMocks();
    });
    

Performance

Slow Page Load

Symptoms:

  • Pages take >2 seconds to load
  • Slow API responses

Solutions:

  1. Check database queries:

    • Add indexes to frequently queried fields
    • Use select to limit returned fields
    • Avoid N+1 queries
  2. Enable caching:

    • Use Next.js caching
    • Consider Redis (Plan 6)
  3. Optimize images:

    • Use next/image component
    • Serve WebP format
  4. Check network tab in DevTools for slow requests


High Memory Usage

Symptoms:

  • Dev server crashes
  • Slow performance

Solutions:

  1. Restart dev server periodically

  2. Close unused tabs/programs

  3. Increase Node memory:

    NODE_OPTIONS="--max-old-space-size=4096" npm run dev
    

Admin Panel

Admin Menu Not Showing

Symptoms:

  • Logged in as admin but no "Admin" menu

Solutions:

  1. Verify user role in database:

    npx prisma studio
    # Check User table, role should be "ADMIN"
    
  2. Update role manually:

    UPDATE users SET role = 'ADMIN' WHERE email = 'your@email.com';
    
  3. Logout and login again to refresh session

  4. Check session includes role:

    http://localhost:3000/api/auth/session
    

See Also: docs/ADMIN_QUICK_START.md


Can't Access Admin Pages

Symptoms:

  • Redirected when accessing /admin/*

Solutions:

  1. Verify you're logged in

  2. Verify admin role (see above)

  3. Check middleware in src/middleware.ts

  4. Clear browser cache and try again


Images & File Upload

Images Not Uploading

Symptoms:

  • Upload fails silently
  • Error message shows

Solutions:

  1. Check file size (max 10MB):

    if (file.size > 10 * 1024 * 1024) {
      throw new Error('File too large');
    }
    
  2. Verify file type:

    const validTypes = ['image/jpeg', 'image/png', 'image/webp'];
    if (!validTypes.includes(file.type)) {
      throw new Error('Invalid file type');
    }
    
  3. Check directory exists and is writable:

    mkdir -p public/images/products
    
  4. Check Sharp is installed:

    npm install sharp
    

See Also: docs/issues/ISSUE_2025_11_20_IMAGE_FIX.md


Images Not Displaying

Symptoms:

  • Broken image icons
  • 404 on image URLs

Solutions:

  1. Verify image path:

    /images/products/product-1-bg-1.webp
    
  2. Check file exists in public/images/products/

  3. Use correct Next.js Image component:

    import Image from 'next/image';
    
    <Image
      src="/images/products/product-1-bg-1.webp"
      alt="Product"
      width={800}
      height={800}
    />
    
  4. Check browser console for errors


Getting More Help

Debug Steps

  1. Check browser console for JavaScript errors
  2. Check terminal for server errors
  3. Check Network tab in DevTools
  4. Enable verbose logging
  5. Search error message in issues docs

Useful Commands

# View logs
npm run dev

# Database GUI
npx prisma studio

# Reset everything
npx prisma migrate reset --force
npm install
npm run dev

# Run tests
npm test -- --verbose

# Type check
npm run type-check

# Lint
npm run lint

Documentation

Still Stuck?

  1. Check existing issues in docs/issues/
  2. Search error message in documentation
  3. Create detailed issue report
  4. Include error messages, steps to reproduce, and environment details

Known Issues

See docs/issues/README.md for detailed documentation of resolved issues.

Recently Resolved

  • ✅ Nested buttons accessibility (ISSUE_001)
  • ✅ Search API Prisma errors (ISSUE_003)
  • ✅ Redux serialization (ISSUE_004)
  • ✅ Migration P3018 error
  • ✅ Inventory field missing
  • ✅ TypeScript type errors (all fixed)
  • ✅ ESLint violations (all fixed)

TypeScript Errors

Property Does Not Exist on Type

Symptoms:

Error: Property 'xxx' does not exist on type 'yyy'

Solutions:

  1. Check if field exists in Prisma schema:

    npx prisma studio
    # Verify schema matches your code
    
  2. Regenerate Prisma client:

    npx prisma generate
    
  3. Add type assertion if you're sure it exists:

    (item as { xxx: string }).xxx
    
  4. Define proper types instead of using any


Type 'undefined' Is Not Assignable

Symptoms:

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

Solutions:

  1. Add optional chaining:

    const value = item?.property ?? 'default';
    
  2. Add nullish coalescing:

    const value = item.property ?? '';
    
  3. Check for undefined first:

    if (item.property) {
      // use item.property
    }
    

Cannot Find Module 'next/server' in Tests

Symptoms:

Cannot find module 'next/server' from 'src/lib/...'

Solutions:

This occurs when importing middleware that uses NextRequest/NextResponse in Jest:

  1. Don't re-export middleware from main index files

  2. Import directly in API routes:

    // Don't do this in index.ts that's used by tests
    export * from './middleware';
    
    // Instead, import directly in API routes
    import { withValidation } from '@/lib/validation/middleware';
    
  3. Mock next/server in tests if needed:

    jest.mock('next/server', () => ({
      NextRequest: jest.fn(),
      NextResponse: {
        json: jest.fn((data) => ({ data })),
      },
    }));
    

Storybook Issues

Stories Not Loading

Symptoms:

  • Stories show "Loading..." forever
  • Stories error with "Cannot find module"

Solutions:

  1. Restart Storybook:

    npm run storybook
    
  2. Clear Storybook cache:

    rm -rf node_modules/.cache/storybook
    npm run storybook
    
  3. Check story file naming (must end in .stories.tsx):

    src/components/Button/Button.stories.tsx
    
  4. Verify component exports match story imports


Storybook Addon Errors

Symptoms:

Error: Cannot find module '@storybook/addon-xxx'

Solutions:

# Reinstall dependencies
rm -rf node_modules package-lock.json
npm install

# Or install specific addon
npm install @storybook/addon-xxx --save-dev

Redux Issues

State Not Updating

Symptoms:

  • Dispatch action but UI doesn't update
  • Selector returns stale data

Solutions:

  1. Check you're using typed hooks:

    // Use these, not useSelector/useDispatch
    import { useAppSelector, useAppDispatch } from '@/redux';
    
  2. Verify reducer updates correctly:

    // Use Immer properly (RTK handles this)
    state.items.push(newItem); // OK in RTK
    
  3. Check selector memoization:

    // Use createSelector for derived data
    export const selectTotal = createSelector(
      [selectItems],
      (items) => items.reduce((sum, i) => sum + i.price, 0)
    );
    

Redux State Serialization Warning

Symptoms:

A non-serializable value was detected in an action

Solutions:

  1. Don't store non-serializable data (functions, Date objects):

    // Bad
    { timestamp: new Date() }
    
    // Good
    { timestamp: Date.now() }
    
  2. Configure serializable check in store:

    middleware: (getDefaultMiddleware) =>
      getDefaultMiddleware({
        serializableCheck: {
          ignoredActions: ['persist/PERSIST'],
          ignoredPaths: ['someReducer.callbacks'],
        },
      }),
    

Next.js App Router Issues

Server/Client Component Mismatch

Symptoms:

Error: useState can only be used in a Client Component

Solutions:

  1. Add 'use client' directive:

    'use client';
    
    import { useState } from 'react';
    
  2. Separate client logic into child components

  3. Check imports - Server Components can't import Client Components that use hooks


Dynamic Rendering Issues

Symptoms:

  • Data is stale
  • User-specific data not showing

Solutions:

  1. Add dynamic export:

    export const dynamic = 'force-dynamic';
    
  2. Use cookies/headers which automatically make route dynamic

  3. For API routes with auth:

    export const dynamic = 'force-dynamic';
    export const revalidate = 0;
    

Cache Not Invalidating

Symptoms:

  • Updated data not showing
  • Old cached responses

Solutions:

  1. Use revalidateTag:

    import { revalidateTag } from 'next/cache';
    
    await revalidateTag('products', 'layout');
    
  2. Use revalidatePath:

    import { revalidatePath } from 'next/cache';
    
    revalidatePath('/products');
    
  3. Hard refresh the page (Ctrl+Shift+R)


E2E Testing (Playwright)

Tests Timing Out

Symptoms:

Test timeout of 30000ms exceeded

Solutions:

  1. Increase timeout in test:

    test('slow test', async ({ page }) => {
      test.setTimeout(60000);
      // ...
    });
    
  2. Wait for network idle:

    await page.goto('/', { waitUntil: 'networkidle' });
    
  3. Check dev server is running:

    npm run dev
    

Element Not Found

Symptoms:

Waiting for selector "text=Button"

Solutions:

  1. Use better selectors:

    // By role (recommended)
    await page.getByRole('button', { name: 'Submit' });
    
    // By test ID
    await page.getByTestId('submit-button');
    
  2. Wait for element:

    await expect(page.getByText('Loaded')).toBeVisible();
    
  3. Check element renders (open browser with headed mode):

    npx playwright test --headed
    

Production Deployment

Service Unavailable (503)

Symptoms:

  • Site shows 503 error
  • Intermittent failures

Solutions:

  1. Check server logs:

    ssh ubuntu@your-server
    pm2 logs
    
  2. Restart application:

    pm2 restart all
    
  3. Check disk space:

    df -h
    
  4. Check memory:

    free -m
    

See Also: docs/issues/resolved/ISSUE_2025_12_12_DEPLOYMENT_SERVICE_UNAVAILABLE.md


Database Connection Pool Exhausted

Symptoms:

Can't add new command when connection pool is exhausted

Solutions:

  1. Add connection limit in DATABASE_URL:

    mysql://user:pass@host:3306/db?connection_limit=10
    
  2. Use Prisma connection pooling:

    const prisma = new PrismaClient({
      datasources: {
        db: {
          url: process.env.DATABASE_URL,
        },
      },
    });
    
  3. Check for connection leaks - ensure Prisma disconnects:

    // In API routes, use global client
    import { prisma } from '@/lib/prisma';
    

Last Updated: December 27, 2025

Note: If you encounter an issue not listed here, please document it following the template in docs/templates/issue-template.md.

Documentation | Elite Events | Philip Rehberger