Aruthoth
Aruthoth
BABetter Auth
Created by Aruthoth on 12/9/2024 in #help
How to set up the database with drizzleAdapter + D1 using Hono on Cloudflare Workers
Hey folks, what's up? I'm creating an API with authentication that runs on Cloudflare Workers. Initially, I configured Hono, Drizzle, and D1. But now I'm facing some errors when implementing authentication with better-auth. Briefly, I'd like to know if anyone has successfully implemented something similar with these technologies. Initially, I couldn't set up the database because the Cloudflare Workers environment only provides access to D1 through the context of a request (as far as I could understand from the Cloudflare documentation). I tried to work around the problem by creating a function to encapsulate the creation of the auth object and pass the D1 through the context.
// src/lib/auth.ts
import type { Context } from 'hono'

import { betterAuth } from 'better-auth'
import { drizzleAdapter } from 'better-auth/adapters/drizzle'
import { openAPI } from 'better-auth/plugins'

import type { AppBindings } from '@/lib/types'

export function getAuth(c: Context<AppBindings>) {
return betterAuth({
plugins: [
openAPI(),
],
database: drizzleAdapter(c.env.DB, {
provider: 'sqlite',
usePlural: true,
}),
socialProviders: {
google: {
clientId: c.env.AUTH_GOOGLE_CLIENT_ID,
clientSecret: c.env.AUTH_GOOGLE_CLIENT_SECRET,
},
},
})
}
// src/lib/auth.ts
import type { Context } from 'hono'

import { betterAuth } from 'better-auth'
import { drizzleAdapter } from 'better-auth/adapters/drizzle'
import { openAPI } from 'better-auth/plugins'

import type { AppBindings } from '@/lib/types'

export function getAuth(c: Context<AppBindings>) {
return betterAuth({
plugins: [
openAPI(),
],
database: drizzleAdapter(c.env.DB, {
provider: 'sqlite',
usePlural: true,
}),
socialProviders: {
google: {
clientId: c.env.AUTH_GOOGLE_CLIENT_ID,
clientSecret: c.env.AUTH_GOOGLE_CLIENT_SECRET,
},
},
})
}
However, it only "works" when I use this function directly, for example: getAuth().api.someFunction(). When I try to authenticate through created routes, I get the error "Cannot read properties of undefined (reading 'DB')". It seems that just encapsulating the creation of the auth object was a terrible idea because somehow better-auth (I didn't get to see the internal code of better-auth) expects and searches for the reference to this object by the name auth from the auth.ts file.
32 replies