Drizzle Usage

Learn how to configure and use Drizzle ORM for your project

Configuration

The Drizzle configuration is defined in drizzle.config.ts. This is used by Drizzle ORM to connect to the database, run migrations, and generate the database schema.

drizzle.config.ts
import type { Config } from "drizzle-kit";
const { TURSO_DB_URL, TURSO_DB_TOKEN } = process.env;

if (!TURSO_DB_URL || !TURSO_DB_TOKEN) {
  throw new Error(
    "Missing 'TURSO_DB_URL' or 'TURSO_DB_TOKEN' environment variables",
  );
}

export default {
  schema: "./server/database/schema.ts",
  out: "./server/database/migrations",
  driver: "turso",
  dialect: "sqlite",
  dbCredentials: {
    url: TURSO_DB_URL,
    authToken: TURSO_DB_TOKEN,
  },
} satisfies Config;

You can find the full configuration in the Drizzle ORM documentation.

Migrations

Migrations are used to update the database schema. They are located in server/database/migrations.

Creating Migrations

To create a new migration, run:

pnpm db:migrate

Deploying Migrations

To deploy the database, you can use the pnpm db:deploy command.

Auto run migrations

You can utilize Nuxt's server plugins to run the migrations on the development server start:

server/plugins/migrations.ts
import { consola } from "consola";
import { migrate } from "drizzle-orm/d1/migrator";

export default defineNitroPlugin(async () => {
  if (!import.meta.dev) return;

  nuxtApp.hook("ready", async () => {
    await migrate(useDB(), { migrationsFolder: "server/database/migrations" })
      .then(() => {
        consola.success("Database migrations done");
      })
      .catch((err) => {
        consola.error("Database migrations failed", err);
      });
  });
});