Seeding with Drizzle ORM and tsx runner

I'm trying to seed my database. My project uses Drizzle ORM, and I have a seed.ts in my db directory. Simply including a tsx seed.ts gives me a message that my environment is not set up.

It's my first full stack project. I need some help pointing in the right direction for convincing the environment to be set up in the same way as running for a dev/test/prod db, but for the script that tsx will run.
Solution
Install the tsx runner. If you are using Node.js 20 or later, the following package.json entry will run your script:

"db:seed": "node --import tsx --env-file .env ./src/server/db/seed.ts",


If you're using Node.js before 20, use this instead:
    "db:seed": "tsx ./src/server/db/seed.ts"


Your script will look similar to this:
import { db } from "../db"
import { users } from "./schema"

let usernames = [
    'alice', 'bob', 'charlie'
]

for (let username of usernames){
    await db.insert(users).values({ name: username })
}


If you're using Node.js < 20, at the top, also insert this before the db import:
import 'dotenv/config'
Was this page helpful?