PrismaClientKnownRequestError: Unique constraint failed on the fields: (`email`)
You’re trying to insert a duplicate value in a unique column.
Fix 1: Use upsert
await prisma.user.upsert({
where: { email: 'alice@example.com' },
update: { name: 'Alice Updated' },
create: { email: 'alice@example.com', name: 'Alice' },
});
Fix 2: Check before inserting
const existing = await prisma.user.findUnique({
where: { email: 'alice@example.com' },
});
if (!existing) {
await prisma.user.create({ data: { email: 'alice@example.com', name: 'Alice' } });
}
Fix 3: Handle the error
try {
await prisma.user.create({ data });
} catch (e) {
if (e.code === 'P2002') {
console.log('Email already exists');
}
}