LogoStarterkitpro
Features/Databases

Database Seeding Setup

Populating your database with initial data using Prisma seeds.

Database seeding is the process of populating a database with initial data. This is useful for development (having test users/data), demonstrations, or setting up default configurations.

Prisma provides a built-in mechanism for seeding your database.

1. Create the Seed File (prisma/seed.ts)

Create a file named seed.ts inside your prisma directory. This file will contain the logic for creating your initial data.

prisma/seed.ts
import { PrismaClient } from "@prisma/client";
 
const prisma = new PrismaClient();
 
async function main() {
  console.log(`Start seeding ...`);
 
  // --- Seed Data Logic ---
  // Add your Prisma client calls here to create initial data.
  // Example: Create initial users
  try {
    const users = [
      { email: "test@example.com", name: "Test User 1" },
      { email: "admin@example.com", name: "Admin User" },
      // Add more initial data as needed
    ];
 
    // Using createMany for efficiency, but you can use create if needed
    const createdUsers = await prisma.user.createMany({
      data: users,
      skipDuplicates: true, // Optional: Prevent errors if records already exist
    });
 
    console.log(`Created ${createdUsers.count} users.`);
 
    // Example: Create initial posts (assuming a Post model related to User)
    /*
    const user1 = await prisma.user.findUnique({ where: { email: 'test@example.com' } });
    if (user1) {
      await prisma.post.createMany({
        data: [
          { title: 'First Post', content: 'Hello World!', authorId: user1.id },
          { title: 'Second Post', content: 'Another one!', authorId: user1.id },
        ],
        skipDuplicates: true,
      });
      console.log(`Created initial posts for user ${user1.email}`);
    }
    */
 
    // Add more seeding logic for other models...
  } catch (error) {
    console.error("Error during seeding specific data:", error);
    // Decide if you want to exit or continue if a part fails
    process.exit(1);
  } finally {
    // This block is not strictly necessary within the main try/catch
    // as the outer finally will handle disconnection.
  }
  // --- End Seed Data Logic ---
 
  console.log(`Seeding finished.`);
}
 
// Execute the main seeding function
main()
  .catch((e) => {
    console.error("Error executing main seed function:", e);
    process.exit(1);
  })
  .finally(async () => {
    // Ensure Prisma Client disconnects after seeding
    await prisma.$disconnect();
  });
  • Replace the example prisma.user.createMany call with your actual Prisma model operations. - Add logic to seed any other necessary models. - Use skipDuplicates: true where appropriate if running the seed script multiple times shouldn't cause errors.

2. Configure package.json

Add a seed script and the Prisma seed configuration to your package.json file:

package.json (Additions)
{
  "scripts": {
    // ... other scripts
    "db:seed": "prisma db seed"
  },
  "prisma": {
    "seed": "ts-node --compiler-options {\\"module\\":\\"CommonJS\\"} prisma/seed.ts"
  }
  // ... other configurations
}
  • The db:seed script provides a convenient way to run the Prisma seeding command.
  • The prisma.seed configuration tells Prisma how to execute your TypeScript seed file using ts-node.
  • The --compiler-options {"module":"CommonJS"} flag is often necessary to ensure ts-node handles modules correctly in this context.

3. Run the Seed Script

Execute the seed script using npm (or yarn):

Terminal
npm run db:seed

Prisma will now execute your prisma/seed.ts file, populating your database with the initial data you defined.

Ensure your database connection URL in .env is correctly configured before running the seed command. Make sure you have run prisma migrate dev or prisma migrate deploy at least once to ensure your database schema exists.

On this page