How to seed a database during development with Prisma and Chance.js

Learn how to seed a database during development when using Prisma as an ORM. We will use Chance.js to generate mock data and accelerate development

What is seeding a database?

Seeding a database is the process of populating the database with data. It is great when you want data that is close to what your real life data would look like but don't necessarily have that data yet.

Seeding your database
Learn how to seed your database using Prisma’s integrated seeding functionality and Prisma Client

In the context of Prisma there a few reasons you might need to seed your database

What is Chance.js

Chance.js is a library you can use to generate random data in various formats (strings, numbers, names, sentences, urls, etc).

How to seed your database

Install chance.js

npm install --save-dev chance

If you are using typescript like me you will need to also install @types/chance to have proper autocomplete in your IDE and ts-node to run the seed.ts file

npm install --save-dev @types/chance ts-node

Create a seed file

A seed file tells prisma how to populate the database. Create a file called seed.ts (or seed.js if you don't use typescript) under root_folder/prisma/seed.ts

Add the seed file to your package.json

For prisma to run your seed file, it needs know where it's located. Add this to your package.json

  "prisma": {
    "seed": "ts-node prisma/seed.ts"
  },

Create the data

The seed file is simply a typescript/javascript file that creates a PrismaClient and populates the database. Find an example below. In this example I am creating 1000 bookmarks using Chance.js. I am using the url(), string() methods from Chance.JS.  Bookmark and User are tables in my prisma.schema file

model User {
  id                  String               @id
  email               String             @unique
  bookmarks           Bookmark[]
}

model Bookmark {
  id            String            @id @default(uuid())
  title         String            @db.Text()
  description   String?           @db.Text()
  url           String
  createdAt     DateTime          @default(now())
  updatedAt     DateTime          @updatedAt
  ownerId       String
  owner         User              @relation(fields: [ownerId], references: [id], onDelete: Cascade)
}
import {PrismaClient, User} from "@prisma/client";
import Chance from 'chance'
import {Bookmark} from "@pagemarker/data";

const client = new PrismaClient()
var chance = new Chance();

async function seed() {
    const user: User = {
        id: "xxxxxxxxx",
        email: "foobar@gmail.com"
    }

    await client.user.create({data: user})

    for (let i = 0; i < 1000; i++) {
        await client.bookmark.create({
            data: {
                title: chance.word({length: 10}),
                description: chance.sentence(),
                url: chance.url(),
                ownerId: user.id,
            }
        })
    }
}

seed()

Chance.js has many more methods. For a complete list look at the documentation

https://chancejs.com/

Run the prisma db seed command

Now we run the following command to populate the database

prisma db seed

Prisma will run your seed.ts file as if it was a regular node.js program. Make sure you don't run this command on your production database

If you look in your development database with Prisma Studio you will see something like this

Keep in mind that you do not always need to run this command manually Prisma will execute when you loose your data after prisma migrate dev or run the prisma migrate reset command manually

Using seeding in your development workflow

Here's what I do when developing using Prisma

  1. create/update prisma.schema
  2. run prisma db push when prototyping
  3. when satisfied with my schema I run prisma migrate dev to create a new migration.
  4. The migration will reset the database and prisma db seed is ran automatically
  5. Work on frontend or backend
  6. Test everything.
  7. Run prisma migrate deploy on production database

For more info on seeding, check the prisma documentation

Seeding your database
Learn how to seed your database using Prisma’s integrated seeding functionality and Prisma Client

Do you need help building your SaaS? Hi my name is Charles. I am freelance full stack web developer focused on building SaaS using Next.js, React and Node.js. Shoot me an email to get started!