Skip to content

Wire better-auth onto D1 via better-auth-cloudflare - #123

Merged
soorya-u merged 11 commits into
mainfrom
issue-110-better-auth-d1
Jul 26, 2026
Merged

Wire better-auth onto D1 via better-auth-cloudflare#123
soorya-u merged 11 commits into
mainfrom
issue-110-better-auth-d1

Conversation

@soorya-u

@soorya-u soorya-u commented Jul 25, 2026

Copy link
Copy Markdown
Owner

Summary

  • Cut better-auth persistence onto the Worker DB D1 binding via better-auth-cloudflare's withCloudflare() helper (plugins unchanged)
  • Pin better-auth-cloudflare to exact 0.3.1 and drop the Neon-only auth schema now that auth tables live on SQLite/D1
  • Add a Workers-pool device-authorization flow test against real D1 (migrations applied in setup)

Closes #110.

Test plan

Made with Cursor

Summary by CodeRabbit

  • New Features

    • Added Cloudflare D1 support for authentication, including local and remote database configurations.
    • Added automated D1 migration handling.
    • Added device authorization flow coverage for sign-in, approval, and token issuance.
    • Added shared authentication configuration supporting OAuth, device authorization, bearer tokens, and related flows.
  • Refactor

    • Replaced the previous database-backed authentication setup with the D1-based configuration.
    • Centralized database environment validation and authentication settings.
  • Tests

    • Expanded end-to-end authentication testing in the Cloudflare environment.

soorya-u and others added 2 commits July 25, 2026 11:17
Cut auth persistence off Neon so the device-authorization flow runs
against the Worker D1 binding, with plugins unchanged and the wrapper
pinned to an exact version.

Co-authored-by: Cursor <cursoragent@cursor.com>
Treat the Workers migration setup as an entry, ignore the vitest
relative setup path knip can't resolve from the repo root, and mark
the better-auth CLI export as public API.

Co-authored-by: Cursor <cursoragent@cursor.com>
@vercel

vercel Bot commented Jul 25, 2026

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
cyrus Ready Ready Preview, Comment Jul 26, 2026 6:19am

@coderabbitai

coderabbitai Bot commented Jul 25, 2026

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@soorya-u, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 56 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 08595307-746e-471f-871e-790258f9bb84

📥 Commits

Reviewing files that changed from the base of the PR and between 0e8a9d4 and 52b2fcd.

📒 Files selected for processing (3)
  • apps/server/src/auth/options.ts
  • apps/server/tsconfig.json
  • knip.json
📝 Walkthrough

Walkthrough

Better Auth is migrated from Neon/Postgres to Cloudflare D1. Database environment validation, Drizzle configuration, generated auth models, migration application, shared auth options, CLI wiring, worker test setup, and device authorization coverage are updated.

Changes

D1-backed Better Auth

