@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
- Yarn
- pnpm
npm install next-auth @auth/d1-adapter
yarn add next-auth @auth/d1-adapter
pnpm add 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β
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;