#How to seed from typescript?

4 messages · Page 1 of 1 (latest)

hearty fog
#

Is there docs or an example of seeding from a script / typescript instead of static json?

tawdry auroraBOT
#

Hi @hearty fog. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

Yes, you can seed data in Convex directly from TypeScript scripts, rather than using static JSON files. This approach is well-documented and commonly used in Convex projects.

How to Seed from TypeScript

  1. Write a Mutation or Internal Mutation

    • Create a mutation (or preferably an internalMutation for security) in your convex/ directory. This function will insert your seed data using the Convex database API.

    Example:

    // convex/init.ts
    import { internalMutation } from "./_generated/server";
    
    export default internalMutation(async (ctx) => {
      // Only seed if the table is empty
      const existing = await ctx.db.query("users").first();
      if (existing) return;
    
      await ctx.db.insert("users", {
        name: "Alice",
        email: "[email protected]",
      });
      // Add more seed data as needed
    });
    
  2. Run the Seed Script

    • You can execute this mutation from the CLI:
      npx convex run init
      
    • Or configure your package.json to run it automatically on startup:
      {
        "scripts": {
          "predev": "convex dev --until-success --run init"
        }
      }
      
      This will run your seed function every time you start your dev server, ensuring your database is initialized with the seed data. The function can be safely called multiple times if it checks for existing data first.
  3. Use Faker or Other Libraries for Dynamic Data

    • You can use libraries like Faker to generate realistic fake data within your mutation:
      import { faker } from '@faker-js/faker';
      import { internalMutation } from "./_generated/server";
#

export const createFake = internalMutation(async (ctx) => {
faker.seed();
for (let i = 0; i < 200; i++) {
await ctx.db.insert("users", {
name: faker.person.fullName(),
company: faker.company.name(),
avatar: faker.image.avatar(),
});
}
});
Then run with:
npx convex run users:createFake
```
Testing Your App: How to Generate Fake Data

Documentation & Examples

This approach is preferred for type safety, maintainability, and the ability to generate complex or dynamic data structures.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: