Prisma error P2003 (Foreign Key Constraint Failed) explained: what it means, why it happens, and how to fix it — with copy-paste code examples.
Read error.meta.field_name to find the foreign key column that failed. If that does not apply, confirm the referenced parent record actually exists in the target table — the full checklist is below.
Error code: P2003
Official name: Foreign Key Constraint Failed
Service: Prisma
Foreign key constraint failed on the field: {field_name}
const user = await prisma.user.create({
data: {
email: 'ada@example.com',
profile: { create: { bio: 'Engineer' } },
},
})
Prisma creates the parent first, then the dependent row, so the foreign key is always satisfied.
catch (e) {
if (e.code === 'P2003') {
console.error('foreign key:', e.meta.field_name)
}
}
meta.field_name points at the offending column in the schema.
Translate P2003 into HTTP 400/409 with the field name; tell clients the referenced parent is missing.
if (e.code === 'P2003') {
return response.status(400).json({
message: `Invalid reference on ${e.meta.field_name}`,
})
}
Use nested creates so Prisma inserts the parent and child in one operation, satisfying the FK.
await prisma.user.create({
data: {
name: 'Ada',
posts: { create: [{ title: 'Hello' }] },
},
})
Most often this happens when inserting or updating a child row whose foreign key references a parent id that does not exist, or when deleting a parent row that is still referenced by children under a Restrict/NoAction relation.
Read error.meta.field_name to find the foreign key column that failed.
This page documents fixes for: nestjs, prisma-client.
Recommendations are editorial — DB Error Reference takes no payment or affiliate fees for tool listings.
This page is based on the official Prisma documentation linked below and adds practical troubleshooting guidance on top.