Back to Blog
Lesson 21 of the Next.js: Build Full-Stack Apps with the App Router course
Next.jsAugust 8, 20264 min read

Seeding Data: Automating Database Population with Prisma

Learn how to create and run Prisma seed scripts to automate database population, ensuring your Next.js project always has consistent data for testing.

Next.jsPrismaDatabaseSeedingTypeScript
Detailed image of laboratory equipment with rows of test tubes ready for analysis.

Previously in this course, we covered Database Setup with Prisma in Next.js: A Practical Guide and moved on to Defining the Blog Schema: Prisma Models and Migrations. Now that you have a database schema, you need a way to populate it with initial data so you aren't staring at empty screens while building your UI.

Seeding is the process of programmatically inserting initial data into your database. It is essential for development, allowing you to quickly reset your environment or provide default content for your blog without manual entry.

Why We Seed Databases

When you're building a feature-rich application, you often need a reliable set of "dummy" data to test layout variations, edge cases, and pagination. Instead of manually typing rows into a database tool, we write a script that defines this data as code.

By using Prisma's built-in seeding mechanism, you ensure that every developer on your team (or your future self) starts with the same data state.

Creating Your Seed Script

Prisma looks for a seed.ts file (or .js) in your prisma/ directory. First, ensure you have ts-node installed so you can run TypeScript seed scripts directly:

Bash
npm install -D ts-node

Next, update your package.json to tell Prisma where your seed script lives:

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

Now, create prisma/seed.ts. This script will use the PrismaClient instance to upsert data—this is better than create because it prevents errors if you run the seed script multiple times (it updates existing records instead of failing on duplicates).

TYPESCRIPT
import { PrismaClient } from CE9178">'@prisma/client';

const prisma = new PrismaClient();

async function main() {
  await prisma.post.upsert({
    where: { slug: CE9178">'hello-world' },
    update: {},
    create: {
      title: CE9178">'Hello World',
      slug: CE9178">'hello-world',
      content: CE9178">'Welcome to my new blog built with Next.js!',
    },
  });
}

main()
  .catch((e) => {
    console.error(e);
    process.exit(1);
  })
  .finally(async () => {
    await prisma.$disconnect();
  });

Running Database Seeding

A female engineer using a laptop while monitoring data servers in a modern server room.

You can trigger your seeding logic manually at any time using the Prisma CLI. This is particularly useful after you've run a migration or wiped your database for a clean start.

Run the following command in your terminal:

Bash
npx prisma db seed

Prisma will execute your seed.ts file, connect to the database, and insert the defined blog posts. If you are working on your local project and want to reset your database entirely (useful for development), you can run:

Bash
npx prisma migrate reset

This command drops your database, runs your migrations again, and automatically triggers the seeding script at the end.

Verifying Data Persistence

Once the script finishes, you need to confirm the data is actually there. You can use Prisma Studio, a visual browser-based interface for your data.

Run this in your terminal:

Bash
npx prisma studio

This opens a local web server (usually at http://localhost:5555) where you can view tables, inspect your "Hello World" post, and verify that the database connection is working as expected.

Common Pitfalls

  • Forgetting to Disconnect: Always call prisma.$disconnect() in your finally block. Without it, the script may hang in your terminal, waiting for an open connection.
  • Duplicate Keys: If you use prisma.post.create instead of upsert, running the seed script twice will throw a unique constraint error because your slug is likely marked as @unique. Always prefer upsert for seeding.
  • Schema Mismatch: If you change your schema but don't update your seed.ts, the script will fail. Always ensure your seed data matches the latest version of your model definitions.

FAQ

Can I use seed data in production? No. Seeding is intended for development environments. In production, you should use migration scripts or dedicated migration tools to manage data population.

How do I seed related data? You can chain prisma.post.create calls within your main() function, using the data property to nest related records, such as linking a User to a Post.

Does prisma db seed clear my database? No, it only executes the code in your seed file. To clear the database, you must use prisma migrate reset.

Recap

Team members presenting a project in a modern office setting with a focus on collaboration.

In this lesson, we configured a seed.ts file, integrated it into the package.json, and learned how to use upsert to safely populate our database. You now have a repeatable way to ensure your blog has content for the next stage of development.

Up next: Fetching Data from the Database — we will finally pull these seeded posts into our Server Components and display them on the homepage.

Similar Posts