PrismaClientKnownRequestError: Unique constraint failed on the fields: (`email`)
Youβre trying to insert a duplicate value in a unique column.
Why this happens
Your Prisma schema has a @unique attribute on a field (like email), and youβre attempting to create a record with a value that already exists. This also happens with @@unique compound constraints, or when race conditions cause two concurrent requests to insert the same value before either commits.
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');
}
}
Alternative solution: Use createMany with skipDuplicates
When inserting multiple records, skip duplicates silently:
await prisma.user.createMany({
data: users,
skipDuplicates: true,
});
Prevention
- Validate uniqueness on the frontend before submitting (e.g., check if email is taken during registration).
- Always handle P2002 errors in your API layer and return a user-friendly 409 Conflict response.
Related: Prisma cheat sheet Β· What is PostgreSQL Β· Prisma vs Drizzle vs TypeORM