🔧 Error Fixes
· 1 min read

Next.js 500 Internal Server Error — How to Fix It


500 Internal Server Error
Error: An error occurred in the Server Components render.

Your Next.js app works in development but crashes in production. The error is happening server-side.

Fix 1: Check the Server Logs

# Vercel
vercel logs --follow

# Self-hosted
pm2 logs
# Or check .next/server logs

Development hides many errors that production exposes. Always check logs first.

Fix 2: Missing Environment Variables

# ❌ .env.local exists locally but not in production
DATABASE_URL=postgresql://...  # Not set on Vercel/server

# ✅ Add env vars to your hosting platform
# Vercel: Settings → Environment Variables
# Or use .env.production

Fix 3: Server Component Using Browser APIs

// ❌ window doesn't exist on the server
export default function Page() {
    const width = window.innerWidth;  // 💥 500 error
}

// ✅ Use 'use client' or check for window
'use client';
export default function Page() {
    const [width, setWidth] = useState(0);
    useEffect(() => setWidth(window.innerWidth), []);
}

Fix 4: Database Connection Failing

// ❌ Database unreachable in production
// Check connection string, IP allowlist, SSL settings

// ✅ Verify connection
// Prisma: npx prisma db pull
// Direct: test with a simple query in production

Fix 5: Build vs Runtime Error

# If it builds fine but crashes at runtime:
npm run build  # Check for warnings
npm run start  # Test production mode locally

# Common: dynamic imports failing, missing dependencies

Fix 6: API Route Throwing

// ❌ Unhandled error in API route
export async function GET() {
    const data = await db.query();  // 💥 If this throws
    return Response.json(data);
}

// ✅ Wrap in try/catch
export async function GET() {
    try {
        const data = await db.query();
        return Response.json(data);
    } catch (e) {
        return Response.json({ error: e.message }, { status: 500 });
    }
}