Layer / File(s) Summary
D1 environment and migration runtime
apps/server/src/db/env.ts, apps/server/src/config/env.ts, apps/server/drizzle.config.ts, apps/server/src/db/migrations/*, apps/server/.env.example
Database configuration now validates local or complete remote D1 credentials, selects the matching Drizzle driver, and applies parsed migrations to env.DB.
D1 auth runtime and model wiring
apps/server/src/auth/*, apps/server/src/db/models/index.ts, apps/server/src/db/neon/*, apps/server/package.json
Authentication uses withCloudflare with D1 and consolidated auth models; shared options and a CLI instance are added, while the Neon client and schema are removed.
Device authorization and worker test integration
apps/server/src/auth/index.test.ts, vitest.config.ts, apps/server/tsconfig.json, knip.json
Worker tests apply D1 migrations and cover signup, session validation, device approval, and token exchange; test entries, typings, bindings, and analysis configuration are updated.

Estimated code review effort: 4 (Complex) | ~45 minutes

Possibly related issues

Possibly related PRs

  • soorya-u/cyrus#5 — Adds the device authorization models, migrations, and plugins exercised by this PR’s end-to-end flow.
  • soorya-u/cyrus#120 — Establishes related D1 binding and database/auth wiring that this PR completes with withCloudflare.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main change: wiring better-auth to D1 through better-auth-cloudflare.
Linked Issues check ✅ Passed The PR meets #110 by moving auth tables off Neon, wiring better-auth through withCloudflare on D1, pinning better-auth-cloudflare, and adding an end-to-end device-flow test.
Out of Scope Changes check ✅ Passed The additional config, migration, and test updates support the D1 auth cutover and do not introduce unrelated changes.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch issue-110-better-auth-d1

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@soorya-u soorya-u changed the title Wire better-auth onto D1 via better-auth-cloudflare (#110) Wire better-auth onto D1 via better-auth-cloudflare Jul 25, 2026
Resolve conflicts after the application-data D1 cutover (#109/#122): keep
auth on withCloudflare+D1, drop the Neon auth leftovers, and refresh
tooling comments now that both paths use D1.

Co-authored-by: Cursor <cursoragent@cursor.com>
Comment thread apps/server/src/auth/index.test.ts Outdated
Comment thread apps/server/src/auth/index.ts Outdated
Comment thread apps/server/src/db/apply-migrations.ts Outdated
Comment thread apps/server/src/middleware/logging.ts Outdated
Comment thread apps/server/src/index.ts Outdated
Comment thread apps/server/.env.example Outdated
Comment thread package.json Outdated
Comment thread package.json Outdated
…ocal.

Pin better-auth-cloudflare / drizzle-adapter on @cyrus/server only, type
authOptions with BetterAuthOptions, and drop the noisy .env.example notes.

Co-authored-by: Cursor <cursoragent@cursor.com>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (1)
apps/server/tsconfig.json (1)

6-7: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Verify bun types are actually needed before keeping them with Workers test types.

apps/server targets Cloudflare Workers, and the added @cloudflare/vitest-pool-workers/types provide the test globals. "bun" is only necessary if code explicitly relies on Bun APIs or bun:test; otherwise it can introduce unnecessary runtime typings and potential global overlap.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/server/tsconfig.json` around lines 6 - 7, Review the apps/server
TypeScript configuration and remove "bun" from the types array unless the server
code explicitly uses Bun APIs or bun:test; retain
`@cloudflare/vitest-pool-workers/types` for Workers test globals.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@apps/server/src/auth/index.ts`:
- Around line 84-96: Replace the db: db as never workaround in the
withCloudflare configuration with a compatible adapter integration: upgrade/use
the newer `@better-auth/drizzle-adapter` 1.7+ path or switch to the
provider-backed D1 adapter so the workspace’s drizzle-orm version is supported.
Remove the never cast while preserving the existing schema and transaction
options.

In `@knip.json`:
- Line 6: Move the ignore configuration from the root knip settings into the
apps/server configuration, and change it to match the actual unresolved import
specifier used by the server migration code rather than a file path. Do not use
ignoreUnresolved for suppressing the file itself; use the appropriate file-level
ignore setting if that is the intended behavior.

---

Nitpick comments:
In `@apps/server/tsconfig.json`:
- Around line 6-7: Review the apps/server TypeScript configuration and remove
"bun" from the types array unless the server code explicitly uses Bun APIs or
bun:test; retain `@cloudflare/vitest-pool-workers/types` for Workers test globals.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: e6e6fb5d-db7c-4fa4-bacc-9bb35e0ee261

📥 Commits

Reviewing files that changed from the base of the PR and between db3409f and 32f6967.

⛔ Files ignored due to path filters (1)
  • bun.lock is excluded by !**/*.lock
📒 Files selected for processing (13)
  • apps/server/.env.example
  • apps/server/drizzle.config.ts
  • apps/server/package.json
  • apps/server/src/auth/index.test.ts
  • apps/server/src/auth/index.ts
  • apps/server/src/db/apply-migrations.ts
  • apps/server/src/db/neon/index.ts
  • apps/server/src/db/neon/schema.ts
  • apps/server/src/index.ts
  • apps/server/src/middleware/logging.ts
  • apps/server/tsconfig.json
  • knip.json
  • vitest.config.ts
💤 Files with no reviewable changes (2)
  • apps/server/src/db/neon/index.ts
  • apps/server/src/db/neon/schema.ts

