PrismaClientKnownRequestError: Unique constraint failed on the fields: ('email')
ID: node/prisma-p2002-unique-constraint
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 20 | active | — | — | — |
Root Cause
A database insert or update violates a unique constraint. The correct fix depends on the use case: upsert for 'create or update' patterns, error catching for user-facing duplicate checks.
genericWorkarounds
-
94% success Use prisma.model.upsert() with where matching the unique constraint
await prisma.user.upsert({ where: { email }, update: { name }, create: { email, name } }). The 'where' clause must match the exact field(s) in the unique constraint that caused the error.Sources: https://www.prisma.io/docs/reference/api-reference/prisma-client-reference#upsert
-
92% success Catch error code P2002 and return a user-friendly message
try { await prisma.user.create({ data }) } catch(e) { if (e instanceof Prisma.PrismaClientKnownRequestError && e.code === 'P2002') { return { error: `${e.meta?.target?.[0]} already exists` } } throw e; }Sources: https://www.prisma.io/docs/reference/api-reference/error-reference#p2002
-
88% success Check e.meta.target for compound unique constraint diagnosis
For compound unique constraints (e.g., @@unique([email, orgId])), e.meta.target returns an array of field names like ['email', 'org_id']. Use this to generate specific error messages per constraint.
Dead Ends
Common approaches that don't work:
-
Catching the error and retrying the same create operation
95% fail
A unique constraint violation is deterministic for the same input. Retrying with identical data produces the same error every time. This wastes database connections and creates confusing log noise.
-
Removing the @unique attribute from the Prisma schema
90% fail
Removes a critical data integrity constraint. Duplicate records cause cascading bugs in queries, authentication, and foreign key relationships. The constraint exists to protect data consistency.
-
Using upsert without matching on the correct unique field
65% fail
prisma.model.upsert requires the 'where' clause to match on the unique constraint field. If you match on 'id' instead of 'email', you create duplicates because the 'where' misses the conflicting record.