How To Seed Your Database With Prisma
Prisma
02/01/2023
Create your script
The logic of your seed script (e.g. create user data) is contained within a main
function. Once your script is finished executing, the prisma client is terminated in the finally
method. Simultaneously, we keep an eye 👀 out for any potential errors using the catch
method (e.g. due to an incorrect query).
const prisma = new PrismaClient()
async function main() { // Perform database queries here // await prisma.user.create(...)}
main() .catch(error => { console.error(error) process.exit(1) }) .finally(async () => { await prisma.$disconnect() })
Run your script
To run your script, you will first need to have the following dependencies installed.
# NPMnpm install -D typescript ts-node @types/node
# Yarnyarn add --dev typescript ts-node @types/node
Prisma expects any seed scripts to be executed via the seed
field in the prisma
key of your package.json
file.
{ "name": "my-blog", "version": "1.0.0", "prisma": { "seed": "ts-node <path to file>/seed.ts" }, "devDependencies": { "@types/node": "18.7.12", "ts-node": "^10.9.1", "typescript": "4.8.0" }}
You may then manually 💻 execute your script with:
# NPMnpx prisma db seed
# Yarnyarn prisma db seed
Be aware that your seed script is run automatically with prisma migrate dev
and prisma migrate reset
. If you wish this not to happen, append --skip-seed
.
Script execution in Next.js
If you are running, for example, a Next.js project, you will need to adjust your prisma seed field to include a compiler.
"prisma": { "seed": "ts-node --compiler-options {\"module\":\"CommonJS\"} <path to file>/seed.ts"}