Skip to content
Migrating from NextAuth.js v4? Read our migration guide.

Cloudflare D1 Adapter

Resources

Setup

Installation

npm install next-auth @auth/d1-adapter

Environment Variables

Environment variables in Cloudflare’s platform are set either via a wrangler.toml configuration file, or in the admin dashboard.

Configuration

./auth.ts
import NextAuth from "next-auth"
import { D1Adapter } from "@auth/d1-adapter"
 
export const { handlers, auth, signIn, signOut } = NextAuth({
  providers: [],
  adapter: D1Adapter(env.db),
})

Migrations

Somewhere in the initialization of your application you need to run the up(env.db) function to create the tables in D1. It will create 4 tables if they don’t already exist: accounts, sessions, users, verification_tokens.

The table prefix "" is not configurable at this time.

You can use something like the following to attempt the migration once each time your worker starts up. Running migrations more than once will not erase your existing tables.

import { up } from "@auth/d1-adapter"
 
let migrated = false
async function migrationHandle({ event, resolve }) {
  if (!migrated) {
    try {
      await up(event.platform.env.db)
      migrated = true
    } catch (e) {
      console.log(e.cause.message, e.message)
    }
  }
  return resolve(event)
}
  • You can also initialize your tables manually. Look in migrations.ts for the relevant SQL as well as an example of the up() function from above.
  • Paste and execute the SQL from within your D1 database’s console in the Cloudflare dashboard.
Auth.js © Balázs Orbán and Team - 2024