How to use Better Auth with Cloudflare D1?
How to use Better Auth with Cloudflare D1?
@Better Auth
29 Replies
You can integrate Better Auth with Cloudflare D1 by leveraging the community plugin and example projects that are already set up for this purpose. For example, there’s a sample project that demonstrates using Better Auth together with Hono and Cloudflare D1, which shows how to build an authentication API while handling some of Cloudflare D1’s unique binding requirements [1]. Additionally, the community plugin “better-auth-cloudflare” is designed to streamline this integration by supporting Cloudflare Workers, D1, and related tooling, including CLI commands for project generation and database migrations [2].
Keep in mind that because Cloudflare bindings (like D1) are only available within the context of an incoming request, you can’t initialize the auth instance using a global binding (for example, with process.env) outside the request context. Instead, you should use the context-specific method (such as using c.env in Hono) when handling requests. There are some known issues and workarounds documented when setting up Better Auth in serverless environments like Cloudflare Workers, so checking out the sample projects and related issues can help guide your implementation [3].
Let me know if you need any more help!
Sources:
[1] docs(example): add example project for Hono and D1 integration
[2] docs: add better-auth-cloudflare to community plugins
[3] Can't bind D1 Database on Hono with Cloudflare Workers
GitHub
Build software better, together
GitHub is where people build software. More than 150 million people use GitHub to discover, fork, and contribute to over 420 million projects.

GitHub
Build software better, together
GitHub is where people build software. More than 150 million people use GitHub to discover, fork, and contribute to over 420 million projects.

GitHub
better-auth/better-auth
The most comprehensive authentication framework for TypeScript - better-auth/better-auth
GitHub
docs(example): add example project for Hono and D1 integration by r...
I thought that the current documentation alone might not be sufficient for implementing an authentication API using Better Auth, Hono, and Cloudflare D1—especially since Cloudflare D1 has some uniq...
GitHub
docs: add better-auth-cloudflare to community plugins by zpg6 · Pu...
Summary by cubic
Add better-auth-cloudflare to the community plugins list in the docs. This surfaces the Cloudflare integration (Workers, D1, Hyperdrive, KV, R2, geolocation) and its CLI/migration ...
You could check out this repo: https://github.com/oscabriel/better-cloud
GitHub
GitHub - oscabriel/better-cloud: Better-Auth 🤝 Cloudflare
Better-Auth 🤝 Cloudflare. Contribute to oscabriel/better-cloud development by creating an account on GitHub.
@Better Auth how do i use kysely-d1 with better auth?
Better Auth supports any database dialect that Kysely supports—including Cloudflare D1 via the D1Dialect from the “kysely-d1” package [1]. However, note that if you’re running in a Cloudflare Workers environment, bindings (such as your D1 database) are only available inside the context of an inbound request. This means you can’t initialize your database outside a request as you might normally do on other platforms [2].
A common workaround is to set up your Better Auth instance so that it retrieves the D1 binding dynamically during each inbound request. For example, the OpenNext example project shows how to set up a dedicated bindings method to retrieve your D1 database context as needed, making it work seamlessly with Better Auth in a Workers environment [3].
In summary:
- Use the D1Dialect from “kysely-d1” to connect Better Auth with Cloudflare D1.
- If deploying on Cloudflare Workers, adjust your initialization to obtain the binding inside the request context (see the referenced example) to avoid binding issues.
I hope this helps! Let me know if you have any more questions.
Sources:
[1] Other Relational Databases | Better Auth
[2] Can't bind D1 Database on Hono with Cloudflare Workers
[3] docs(example): add example project for Hono and D1 integration
GitHub
better-auth/better-auth
The most comprehensive authentication framework for TypeScript - better-auth/better-auth
GitHub
Build software better, together
GitHub is where people build software. More than 150 million people use GitHub to discover, fork, and contribute to over 420 million projects.

