⚠ Error - Top-level await is currently not supported with the "cjs" output format

I am trying to migrate to mysql database. I have already defined the schema and generated the migration files. But I try to migrate, I am getting this weird error -
PS D:\Typescript\drizzle orm\drizzle_test> npm run db:migrate

> drizzle_test@0.1.0 db:migrate
> tsx migrate.ts


node:internal/modules/run_main:115
triggerUncaughtException(
^
Error: Transform failed with 2 errors:
D:\Typescript\drizzle orm\drizzle_test\migrate.ts:6:0: ERROR: Top-level await is currently not supported with the "cjs" output format
D:\Typescript\drizzle orm\drizzle_test\migrate.ts:9:0: ERROR: Top-level await is currently not supported with the "cjs" output format
at failureErrorWithLog (D:\Typescript\drizzle orm\drizzle_test\node_modules\tsx\node_modules\esbuild\lib\main.js:1472:15)
at D:\Typescript\drizzle orm\drizzle_test\node_modules\tsx\node_modules\esbuild\lib\main.js:755:50
at responseCallbacks.<computed> (D:\Typescript\drizzle orm\drizzle_test\node_modules\tsx\node_modules\esbuild\lib\main.js:622:9)
at handleIncomingPacket (D:\Typescript\drizzle orm\drizzle_test\node_modules\tsx\node_modules\esbuild\lib\main.js:677:12)
at Socket.readFromStdout (D:\Typescript\drizzle orm\drizzle_test\node_modules\tsx\node_modules\esbuild\lib\main.js:600:7)
at Socket.emit (node:events:520:28)
at addChunk (node:internal/streams/readable:559:12)
at readableAddChunkPushByteMode (node:internal/streams/readable:510:3)
at Readable.push (node:internal/streams/readable:390:5)
at Pipe.onStreamRead (node:internal/stream_base_commons:191:23) {
name: 'TransformError'
}

Node.js v22.3.0
PS D:\Typescript\drizzle orm\drizzle_test> npm run db:migrate

> drizzle_test@0.1.0 db:migrate
> tsx migrate.ts


node:internal/modules/run_main:115
triggerUncaughtException(
^
Error: Transform failed with 2 errors:
D:\Typescript\drizzle orm\drizzle_test\migrate.ts:6:0: ERROR: Top-level await is currently not supported with the "cjs" output format
D:\Typescript\drizzle orm\drizzle_test\migrate.ts:9:0: ERROR: Top-level await is currently not supported with the "cjs" output format
at failureErrorWithLog (D:\Typescript\drizzle orm\drizzle_test\node_modules\tsx\node_modules\esbuild\lib\main.js:1472:15)
at D:\Typescript\drizzle orm\drizzle_test\node_modules\tsx\node_modules\esbuild\lib\main.js:755:50
at responseCallbacks.<computed> (D:\Typescript\drizzle orm\drizzle_test\node_modules\tsx\node_modules\esbuild\lib\main.js:622:9)
at handleIncomingPacket (D:\Typescript\drizzle orm\drizzle_test\node_modules\tsx\node_modules\esbuild\lib\main.js:677:12)
at Socket.readFromStdout (D:\Typescript\drizzle orm\drizzle_test\node_modules\tsx\node_modules\esbuild\lib\main.js:600:7)
at Socket.emit (node:events:520:28)
at addChunk (node:internal/streams/readable:559:12)
at readableAddChunkPushByteMode (node:internal/streams/readable:510:3)
at Readable.push (node:internal/streams/readable:390:5)
at Pipe.onStreamRead (node:internal/stream_base_commons:191:23) {
name: 'TransformError'
}

Node.js v22.3.0
11 Replies
Shayokh
ShayokhOP5mo ago
Migrate.ts -
import "dotenv/config";
import { migrate } from "drizzle-orm/mysql2/migrator";
import { db, connection } from "./db";

// This will run migrations on the database, skipping the ones already applied
await migrate(db, { migrationsFolder: "./drizzle" });

// Don't forget to close the connection, otherwise the script will hang
await connection.end();
import "dotenv/config";
import { migrate } from "drizzle-orm/mysql2/migrator";
import { db, connection } from "./db";

// This will run migrations on the database, skipping the ones already applied
await migrate(db, { migrationsFolder: "./drizzle" });

// Don't forget to close the connection, otherwise the script will hang
await connection.end();
db.ts -
import { drizzle } from "drizzle-orm/mysql2";
import mysql from "mysql2/promise";
import * as schema from "./drizzle/schema";

export const connection = await mysql.createConnection({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
multipleStatements: true,
});

export const db = drizzle(connection, { schema, mode: "default" });
import { drizzle } from "drizzle-orm/mysql2";
import mysql from "mysql2/promise";
import * as schema from "./drizzle/schema";

export const connection = await mysql.createConnection({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
multipleStatements: true,
});

export const db = drizzle(connection, { schema, mode: "default" });
drizzle config -
import { defineConfig } from "drizzle-kit";

export default defineConfig({
schema: "./drizzle/schema.ts",
out: "./drizzle/migrations",
dialect: "mysql",
verbose: true,
strict: true,

dbCredentials: {
url: process.env.DATABASE_URL as string,
},
});
import { defineConfig } from "drizzle-kit";

export default defineConfig({
schema: "./drizzle/schema.ts",
out: "./drizzle/migrations",
dialect: "mysql",
verbose: true,
strict: true,

dbCredentials: {
url: process.env.DATABASE_URL as string,
},
});
I additionally added these - tsconfig -
"module": "es2022",
"target": "ES2017",
"module": "es2022",
"target": "ES2017",
package.json -
"db:generate": "npx drizzle-kit generate",
"db:migrate": "tsx migrate.ts"
"db:generate": "npx drizzle-kit generate",
"db:migrate": "tsx migrate.ts"
BettoRaite
BettoRaite5mo ago
I think your ts config spits out cjs, that is why
D:\Typescript\drizzle orm\drizzle_test\migrate.ts:6:0: ERROR: Top-level await is currently not supported with the "cjs" output format
D:\Typescript\drizzle orm\drizzle_test\migrate.ts:6:0: ERROR: Top-level await is currently not supported with the "cjs" output format
in common js module system you can't have await keyword in global context You see your migration file uses the await in global context
await migrate(db, { migrationsFolder: "./drizzle" }); // <-- not good
await connection.end(); // <-- not good
await migrate(db, { migrationsFolder: "./drizzle" }); // <-- not good
await connection.end(); // <-- not good
possible fix wrap in Immediately Invoked Function Expressions (IIFE) in
import "dotenv/config";
import { migrate } from "drizzle-orm/mysql2/migrator";
import { db, connection } from "./db";

(async()=>{
// This will run migrations on the database, skipping the ones already applied
await migrate(db, { migrationsFolder: "./drizzle" });

// Don't forget to close the connection, otherwise the script will hang
await connection.end();
})();
import "dotenv/config";
import { migrate } from "drizzle-orm/mysql2/migrator";
import { db, connection } from "./db";

(async()=>{
// This will run migrations on the database, skipping the ones already applied
await migrate(db, { migrationsFolder: "./drizzle" });

// Don't forget to close the connection, otherwise the script will hang
await connection.end();
})();
same here so you either change the ts config or wrap in IIFE
Shayokh
ShayokhOP5mo ago
How do I change the ts config? I mean what should I add or remove? IIFE didnt work Same error
BettoRaite
BettoRaite5mo ago
There should a target option Try changing to es 2020 And btw gimme a screen of TS config
rphlmr ⚡
rphlmr ⚡5mo ago
This is because your package.json needs to have “type”: “module” to be 100% esm. But depending on your project it can cause some issues if one of your dependencies is not esm. The iife doesn’t work because your db.ts uses an await. Mysql2 has a synchronous way too (https://github.com/rphlmr/drizzle-mysql-commonjs/blob/main/config.js)
GitHub
drizzle-mysql-commonjs/config.js at main · rphlmr/drizzle-mysql-com...
Contribute to rphlmr/drizzle-mysql-commonjs development by creating an account on GitHub.
rphlmr ⚡
rphlmr ⚡5mo ago
You could also try to await import your db in the iief Note: drizzle-kit has a migrate command too This is my migrate script of one of my projects. I create a temp client in the function
import { drizzle } from "drizzle-orm/postgres-js";
import { migrate } from "drizzle-orm/postgres-js/migrator";
import postgres from "postgres";

async function runMigrate() {
if (!process.env.DATABASE_URL) {
throw new Error("DATABASE_URL is not set");
}

const migrationsClient = postgres(process.env.DATABASE_URL, {
max: 1,
prepare: false,
});

const db = drizzle(migrationsClient, { logger: true });

console.log("⏳ Running migrations...");

const start = Date.now();

await migrate(db, { migrationsFolder: `${__dirname}/migrations` });

const end = Date.now();

console.log(`✅ Migration end & took ${end - start}ms`);

process.exit(0);
}

runMigrate().catch((err) => {
console.error("❌ Migration failed");
console.error(err);
process.exit(1);
});
import { drizzle } from "drizzle-orm/postgres-js";
import { migrate } from "drizzle-orm/postgres-js/migrator";
import postgres from "postgres";

async function runMigrate() {
if (!process.env.DATABASE_URL) {
throw new Error("DATABASE_URL is not set");
}

const migrationsClient = postgres(process.env.DATABASE_URL, {
max: 1,
prepare: false,
});

const db = drizzle(migrationsClient, { logger: true });

console.log("⏳ Running migrations...");

const start = Date.now();

await migrate(db, { migrationsFolder: `${__dirname}/migrations` });

const end = Date.now();

console.log(`✅ Migration end & took ${end - start}ms`);

process.exit(0);
}

runMigrate().catch((err) => {
console.error("❌ Migration failed");
console.error(err);
process.exit(1);
});
Shayokh
ShayokhOP5mo ago
I added "type" : "module" and now I am getting this new error -
PS D:\Typescript\drizzle orm\drizzle_test> npm run db:migrate

> drizzle_test@0.1.0 db:migrate
> tsx migrate.ts

D:\Typescript\drizzle orm\drizzle_test\node_modules\src\migrator.ts:41
throw new Error(`Can't find meta/_journal.json file`);
^


Error: Can't find meta/_journal.json file
at readMigrationFiles (D:\Typescript\drizzle orm\drizzle_test\node_modules\src\migrator.ts:41:9)
at migrate (D:\Typescript\drizzle orm\drizzle_test\node_modules\src\mysql2\migrator.ts:9:21)
at <anonymous> (D:\Typescript\drizzle orm\drizzle_test\migrate.ts:6:7)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)

Node.js v22.3.0
PS D:\Typescript\drizzle orm\drizzle_test> npm run db:migrate

> drizzle_test@0.1.0 db:migrate
> tsx migrate.ts

D:\Typescript\drizzle orm\drizzle_test\node_modules\src\migrator.ts:41
throw new Error(`Can't find meta/_journal.json file`);
^


Error: Can't find meta/_journal.json file
at readMigrationFiles (D:\Typescript\drizzle orm\drizzle_test\node_modules\src\migrator.ts:41:9)
at migrate (D:\Typescript\drizzle orm\drizzle_test\node_modules\src\mysql2\migrator.ts:9:21)
at <anonymous> (D:\Typescript\drizzle orm\drizzle_test\migrate.ts:6:7)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)

Node.js v22.3.0
Shayokh
ShayokhOP5mo ago
No description
BettoRaite
BettoRaite5mo ago
Looks good
rphlmr ⚡
rphlmr ⚡5mo ago
yes now it's an other issue. You need to provide the path for migration folder relatives to your script execution. ex in my script: ${__dirname}/migrations but I think __dirname is a cjs thing so it will not work. 2 solutions: 1: make it esm compatible 2: don't care (keep your package.json like it was) and just create a client in your migrate script, inside the function 3: use drizzle-kit migrate and no need for a script
Shayokh
ShayokhOP5mo ago
Thanks a lot I will try them and inform which one did the job :]
Want results from more Discord servers?
Add your server