Prisma P2002 Unique Constraint Failed— Fixed [Complete Guide 2026]
Also covers: duplicate email · duplicate username · upsert pattern · composite unique
⚡ The Error You Are Seeing
PrismaClientKnownRequestError:
Invalid `prisma.user.create()` invocation:
Unique constraint failed on the fields: (`email`)
code: 'P2002',
meta: { target: [ 'email' ] }What Causes Prisma P2002
Prisma throws P2002 when you attempt to create or update a record with a value that already exists in a column marked @unique in your schema. The most common triggers:
- Registering a user with an email that already exists in the database
- Inserting a slug, username, or SKU that was already created
- Violating a composite @@unique([fieldA, fieldB]) constraint
- Running a seed script twice without clearing the database first
- Race condition — two requests creating the same record simultaneously
The key field to inspect is error.meta.target — it tells you exactly which field(s) caused the conflict.
Catch and Handle the P2002 Error
Best practice — never let P2002 crash your serverThe first thing to do is catch the error properly and return a clear user-facing message instead of a 500 crash.
import { PrismaClientKnownRequestError } from "@prisma/client/runtime/library";
export function isPrismaError(error: unknown, code: string): boolean {
return (
error instanceof PrismaClientKnownRequestError &&
error.code === code
);
}
export function getUniqueField(error: unknown): string | null {
if (error instanceof PrismaClientKnownRequestError) {
const target = error.meta?.target as string[] | undefined;
return target?.[0] ?? null;
}
return null;
}import { prisma } from "@/lib/prisma";
import { isPrismaError, getUniqueField } from "@/lib/prisma-error";
export async function POST(request: Request) {
const { email, name, password } = await request.json();
try {
const user = await prisma.user.create({
data: { email, name, password },
});
return Response.json({ user });
} catch (error) {
if (isPrismaError(error, "P2002")) {
const field = getUniqueField(error);
return Response.json(
{ error: `${field ?? "Value"} already in use` },
{ status: 409 }
);
}
throw error; // re-throw unexpected errors
}
}Always re-throw errors that are not P2002 — otherwise you will silently swallow unexpected database errors.
Use upsert Instead of create
Atomic — no race conditions, no P2002If your intent is 'create if not exists, update if exists', use upsert. This is atomic — it eliminates race conditions entirely.
// BEFORE — throws P2002 on duplicate email
const user = await prisma.user.create({
data: { email, name, role: "member" },
});
// AFTER — safe upsert, never throws P2002
const user = await prisma.user.upsert({
where: { email },
update: { name }, // fields to update if record exists
create: { email, name, role: "member" }, // fields for new record
});// Great for seeding or syncing external data
const config = await prisma.appConfig.upsert({
where: { key: "maintenance_mode" },
update: { value: "false" },
create: { key: "maintenance_mode", value: "false" },
});Check Before Inserting (findUnique)
Use when you need to return specific validation errorsWhen you need granular validation messages per field, check first with findUnique before creating.
findUnique + create is NOT atomic — a race condition can still cause P2002 between the two calls. For high-traffic endpoints, prefer upsert or catch P2002 directly.
export async function registerUser(email: string, name: string) {
// Check for existing email first
const existing = await prisma.user.findUnique({
where: { email },
select: { id: true }, // only fetch what you need
});
if (existing) {
return {
error: "An account with this email already exists",
field: "email",
};
}
// Safe to create — but still wrap in try/catch for race conditions
try {
const user = await prisma.user.create({
data: { email, name },
});
return { user };
} catch (error) {
if (isPrismaError(error, "P2002")) {
return { error: "Email already in use", field: "email" };
}
throw error;
}
}Composite Unique Constraints
@@unique([fieldA, fieldB]) in schema.prismaComposite unique constraints enforce uniqueness across multiple fields together. The error looks the same but error.meta.target will contain multiple field names.
model TeamMember {
id String @id @default(cuid())
userId String
teamId String
role String
// A user can only belong to a team once
@@unique([userId, teamId])
}try {
await prisma.teamMember.create({
data: { userId, teamId, role: "member" },
});
} catch (error) {
if (isPrismaError(error, "P2002")) {
// error.meta.target = ['userId', 'teamId']
const fields = (error as PrismaClientKnownRequestError)
.meta?.target as string[];
if (fields.includes("userId") && fields.includes("teamId")) {
return { error: "User is already a member of this team" };
}
}
throw error;
}Database Has Stale Duplicate Data
Seed scripts · data imports · migration driftIf P2002 appears after running a seed script or data import, your database likely contains rows that violate the unique constraint you added later. Fix the data first.
# Open Prisma Studio to inspect and delete duplicate rows
npx prisma studio
# Or query duplicates with raw SQL (PostgreSQL)
npx prisma db execute --stdin <<'SQL'
SELECT email, COUNT(*) as count
FROM "User"
GROUP BY email
HAVING COUNT(*) > 1;
SQL// Use upsert in seeds to make them idempotent
async function seed() {
await prisma.user.upsert({
where: { email: "admin@example.com" },
update: {},
create: {
email: "admin@example.com",
name: "Admin",
role: "admin",
},
});
}
seed().catch(console.error).finally(() => prisma.$disconnect());Prevention Checklist
- Always wrap prisma.create() calls in try/catch and handle P2002 explicitly
- Use upsert for seed scripts and external data syncs — always idempotent
- Return HTTP 409 Conflict (not 500) when a duplicate is detected
- Read error.meta.target to identify the exact conflicting field
- Add findUnique pre-checks for expensive operations where conflict is likely
- Use Prisma Studio (npx prisma studio) to inspect live data and spot duplicates
Frequently Asked Questions
What is Prisma error P2002?+−
How do I fix Prisma P2002 unique constraint failed on email?+−
What does error.meta.target contain in P2002?+−
How do I use upsert to avoid P2002?+−
P2002 on a field I didn't mark @unique — why?+−
How do I find all unique constraints in my Prisma schema?+−
Need Expert Help?
We Build Production-Grade Prisma Backends
Softplix architects and maintains Node.js backends with Prisma, PostgreSQL, and Next.js. Need a reliable data layer with proper error handling? Let us help.
Talk to an Engineer