Other Relational Databases | Better Auth
Integrate Better Auth with other relational databases.
GitHub
Can't bind D1 Database on Hono with Cloudflare Workers · Issue #20...
After some attempts, I couldn't find a way to bind a D1 Database to better-auth on a Hono app deployed to Cloudflare Workers. Following the official instructions, the installation step is commo...
@Better Auth im using kysely-d1 and astro, can you provide code snippets on how to do that?
Below is an example inspired by our Kysely/D1 integrations that you can adapt for an Astro app. In this snippet we create a Better Auth instance using the Kysely‑D1 dialect, then export it so you can use it in an Astro API endpoint (or other server logic):
Then, you can create an Astro API endpoint (for example, at src/pages/api/auth.ts) to delegate requests to Better Auth:
This approach follows our Kysely-based instantiation practices [4] and is similar to the Cloudflare Workers example using D1 [7]. Adjust the adapter settings as needed based on your environment and requirements. Enjoy integrating Better Auth with Astro!
GitHub
docs: add Kysely-based instantiation example to docs by daviduzondu...
Include TypeScript snippet demonstrating how to pass an existing Kysely db instance (with postgres dialect) into betterAuth, based on Kysely's getting‑started guide.
GitHub
better-auth/better-auth
The most comprehensive authentication framework for TypeScript - better-auth/better-auth
Sources:
[4] docs: add Kysely-based instantiation example to docs
[7] Can't bind D1 Database on Hono with Cloudflare Workers
GitHub
docs: add Kysely-based instantiation example to docs by daviduzondu...
Include TypeScript snippet demonstrating how to pass an existing Kysely db instance (with postgres dialect) into betterAuth, based on Kysely's getting‑started guide.
GitHub
Can't bind D1 Database on Hono with Cloudflare Workers · Issue #20...
After some attempts, I couldn't find a way to bind a D1 Database to better-auth on a Hono app deployed to Cloudflare Workers. Following the official instructions, the installation step is commo...
alright i think im almost there
@Better Auth when running
bunx @better-auth/cli generate i get an error
but i can't export an auth instance, because this is what i've got
but i cant have just an auth instance because it relies on context.runtime.env to have env.DB which cant be accessed from process.envIt looks like the CLI is having trouble reading your auth config because Better Auth currently requires a statically exported auth instance (or one exported as a variable named "auth") so that it can generate migrations. In your case, you’re using a dynamic factory (getAuth) that relies on Cloudflare runtime environment variables (like env.DB), which aren’t available globally at compile time [1].
A common workaround is to create a temporary auth config that uses placeholder values (for example, pulling from process.env) so that the CLI can read the configuration to generate the migrations. Then in your production code, you would wrap the auth initialization within a function (such as getAuth) that supplies the Cloudflare environment. This approach is similar to issues raised by others trying to use Better Auth on Cloudflare Workers, where the CLI’s constraints on static exports become a challenge [10][9].
Hope this helps clarify the situation!
Sources:
[1] Can't bind D1 Database on Hono with Cloudflare Workers
[9] Make the CLI generator more flexible (no need to read auth.ts)
[10] Not compatible with Cloudflare Workers or edge environments
GitHub
better-auth/better-auth
The most comprehensive authentication framework for TypeScript - better-auth/better-auth
GitHub
Can't bind D1 Database on Hono with Cloudflare Workers · Issue #20...
After some attempts, I couldn't find a way to bind a D1 Database to better-auth on a Hono app deployed to Cloudflare Workers. Following the official instructions, the installation step is commo...
GitHub
Make the CLI generator more flexible (no need to read auth.ts) · I...
Is this suited for github? Yes, this is suited for github Is your feature request related to a problem? Please describe. I want to generate better-auth schema for Drizzle + D1. But the way I write ...
GitHub
Not compatible with Cloudflare Workers or edge environments · Issu...
Is this suited for github? Yes, this is suited for github To Reproduce bun create hono@latest my-app (select workers template) Setup better-auth for hono follow official better-auth docs While sett...
@Better Auth can you give an example code snippet on how would i do that
Below is an example code snippet that shows how you could retrieve a user session from a request using Better Auth. This snippet assumes you have already configured your Better Auth instance (for example, in an "auth.ts" file):
In this example, when a GET request is made to the route, Better Auth uses the provided headers to check and retrieve the active user session [26]. This demonstrates basic usage and session management as outlined in our documentation [1], [26].
Sources:
[1] Introduction | Better Auth
[26] Basic Usage | Better Auth
Introduction | Better Auth
Introduction to Better Auth.
Basic Usage | Better Auth
Getting started with Better Auth
@Better Auth when running
bunx @better-auth/cli generate i get an error
but i can't export an auth instance, because this is what i've got
but i cant have just an auth instance because it relies on context.runtime.env to have env.DB which cant be accessed from process.env
please give me a full detailed solution to my problem with relevant code snippetsBelow is some background and a suggested solution. Better Auth expects a statically exported auth instance (or one named auth) for CLI commands like generate or migrate [1]. However, in Cloudflare Workers your D1 binding isn’t available globally (only per request via context), so doing something like this…
…means the CLI can’t find a ready-made auth instance to inspect, and you get an error such as:
The workaround is to create a separate configuration file for CLI usage. In that file you can import Better Auth and create a “static” auth instance using fallback values from (for example) process.env (or hardcoded/dummy values if needed)—even if those values will only be used for generating the schema/migrations. For example:
```ts
// src/lib/auth/cli.ts
import { betterAuth } from "better-auth";
import { Kysely } from "kysely";
import { D1Dialect } from "kysely-d1";
import type { D1Database } from "@cloudflare/workers-types";
// Use process.env for CLI usage (or provide dummy values)
const env = {
DB: process.env.DB, // note: for CLI purposes you might supply a fallback
BETTER_AUTH_SECRET: process.env.BETTER_AUTH_SECRET,
GITHUB_CLIENT_ID: process.env.GITHUB_CLIENT_ID,
GITHUB_CLIENT_SECRET: process.env.GITHUB_CLIENT_SECRET,
};
const db = new Kysely<any>({
dialect: new D1Dialect({
// For CLI generation, we use a static value.
database: env.DB as unknown as D1Database,
}),
});
const auth = betterAuth({
secret: env.BETTER_AUTH_SECRET,
database: {
db,
type: "sqlite", // or your actual target type
},
GitHub
better-auth/better-auth
The most comprehensive authentication framework for TypeScript - better-auth/better-auth
socialProviders: {
github: {
clientId: env.GITHUB_CLIENT_ID,
clientSecret: env.GITHUB_CLIENT_SECRET,
// Using a localhost redirect URI for development CLI purposes
redirectURI: "http://localhost:3000/api/auth/callback/github",
},
},
});
export default auth;
bunx @better-auth/cli generate --config ./src/lib/auth/cli.ts
``
This approach decouples your runtime Cloudflare environment (which requires dynamic access to c.env) from the build-time CLI process. You’re essentially using process.env (or fallback values) to supply the values your CLI needs in order to “read” the auth configuration.
In production you keep using your dynamic getAuth` function while for CLI generation you rely on a statically exported auth instance [1], [8]. This separation lets you generate the schema and run migrations without needing to access a Cloudflare Worker’s runtime context.
Sources:
[1] Can't bind D1 Database on Hono with Cloudflare Workers
[8] Not compatible with Cloudflare Workers or edge environmentsGitHub
better-auth/better-auth
The most comprehensive authentication framework for TypeScript - better-auth/better-auth
GitHub
better-auth/better-auth
The most comprehensive authentication framework for TypeScript - better-auth/better-auth
GitHub
Can't bind D1 Database on Hono with Cloudflare Workers · Issue #20...
After some attempts, I couldn't find a way to bind a D1 Database to better-auth on a Hono app deployed to Cloudflare Workers. Following the official instructions, the installation step is commo...
GitHub
Not compatible with Cloudflare Workers or edge environments · Issu...
Is this suited for github? Yes, this is suited for github To Reproduce bun create hono@latest my-app (select workers template) Setup better-auth for hono follow official better-auth docs While sett...
in that case i either cant use better auth or d1
why cant better-auth just work with d1 😭
what is the issue?
hi
i cant use
bunx @better-auth/cli generate with cloudflare d1 because it's passed as context.runtime.env.DB from the request so it's not avaialbe at build time
https://discord.com/channels/1288403910284935179/1416707955423711363/1416830170588905672you can make an endpoint that's called like
/migrate and use this code snippet and whenever you visit that endpoint, the schema will be updated
ok, will try
I've done it like this for now:
and im getting an error
D1_ERROR: not authorized: SQLITE_AUTH like this, when visiting my migrate endpoint:
this https://discord.com/channels/1288403910284935179/1315770998846390312/1315770998846390312 might be related
or https://discord.com/channels/1288403910284935179/1356036282341523546/1356036282341523546
logs with --verbose flag
Is it caused by better auth or by kysely-d1 ?@bekacru what would be the best solution in this case?
https://chatgpt.com/s/t_68c87b6cb06c8191ab22f514f1ef84c0
should i try using drizzle again instead of kysely-d1?
@Better Auth
Based on recent improvements in the Drizzle adapter, it might be worth giving Drizzle another try—especially since recent fixes have addressed issues like type conversions for sqlite/D1 and OAuth-related date handling [1], [12]. If your project uses Cloudflare D1 and you’ve encountered challenges with kysely-d1, the updated Drizzle adapter could provide a smoother experience. Of course, it always depends on your specific requirements and how your schema or database features map to the adapter’s capabilities.
Sources:
[1] Transform sqlite values in Drizzle adapter.
[12] fix: oauth failing when using drizzle adapter
GitHub
Build software better, together
GitHub is where people build software. More than 150 million people use GitHub to discover, fork, and contribute to over 420 million projects.

