Skip to content
Migrating from NextAuth.js v4? Read our migration guide.
Getting Started
Adapters
Drizzle

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.

  1. Create your schema file, based off of one of the ones below.
  2. Install a supported database driver to your project, like @libsql/client, mysql2 or postgres.
  3. Create a drizzle.config.ts file.
  4. Generate the initial migration from your schema file with a command like, drizzle-kit generate:pg.
  5. Apply migrations by using migrate() function or push changes directly to your database with a command like, drizzle-kit push:pg.
  6. If your schemas differ from the default ones, pass them as the second parameter to the adapter.

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: [],
})

Passing your own Schemas

If you want to use your own tables, you can pass them as a second argument to DrizzleAdapter.

  • The sessionsTable is optional and only required if you’re using the database session strategy.
  • The verificationTokensTable is optional and only required if you’re using a Magic Link provider.
auth.ts
import NextAuth from "next-auth"
import Google from "next-auth/providers/google"
import { DrizzleAdapter } from "@auth/drizzle-adapter"
import { db, accounts, sessions, users, verificationTokens } from "./schema"
 
export const { handlers, auth } = NextAuth({
  adapter: DrizzleAdapter(db, {
    usersTable: users,
    accountsTable: accounts,
    sessionsTable: sessions,
    verificationTokensTable: verificationTokens,
  }),
  providers: [Google],
})

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.

Auth.js © Balázs Orbán and Team - 2024