Database migrations provide version control for your database schema. NuxtHub supports SQL migration files (.sql) and automatically applies them during development and deployment. Making them fully compatible with Drizzle Kit generated migrations.
.<dialect>.sql suffix (e.g., 0001_create-todos.postgresql.sql).NuxtHub scans server/db/migrations for migrations in each Nuxt layer.
To scan additional directories, specify them in your config:
export default defineNuxtConfig({
hub: {
db: {
dialect: 'postgresql',
migrationsDirs: [
'server/db/custom-migrations/'
]
}
}
})
For more control (e.g., in Nuxt modules), use the hub:db:migrations:dirs hook:
import { createResolver, defineNuxtModule } from '@nuxt/kit'
export default defineNuxtModule({
meta: {
name: 'my-auth-module'
},
setup(options, nuxt) {
const { resolve } = createResolver(import.meta.url)
nuxt.hook('hub:db:migrations:dirs', (dirs) => {
dirs.push(resolve('./db-migrations'))
})
}
})
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
email TEXT NOT NULL
);
.data/db/migrations when you run Nuxt, giving you a consolidated view.Migrations are automatically applied when you:
npx nuxi dev)npx nuxi build)Applied migrations are tracked in the _hub_migrations database table.
Once you have updates your database schema, you can generate new migrations using the following command:
npx nuxt db generate
This will generate new migrations files in server/db/migrations/{dialect}/ which are automatically applied during development and deployment.
Once you have generated new migrations, you can apply them using the following command:
npx nuxt db migrate
This will apply the new migrations to your database.
_hub_migrations. Ensure they're idempotent.Use the hub:db:queries:paths hook to run additional queries after migrations:
import { createResolver, defineNuxtModule } from '@nuxt/kit'
export default defineNuxtModule({
meta: {
name: 'my-auth-module'
},
setup(options, nuxt) {
const { resolve } = createResolver(import.meta.url)
nuxt.hook('hub:db:queries:paths', (paths, dialect) => {
paths.push(resolve(`./db-queries/seed-admin.${dialect}.sql`))
})
}
})
INSERT OR IGNORE INTO admin_users (id, email, password) VALUES (1, 'admin@nuxt.com', 'admin');
.data/db/queries when you run Nuxt, giving you a consolidated view.For Cloudflare D1 with Drizzle ORM migrations, replace:
-PRAGMA foreign_keys = OFF;
+PRAGMA defer_foreign_keys = on;
ALTER TABLE ...
-PRAGMA foreign_keys = ON;
+PRAGMA defer_foreign_keys = off;
Query
Learn how to read and write data using Drizzle ORM in Nuxt, including filtering, joining, and aggregating relational data safely and efficiently.
CLI
Manage your Nuxt SQL database with the `npx nuxt db` CLI, including generating migrations, applying them, running SQL queries, and marking migrations as applied.