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",
"db:seed": "node --import tsx --env-file .env ./src/server/db/seed.ts",
...
Jump to solution
4 Replies
Vincent Udén
Vincent Udén5mo ago
Running standalone .ts can be unexpectedly difficult. I've had great success with tsno (https://github.com/egoist/tsno) but I'm not sure if its the preferred method anymore. Hasnt needed any extra configuration other than proper imports inside the standalone .ts file
GitHub
GitHub - egoist/tsno: node with typescript support, importing fro...
node with typescript support, importing from URL, etc. - GitHub - egoist/tsno: node with typescript support, importing from URL, etc.
Vincent Udén
Vincent Udén5mo ago
Also, if you happen to have bun that might be worth a shot too
Josh
Josh5mo ago
for seed scripts and such, bun is my recommendation the reason you're environment isn't seen is because node doesn't inheritly load your .env file, so you'll need to use something like dotenv in your seed script to load them make sure that your env variables are loaded before you try to connect to the db good debugging tip is to console log the connection keys right before you create your drizzle connection. if they are undefined, you know that they failed to get loaded in for whatever reason use wsl
Solution
rik
rik5mo ago
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",
"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"
"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 })
}
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'
import 'dotenv/config'