GameCraftGameCraft

Troubleshooting

Common issues and how to fix them - get unstuck fast

Troubleshooting

Stuck? This guide covers common issues and their solutions.

Can't find your issue? Search GitHub Issues or ask in Discussions.


Installation Issues

"Module not found" after pnpm install

Symptoms: Import errors, TypeScript can't find modules

Solution:

# Clear everything and reinstall
rm -rf node_modules .next pnpm-lock.yaml
pnpm install

# Restart dev server
pnpm dev

"pnpm not found"

Solution: Install pnpm globally

npm install -g pnpm

# Or use Corepack (recommended)
corepack enable
corepack prepare pnpm@latest --activate

"Node version too old"

Symptoms: Build fails with syntax errors

Solution: Upgrade to Node.js 18+

# Check current version
node -v

# Install latest LTS (using nvm)
nvm install --lts
nvm use --lts

Database Issues

"Database connection failed"

Check these:

  1. Is PG_DATABASE_URL set?

    echo $PG_DATABASE_URL
    # Should show: postgresql://...
  2. Is the format correct?

    # Correct format:
    postgresql://user:password@host:5432/database
  3. Can you connect manually?

    psql $PG_DATABASE_URL
    # Should connect without errors
  4. Is database running?

    # For local Postgres
    brew services list  # macOS
    systemctl status postgresql  # Linux

"relation does not exist"

Cause: Tables not created

Solution: Run migrations

pnpm db:migrate

"Too many clients" (Vercel/Serverless)

Cause: Not using connection pooling

Solution: Use pooled connection string

Neon - Change port from 5432 → 6543:

# Before
postgresql://user:pass@host:5432/db

# After (pooled)
postgresql://user:pass@host:6543/db

Supabase - Use "Connection pooling" string from dashboard


Build & TypeScript Errors

"Type error: Cannot find module '~/...'"

Cause: Path aliases not configured

Solution: Check tsconfig.json:

{
  "compilerOptions": {
    "paths": {
      "~/*": ["./src/*"]
    }
  }
}

Restart your editor after changing!

"Property 'X' does not exist on type 'Y'"

Common causes:

  1. Typo - Check spelling
  2. Missing type - Run pnpm db:generate after schema changes
  3. Outdated types - Restart TypeScript server (VS Code: Cmd+Shift+P → "Restart TS Server")

Build fails with "ReferenceError: X is not defined"

Cause: Using Node.js-only code in client components

Solution: Add 'use client' or move to API route

// ❌ Don't use in client components
import fs from 'fs';

// ✅ Move to API route or server component
// src/app/api/read-file/route.ts
import fs from 'fs';
export async function GET() { ... }

Authentication Issues

"Unauthorized" on protected routes

Check:

  1. Are you logged in?

    // In browser console
    authClient.getSession().then(console.log);
    // Should show session object, not null
  2. Is cookie being sent?

    • Open DevTools → Application → Cookies
    • Look for better-auth.session_token
    • Should have value, HttpOnly, Secure flags
  3. Is BETTER_AUTH_URL correct?

    # Development
    BETTER_AUTH_URL=http://localhost:3000
    
    # Production
    BETTER_AUTH_URL=https://yourapp.com

OAuth "Redirect URI mismatch"

Cause: Callback URL doesn't match OAuth app settings

Solution: Update OAuth app with exact URL