GitHub
Transform sqlite values in Drizzle adapter. by RyanNieuwoudt · Pul...
Not sure whether this is considered a fix or a new feature, depending on whether better-auth officially supports sqlite via drizzle-adapter. In this configuration, authentication does not work. Ins...
GitHub
fix: oauth failing when using drizzle adapter by focux · Pull Requ...
This PR addresses an issue with the Drizzle adapter where OAuth providers were failing due to incorrect date format handling. The fix removes the .toISOString() call on the Date object when doing v...
@Better Auth i've switched to drizzle but i get this error now:
my code:
pages/migrate.ts
lib/auth.ts
lib/db.ts
It looks like you're hitting an issue because the migration method (getMigrations) is only supported when using the Kysely adapter. With the Drizzle adapter you’re using, Better Auth will default to sqlite if it can’t determine the type and doesn’t support automated migrations via getMigrations. Instead, you should use the CLI’s generate command to create the schema (and migration files) manually [1][2].
For example, with Drizzle you can run:
npx @better-auth/cli@latest generate
Then, if needed, generate and apply migrations using your ORM’s migration tools (like drizzle-kit). This workflow is required because the built-in migration support only works out of the box with the Kysely adapter.
Let me know if you have any more questions!
Sources:
[1] Drizzle ORM Adapter | Better Auth
[2] Installation | Better Auth
Drizzle ORM Adapter | Better Auth
Integrate Better Auth with Drizzle ORM.
Installation | Better Auth
Learn how to configure Better Auth in your project.
@Better Auth i cannot use
bunx @better-auth/cli generate because it expects an exported auth instance which is not possible with a d1 dbHi there! This is a known limitation with the current CLI. Because a D1 database binding relies on a runtime context (for example, in a Cloudflare Workers or Hono setup), it isn’t possible to have a static exported auth instance that the CLI expects to find [5].
A common workaround is to create a temporary auth configuration that exports a static instance—perhaps using a mock or alternative static connection—solely for running the CLI commands (using the --config flag if needed). This way, you can generate your schema or migration file without needing the dynamic context that D1 requires in production. We're aware of this limitation and are exploring improvements to make the CLI more flexible with dynamic configurations [18].
Let me know if you have any more questions or need further assistance!
Sources:
[5] Can't bind D1 Database on Hono with Cloudflare Workers
[18] Make the CLI generator more flexible (no need to read auth.ts)
GitHub
better-auth/better-auth
The most comprehensive authentication framework for TypeScript - better-auth/better-auth
GitHub
better-auth/better-auth
The most comprehensive authentication framework for TypeScript - better-auth/better-auth
GitHub
Can't bind D1 Database on Hono with Cloudflare Workers · Issue #20...
After some attempts, I couldn't find a way to bind a D1 Database to better-auth on a Hono app deployed to Cloudflare Workers. Following the official instructions, the installation step is commo...
GitHub
Make the CLI generator more flexible (no need to read auth.ts) · I...
Is this suited for github? Yes, this is suited for github Is your feature request related to a problem? Please describe. I want to generate better-auth schema for Drizzle + D1. But the way I write ...
When it comes to using the CLI while also using a D1 DB I recommend just making a fake auth instance in a separate file just for this, and not actually give it a real DB but still use the drizzle adapter
I was looking at the link you sent earlier and there they did it like this
https://github.com/oscabriel/better-cloud/blob/main/src/server/db/index.ts
GitHub
better-cloud/src/server/db/index.ts at main · oscabriel/better-cloud
Better-Auth 🤝 Cloudflare. Contribute to oscabriel/better-cloud development by creating an account on GitHub.
and i have also tried doing that earlier
but it looks like astro has a bug with it
https://community.cloudflare.com/t/failed-to-import-env-from-cloudflare-workers-in-astro-project/834068
i've asked in astro discord, i will see what they say
this might work i guess actually with drizzle instead of kysely-d1
https://discord.com/channels/1288403910284935179/1349399814013718538/1349399814013718538
I have this working
@Roman
you need to use Kysely

