Skip to main content

@auth/d1-adapter

An official Cloudflare D1 adapter for Auth.js / NextAuth.js.

Warning​

This adapter is not developed or maintained by Cloudflare and they haven't declared the D1 api stable. The author will make an effort to keep this adapter up to date. The adapter is compatible with the D1 api as of March 22, 2023.

Installation​

npm install next-auth @auth/d1-adapter

D1Adapter()​

D1Adapter(db): Adapter

Setup​

This is the D1 Adapter for next-auth. This package can only be used in conjunction with the primary next-auth package. It is not a standalone package.

Configure Auth.js​

pages/api/auth/[...nextauth].js
import NextAuth from "next-auth"
import { D1Adapter, up } from "@auth/d1-adapter"

// For more information on each option (and a full list of options) go to
// https://authjs.dev/reference/configuration/auth-options
export default NextAuth({
// https://authjs.dev/reference/providers/
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. Paste and execute the SQL from within your D1 database's console in the Cloudflare dashboard.

Parameters​

β–ͺ db: D1Database

Returns​

Adapter


up()​

up(db): Promise< void >

Parameters​

β–ͺ db: D1Database

Returns​

Promise< void >


D1Database​

type D1Database: WorkerDatabase | MiniflareD1Database;