Comment thread apps/server/src/auth/index.ts Outdated
Comment thread knip.json Outdated
One Worker D1 binding means a WeakMap keyed by database was overkill.

Co-authored-by: Cursor <cursoragent@cursor.com>
Drop getAuth; bind better-auth to env.DB at module scope and move the
CLI generate config to auth/cli.ts so Node can still load it.

Co-authored-by: Cursor <cursoragent@cursor.com>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@apps/server/src/auth/options.ts`:
- Around line 39-46: The logger callback’s object construction incorrectly
spreads the variadic args array into numeric-keyed properties. Update the
logger.log implementation to preserve the message while handling extra args as
meaningful structured metadata, using the existing log[level] call and the
callback’s `(level, message, ...args)` contract.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: e54b64da-ea6c-4bfd-8ad8-0b51b16b0aea

📥 Commits

Reviewing files that changed from the base of the PR and between 32f6967 and a72dc5e.

📒 Files selected for processing (5)
  • apps/server/package.json
  • apps/server/src/auth/cli.ts
  • apps/server/src/auth/index.ts
  • apps/server/src/auth/options.ts
  • knip.json
🚧 Files skipped from review as they are similar to previous changes (2)
  • knip.json
  • apps/server/package.json

Comment thread apps/server/src/auth/options.ts
soorya-u and others added 2 commits July 26, 2026 11:21
Read nested Drizzle migration files via Vite glob in the Workers setup file instead of binding them from vitest.config, and tidy the auth schema wiring.

Co-authored-by: Cursor <cursoragent@cursor.com>
Split Cloudflare kit vars into db/env with a discriminated final schema and wire drizzle-kit plus app env through it.

Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
Pass better-auth logger extras as an args array instead of spreading, drop unused Bun types from the server tsconfig, and scope the Vitest setup-file Knip ignore to the root workspace.

Co-authored-by: Cursor <cursoragent@cursor.com>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
apps/server/src/config/env.ts (1)

3-30: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Make DATABASE_URL optional on startup, and only require it for Neon-backed health checks.

apps/server/src/index.ts imports ./middleware/index, which pulls in corsMiddleware, partyserverMiddleware, and auth modules that all import the composed config; therefore DATABASE_URL is still validated during Worker startup when D1-only environments do not provide it.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/server/src/config/env.ts` around lines 3 - 30, Update the composed env
schema in createEnv and the imported dbEnv configuration so DATABASE_URL is
optional during startup, then add validation at the Neon-backed health-check
boundary to require it before use. Preserve D1-only startup without DATABASE_URL
and ensure Neon health checks still fail clearly when the value is missing.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@apps/server/src/config/env.ts`:
- Around line 3-30: Update the composed env schema in createEnv and the imported
dbEnv configuration so DATABASE_URL is optional during startup, then add
validation at the Neon-backed health-check boundary to require it before use.
Preserve D1-only startup without DATABASE_URL and ensure Neon health checks
still fail clearly when the value is missing.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 6d5195a1-0915-44f3-97f7-18a9bda66574

📥 Commits

Reviewing files that changed from the base of the PR and between a72dc5e and 0e8a9d4.

📒 Files selected for processing (10)
  • apps/server/drizzle.config.ts
  • apps/server/src/auth/cli.ts
  • apps/server/src/auth/index.test.ts
  • apps/server/src/auth/index.ts
  • apps/server/src/config/env.ts
  • apps/server/src/db/env.ts
  • apps/server/src/db/migrations/apply.ts
  • apps/server/src/db/models/index.ts
  • knip.json
  • vitest.config.ts
🚧 Files skipped from review as they are similar to previous changes (3)
  • apps/server/src/auth/cli.ts
  • apps/server/src/auth/index.ts
  • apps/server/src/auth/index.test.ts

@soorya-u
soorya-u merged commit a888d6d into main Jul 26, 2026
9 checks passed
@soorya-u
soorya-u deleted the issue-110-better-auth-d1 branch July 26, 2026 06:21
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Cut better-auth over to D1 via better-auth-cloudflare

1 participant