Skip to main content

@auth/d1-adapter

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

Warning​

This adapter is not developed or maintained by Clouflare 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

D1Database​

D1Database: WorkerDatabase | MiniflareD1Database


D1Adapter()​

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 init.ts for the relevant sql. Paste and run the SQL into your D1 dashboard query tool.

D1Adapter(db: D1Database): Adapter

Parameters​

ParameterType
dbD1Database

Returns​

Adapter


up()​

up(db: D1Database): Promise<void>

Parameters​

ParameterType
dbD1Database

Returns​

Promise<void>