GitHub:

  • Callback URL: https://yourapp.com/api/auth/callback/github
  • Must match exactly (including https://)

Google:

  • Authorized redirect URI: https://yourapp.com/api/auth/callback/google

"Invalid session" after deployment

Cause: BETTER_AUTH_SECRET changed or missing

Solution:

  1. Set BETTER_AUTH_SECRET in production env vars
  2. Use different secret than development
  3. Generate new:
    openssl rand -base64 32

Dev Server Issues

"Port 3000 already in use"

Solution 1: Kill the process

# macOS/Linux
lsof -ti:3000 | xargs kill -9

# Or find and kill manually
lsof -i:3000
kill -9 <PID>

Solution 2: Use different port

pnpm dev -- --port 3001

Hot reload not working

Solutions:

  1. Clear .next cache

    rm -rf .next
    pnpm dev
  2. Check file watchers (Linux)

    # Increase limit
    echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf
    sudo sysctl -p
  3. Restart dev server

    # Kill server (Ctrl+C)
    # Start again
    pnpm dev

"EADDRINUSE: address already in use"

Same as "Port already in use" above.


tRPC Issues

"tRPC error: UNAUTHORIZED"

Cause: Protected procedure called without auth

Solution: Sign in first

// Check if logged in
const { data: session } = await authClient.getSession();
if (!session) {
  router.push('/login');
  return;
}

// Then call tRPC
const result = await trpc.protected.route.mutate(...);

"No QueryClient set, use QueryClientProvider"

Cause: tRPC client not wrapped in provider

Solution: Check src/app/layout.tsx:

import { TRPCProvider } from '~/lib/trpc/client';

export default function RootLayout({ children }) {
  return (
    <html>
      <body>
        <TRPCProvider>
          {children}
        </TRPCProvider>
      </body>
    </html>
  );
}

tRPC mutation not refetching query

Solution: Invalidate query after mutation

const utils = trpc.useUtils();

const createMutation = trpc.tasks.create.useMutation({
  onSuccess: () => {
    // Refetch tasks list
    utils.tasks.list.invalidate();
  },
});

Deployment Issues (Vercel)

Build succeeds locally but fails on Vercel

Common causes:

  1. Missing env vars - Add all required vars in Vercel dashboard
  2. Different Node version - Set in package.json:
    {
      "engines": {
        "node": ">=18.0.0"
      }
    }
  3. TypeScript errors - Run pnpm typecheck locally

"Cannot connect to database" after deploy

Check:

  1. PG_DATABASE_URL in Vercel env vars?

    • Go to Project Settings → Environment Variables
    • Add PG_DATABASE_URL for Production
  2. Using pooled connection?

    • Use port 6543 (Neon) or pooled string (Supabase)
  3. Database allows external connections?

    • Check firewall/security settings

OAuth works locally but not in production

Check:

  1. OAuth callback URL updated?

    • Should use production domain
    • Example: https://yourapp.com/api/auth/callback/github
  2. BETTER_AUTH_URL set to production?

    BETTER_AUTH_URL=https://yourapp.vercel.app
  3. OAuth secrets in Vercel env vars?

    • GITHUB_CLIENT_ID, GITHUB_CLIENT_SECRET, etc.

Performance Issues

Slow page loads

Check these:

  1. N+1 queries - Use joins instead of loops

    // ❌ Bad: N+1 queries
    const tasks = await db.select().from(tasks);
    for (const task of tasks) {
      const user = await db.select().from(users).where(eq(users.id, task.userId));
    }
    
    // ✅ Good: Single query with join
    const tasksWithUsers = await db
      .select()
      .from(tasks)
      .leftJoin(users, eq(tasks.userId, users.id));
  2. Large queries - Add pagination

    .limit(20)
    .offset(page * 20)
  3. No indexes - Add to frequently queried columns

    export const tasks = pgTable('tasks', {
      userId: text('user_id').notNull(),
    }, (table) => ({
      userIdIdx: index('user_id_idx').on(table.userId),
    }));

Database timeouts

Solution: Use connection pooling (see "Too many clients" above)


CSS & Styling Issues

Tailwind classes not working

Solutions:

  1. Check tailwind.config.ts content paths

    export default {
      content: [
        './src/**/*.{js,ts,jsx,tsx,mdx}',
      ],
    }
  2. Restart dev server

    rm -rf .next
    pnpm dev
  3. Check for typos

    ✅ className="text-blue-500"
    ❌ className="text-blue500"

Dark mode not working

Check:

  1. Is ThemeProvider added?

    // src/app/layout.tsx
    import { ThemeProvider } from 'next-themes';
    
    <ThemeProvider attribute="class">
      {children}
    </ThemeProvider>
  2. Does CSS have .dark styles?

    .dark {
      --color-background: 224 71% 4%;
    }

Testing Issues

Tests failing with "Cannot find module"

Solution: Add paths to vitest.config.ts:

export default defineConfig({
  resolve: {
    alias: {
      '~': path.resolve(__dirname, './src'),
    },
  },
});

E2E tests timing out

Solution: Increase timeout in playwright.config.ts:

export default defineConfig({
  timeout: 60000, // 60 seconds
});

Browser-Specific Issues

Works in Chrome but not Safari

Common issues:

  1. Unsupported CSS - Check Can I Use
  2. Date parsing - Use ISO 8601 strings
    new Date('2024-03-15T10:00:00Z')
    new Date('3/15/2024')

Works in Firefox but not Chrome

Usually: CSS vendor prefixes missing


Getting Help

Before asking for help:

  1. ✅ Check this troubleshooting guide
  2. ✅ Search GitHub Issues
  3. ✅ Read error message carefully
  4. ✅ Try clearing cache (rm -rf .next node_modules && pnpm install)
  5. ✅ Check browser console for errors

When asking for help, include:

  • Error message (full text, not screenshot)
  • What you tried (steps to reproduce)
  • Environment (OS, Node version, browser)
  • Relevant code (minimal example)
  • Expected vs actual behavior

Good issue:

Title: Database migration fails with "relation already exists"

Environment:
- OS: macOS 14.2
- Node: 18.17.0
- Database: PostgreSQL 16 (Neon)

Steps to reproduce:
1. Run `pnpm db:generate`
2. Run `pnpm db:migrate`
3. Error: relation "users" already exists

Error message:
[full error text here]

Expected: Migration runs successfully
Actual: Error about duplicate relation

What I tried:
- Deleted migration files
- Dropped database and recreated
- Still getting same error

Emergency Fixes

"Everything is broken, start over"

Nuclear option - Fresh start:

# Backup your code changes!
git status
git diff > my-changes.patch

# Delete everything
rm -rf node_modules .next .turbo pnpm-lock.yaml

# Reinstall
pnpm install

# Rebuild
pnpm build

Database corrupted

Reset database:

# Drop all tables
pnpm db:push --force  # ⚠️ DESTRUCTIVE!

# Or manually in psql
psql $PG_DATABASE_URL
DROP SCHEMA public CASCADE;
CREATE SCHEMA public;

# Recreate from migrations
pnpm db:migrate
pnpm db:seed

Useful Commands Cheat Sheet

# Clear caches
rm -rf .next node_modules .turbo
pnpm install

# Typecheck
pnpm typecheck

# Lint & format
pnpm lint

# Database
pnpm db:generate  # Generate migrations
pnpm db:migrate   # Run migrations
pnpm db:studio    # Open GUI

# Deployment
vercel --prod      # Deploy to Vercel
vercel env pull    # Download env vars

# Debugging
pnpm dev --debug   # Verbose logging
NODE_OPTIONS='--inspect' pnpm dev  # Node debugger

Still stuck?

Remember: Every expert was once a beginner. Don't give up! 🚀

On this page