How to use better-auth CLI in a Cloudflare workers + Cloudflare D1 + react-router + drizzle project?
I created a React Router 7 project using the Cloudflare workers template:
The Problem:
I am struggling to find a pattern where I can somehow export
The crux is that
The question is: is there a work around to this? I can't be the first to run into this little puzzle. Let me know any ideas!
Note: I am aware of a way to import the
pnpm create cloudflare@latest my-react-router-app --framework=react-router . I added D1 bindings and drizzle to this project.The Problem:
I am struggling to find a pattern where I can somehow export
auth in a way the CLI can pick up.The crux is that
betterAuth() requires the db instance as a function argument. In Cloudlfare workers, however, the db instance is only available in the fetch() function. So logically the only spot I can instance the drizzle ORM db instance, and thus the betterAuth instance, is within the fetch function scope.The question is: is there a work around to this? I can't be the first to run into this little puzzle. Let me know any ideas!
Note: I am aware of a way to import the
env globally by import { env } from "cloudflare:workers";, however this package is only available in a Cloudflare or Miniflare environment. Ref: https://developers.cloudflare.com/changelog/2025-03-17-importable-env/Solution
I recommend making a fake auth file and a real auth file.
The fake one is just your better-auth config except for any fields which require ENV vars.
This file will be the one you would then use for the better-auth cli to read.
The real one would be the one which includes all needed ENV variables for Better Auth to function.
Tip: Make a config which you can export and use between the both of the real & fake auth files, to keep things consistent - and of course, this excludes the ENV parts in this config.
The fake one is just your better-auth config except for any fields which require ENV vars.
This file will be the one you would then use for the better-auth cli to read.
The real one would be the one which includes all needed ENV variables for Better Auth to function.
Tip: Make a config which you can export and use between the both of the real & fake auth files, to keep things consistent - and of course, this excludes the ENV parts in this config.
