Drizzle ORM Adapter
Resources
Setup
Installation
npm install drizzle-orm @auth/drizzle-adapter
npm install drizzle-kit --save-dev
Environment Variables
AUTH_DRIZZLE_URL=postgres://postgres:postgres@127.0.0.1:5432/db
Configuration
To use this adapter, you must have setup Drizzle ORM and Drizzle Kit in your project. Drizzle provides a simple quick start guide. For more details, follow the Drizzle documentation for your respective database (PostgreSQL, MySQL or SQLite). In summary, that setup should look something like this.
- Create your schema file, based off of one of the ones below.
- Install a supported database driver to your project, like
@libsql/client
,mysql2
orpostgres
. - Create a
drizzle.config.ts
file. - Generate the initial migration from your schema file with a command like,
drizzle-kit generate:pg
. - Push that migration to your configured database with a command like,
drizzle-kit push:pg
.
Schemas
Adapter Setup
./auth.ts
import NextAuth from "next-auth"
import { DrizzleAdapter } from "@auth/drizzle-adapter"
import { db } from "./schema.ts"
export const { handlers, auth, signIn, signOut } = NextAuth({
adapter: DrizzleAdapter(db),
providers: [],
})
Migrating your database
With your schema now described in your code, you’ll need to migrate your database to your schema. An example migrate.ts
file looks like this. For more information, check out Drizzle’s migration quick start guide.
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()
Full documentation on how to manage migrations with Drizzle can be found at the Drizzle Kit Migrations page.