better-auth/cloudflare
specimen · 001tanstack-start

Auth on the edge,
wired in an afternoon.

A reference implementation of better-auth-cloudflare inside a TanStack Start app, deployed to Cloudflare Workers with D1 and KV. Everything you need to copy, learn, and ship.

§ 01 · contents

What this example ships with.

  • auth
    email + password, sessions signed from worker env
  • db
    drizzle orm against cloudflare d1
  • kv
    rate-limit state in a cloudflare kv namespace
  • routing
    protected routes via _authd layout in tanstack router
§ 02 · quick start

Four commands to local auth.

The full walkthrough lives in the README. This is the trail of breadcrumbs for people who learn by running things.

  1. 01
    Provision
    pnpm wrangler d1 create db·pnpm wrangler kv namespace create kv
  2. 02
    Generate
    pnpm generate:authgenerate:cf-typesgenerate:db
  3. 03
    Migrate
    pnpm migrate:dev
  4. 04
    Run
    pnpm devlocalhost:3000
Also needed in .env.local: BETTER_AUTH_SECRET, BETTER_AUTH_URL.
§ 03 · code map

Where to look first.

  • src/lib/auth.tsserver better-auth config · d1 · kv · cloudflare plugin
  • src/lib/auth-client.tsbrowser client
  • src/routes/api/auth/$.tscatch-all route → better-auth
  • src/components/sign-in-form.tsxexample forms
  • src/routes/_authd.tsxprotected layout