node database_error ai_generated true

PrismaClientKnownRequestError: Unique constraint failed on the fields: ('email')

ID: node/prisma-p2002-unique-constraint

Also available as: JSON · Markdown
93%Fix Rate
92%Confidence
70Evidence
2021-01-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
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.

generic

Workarounds

  1. 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

  2. 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

  3. 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:

  1. 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.

  2. 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.

  3. 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.

Error Chain

Frequently confused with: