#How to seed from typescript?
4 messages · Page 1 of 1 (latest)
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
-
Write a Mutation or Internal Mutation
- Create a mutation (or preferably an
internalMutationfor security) in yourconvex/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 }); - Create a mutation (or preferably an
-
Run the Seed Script
- You can execute this mutation from the CLI:
npx convex run init - Or configure your
package.jsonto run it automatically on startup: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.{ "scripts": { "predev": "convex dev --until-success --run init" } }
- You can execute this mutation from the CLI:
-
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";
- You can use libraries like Faker to generate realistic fake data within your mutation:
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
- Seeding Data for Preview Deployments: Seeding data in code
- Supercharge
npm run devwith package.json scripts: Seeding data on startup - Testing Your App: How to Generate Fake Data
- Data Migration and Seeding Example