Cloudflare D1 Adapter
Resources
Setup
Installation
npm install @auth/d1-adapter
Bindings
Bindings allow your Cloudflare Workers to interact with resources on the Cloudflare platform. To use this adapter, you must define the D1 binding in wrangler.toml
.
Follow these docs for instructions on how to do so.
Configuration
Once you have set up next-on-pages, you can access bindings via getRequestContext
.
./auth.ts
import NextAuth from "next-auth"
import { D1Adapter } from "@auth/d1-adapter"
import { getRequestContext } from "@cloudflare/next-on-pages"
export const { handlers, auth, signIn, signOut } = NextAuth(() => {
return {
providers: [],
adapter: D1Adapter(getRequestContext().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.