
转载于https://mp.weixin.qq.com/s/li5dsD1kXu6LFMT71bd3AQ准备工作创建hono项目lixiaobolixiaobodeMacBook-Pro cloudflare %npmcreate hononpxcreate-hono create-hono version0.19.4 ✔ **Target directory** better-auth-cloudflare-demo ✔ **Which templatedoyou want to use?** cloudflare-workers ✔ **Do you want toinstallproject dependencies?** Yes ✔ **Which package managerdoyou want to use?**npm✔ Cloning the template ✔ Installing project dependencies **Copied project files** Get started with: **cd better-auth-cloudflare-demo**安装依赖npminstallbetter-auth在.dev.vars文件中配置SECRET_KEY_V1可以在https://better-auth.com/docs/installation里面点击Generate Secret按钮生成也可以使用openssl rand -base64 32生成编写sql文件better-auth需要User、Session、Account和Verification四张表可以使用npx better-auth/cli generate生成也可以在https://better-auth.com/docs/concepts/database#core-schema 手动拷贝SQLite版本的代码CREATETABLEIFNOTEXISTSuser(idtextNOTNULLPRIMARYKEY,nametextNOTNULL,emailtextNOTNULLUNIQUE,emailVerifiedintegerNOTNULL,imagetext,createdAtdateNOTNULL,updatedAtdateNOTNULL);CREATETABLEIFNOTEXISTSsession(idtextNOTNULLPRIMARYKEY,userIdtextNOTNULL,tokentextNOTNULLUNIQUE,expiresAtdateNOTNULL,ipAddresstext,userAgenttext,createdAtdateNOTNULL,updatedAtdateNOTNULL,FOREIGNKEY(userId)REFERENCESuser(id)ONDELETECASCADE);CREATETABLEIFNOTEXISTSaccount(idtextNOTNULLPRIMARYKEY,userIdtextNOTNULL,accountIdtextNOTNULL,providerIdtextNOTNULL,accessTokentext,refreshTokentext,accessTokenExpiresAtdate,refreshTokenExpiresAtdate,scopetext,idTokentext,passwordtext,createdAtdateNOTNULL,updatedAtdateNOTNULL,FOREIGNKEY(userId)REFERENCESuser(id)ONDELETECASCADE);CREATETABLEIFNOTEXISTSverification(idtextNOTNULLPRIMARYKEY,identifiertextNOTNULL,valuetextNOTNULL,expiresAtdateNOTNULL,createdAtdateNOTNULL,updatedAtdateNOTNULL);* 创建本地数据库 * 编辑wrangler.jsonc文件添加d1_databases相关信息本地运行的时候不存在“database_id”可以将其填为“00000000-0000-0000-0000-000000000000”线上运行的时候按照真实填写 jsond1_databases:[{binding:DB,database_name:better-auth-cloudflare-demo,database_id:}]* 将上面的sql语句保存在better-auth-cloudflare-demo.sql文件里面并执行如下命令 shell lixiaobolixiaobodeMacBook-Pro better-auth-cloudflare-demo%wrangler d1executebetter-auth-cloudflare-demo--local --filebetter-auth-cloudflare-demo.sql▲[WARNING]**Proxy environment variables detected.Well use your proxy for fetch requests.** ⛅️ wrangler 4.106.0 ──────────────────── **Resource location:** local Use --remote if you want to access the remote instance. Executing on local database better-auth-cloudflare-demo () from .wrangler/state/v3/d1: To execute on your remote database, add a --remote flag to your wrangler command. 4 commands executed successfully. * 查看数据库是否生成成功 * npx localflare * webstrom * wrangler shell lixiaobolixiaobodeMacBook-Pro better-auth-cloudflare-demo % npx wrangler d1 execute DB --local --commandSELECT name FROM sqlite_master WHERE typetable; ▲ [WARNING] **Proxy environment variables detected. Welluseyour proxyforfetchrequests.**⛅️ wrangler4.110.0────────────────────**Resource location:**localUse--remote if you want to access the remote instance. ExecutingonlocaldatabaseDB()from.wrangler/state/v3/d1: Toexecuteonyour remotedatabase,adda--remote flag to your wrangler command.1command executed successfully.┌──────────────┐ │ name │ ├──────────────┤ │user│ ├──────────────┤ │session│ ├──────────────┤ │ account │ ├──────────────┤ │ verification │ ├──────────────┤ │ _cf_METADATA生成worker-configuration.d.tswrangler types编写代码src/lib/auth.tsimport{betterAuth}frombetter-authexportconstcreateAuth(env:Cloudflare.Env)betterAuth({database:env.DB,emailAndPassword:{enabled:true,},secrets:[{version:1,value:env.SECRET_KEY_V1},],basePath:/api/auth,baseURL:{allowedHosts:[localhost:*,],protocol:auto,},});exporttypeAuthInstanceReturnTypetypeofcreateAuth;exporttypeSessionUserAuthInstance[$Infer][Session][user];创建路由src/routes/user.tsimport{Hono}fromhonoimport{createAuth,SessionUser}from../lib/auth;exportconstauthRouternewHono{Bindings:Cloudflare.Env,Variables:{user?:SessionUser}}();exportconstAuthRouterPrefix/api/auth;// GET/POST /user/auth/*authRouter.all(/*,(c){constauthcreateAuth(c.env);returnauth.handler(c.req.raw);});// middleware: /user/*authRouter.use(/*,async(c,next){constauthcreateAuth(c.env);constsessionawaitauth.api.getSession({headers:c.req.raw.headers});c.set(user,session?.user);awaitnext();});// GET /api/meauthRouter.get(/me,async(c){if(!c.get(user)){returnc.json({error:unauthorized},401);}returnc.json(c.get(user)!);});src/index.tsimport{Hono}fromhonoimport{createAuth,SessionUser}from./lib/auth;import{authRouter,AuthRouterPrefix}from./routes/authconstappnewHono{Bindings:Cloudflare.Env,Variables:{user?:SessionUser}}()app.route(AuthRouterPrefix,authRouter);console.log( 当前可用的 API 端点列表 );app.routes.forEach(rconsole.log([${r.method}].padEnd(8)r.path));console.log();exportdefaultapp运行和测试本地运行shell wrangler dev 测试注册lixiaobolixiaobodeMacBook-Pro better-auth-cloudflare-demo %curl-XPOST http://localhost:8787/api/auth/sign-up/email\-HContent-Type: application/json\-d{email:testexample.com,password:12345678,name:test}{token:OS57FCQgo9n3maerb7kKoXfD2RNwGBDK,user:{name:test,email:testexample.com,emailVerified:false,image:null,createdAt:2026-07-10T11:10:23.856Z,updatedAt:2026-07-10T11:10:23.856Z,id:cvdFAOWgxn6PMd3WD51pMUQoaDW6iw2F}}登录lixiaobolixiaobodeMacBook-Pro better-auth-cloudflare-demo %curl-sS\-XPOST http://localhost:8787/api/auth/sign-in/email\-HContent-Type: application/json\-d{email:testexample.com,password:12345678}{redirect:false,token:Var3ENBaJGZj4VQrpNzwta1cTtbxbUna,user:{name:test,email:testexample.com,emailVerified:false,image:null,createdAt:2026-07-10T11:10:23.856Z,updatedAt:2026-07-10T11:10:23.856Z,id:cvdFAOWgxn6PMd3WD51pMUQoaDW6iw2F}}错误密码登录lixiaobolixiaobodeMacBook-Pro better-auth-cloudflare-demo %curl-sS\-XPOST http://localhost:8787/api/auth/sign-in/email\-HContent-Type: application/json\-d{email:testexample.com,password:password123}{message:Invalid email or password,code:INVALID_EMAIL_OR_PASSWORD}不存在的用户登录lixiaobolixiaobodeMacBook-Pro better-auth-cloudflare-demo %curl-sS\-XPOST http://localhost:8787/api/auth/sign-in/email\-HContent-Type: application/json\-d{email:nobodyexample.com,password:password123}{message:Invalid email or password,code:INVALID_EMAIL_OR_PASSWORDcloudflare运行生成线上数据库创建数据库lixiaobolixiaobodeMacBook-Pro better-auth-cloudflare-demo % wrangler d1 create better-auth-cloudflare-demo ▲[WARNING]**Proxy environment variables detected. Well use your proxy for fetch requests.** ⛅️ wrangler 4.106.0 (update available 4.110.0) ─────────────────────────────────────────────── ✅ Successfully created DB better-auth-cloudflare-demoinregion WNAM Created your new D1 database. To access your new D1 Databaseinyour Worker,addthe following snippet to your configuration file:{d1_databases:[{binding:better_auth_cloudflare_demo,database_name:better-auth-cloudflare-demo,database_id:25b30dd3-b35d-45fa-9fa9-7c2af8240024}]}✔ **Would you like Wrangler toaddit on your behalf?** …yes✔ **What binding name would you like to use?** … better_auth_cloudflare_demo ✔ **Forlocaldev,doyou want to connect to the remote resource instead of alocalresource?** …yes将返回d1_databases信息贴到wrangler.jsonc文件对应位置(默认应该会自动更新wrangler.jsonc无须手动粘贴)创建表lixiaobolixiaobodeMacBook-Pro better-auth-cloudflare-demo % wrangler d1 execute better-auth-cloudflare-demo--remote--file./better-auth-cloudflare-demo.sql ▲[WARNING]**Proxy environment variables detected. Well use your proxyforfetch requests.** ⛅️ wrangler4.106.0(update available4.110.0)─────────────────────────────────────────────── **Resource location:** remote ✔ **⚠️ This process may take some time, duringwhichyour D1 database will be unavailable to serve queries.** **Ok to proceed?** …yes Executing on remote database better-auth-cloudflare-demo(25b30dd3-b35d-45fa-9fa9-7c2af8240024): To execute on yourlocaldevelopment database, remove the--remoteflag from your wrangler command. Note:ifthe execution fails to complete, your DB willreturnto its original state and you can safely retry. ├ Uploading 25b30dd3-b35d-45fa-9fa9-7c2af8240024.f838ba309bc50ebd.sql │ Uploading complete. │ Starting import... Processed4queries. Executed4queriesin5.36ms(4rows read,14rows written)Database is currently at bookmark 00000001-00000006-000050a4-51499d332507084e452c9586ed6634a2. ┌───────────────────────┬───────────┬──────────────┬───────────────────┐ │Total queries executed │ Rowsread│ Rows written │ Database size(MB)│ ├───────────────────────┼───────────┼──────────────┼───────────────────┤ │4 │4│14│0.05│ └───────────────────────┴───────────┴──────────────┴───────────────────┘发布到线上也可以使用自己的域名lixiaobolixiaobodeMacBook-Pro better-auth-cloudflare-demo % wrangler deploy ▲[WARNING]**Proxy environment variables detected. Well use your proxyforfetch requests.** ⛅️ wrangler4.106.0(update available4.110.0)─────────────────────────────────────────────── Total Upload:1759.21KiB / gzip:304.34KiB Worker Startup Time:47ms Your Worker has access to the following bindings: Binding Resource env.better_auth_cloudflare_demo(better-auth-cloudflare-demo)D1 Database env.BETTER_AUTH_URL(localhost)Environment Variable Uploaded better-auth-cloudflare-demo(5.12sec)Deployed better-auth-cloudflare-demo triggers(1.95sec)https://better-auth-cloudflare-demo.shakingwaves.workers.dev Current Version ID: 2fb6c9de-4448-4954-9209-81ab9402e908修改wrangler.jsonc中BETTER_AUTH_URL为https://better-auth-cloudflare-demo.shakingwaves.workers.dev之后再次发布将本地.dev.vars里的密钥注入云端密文库lixiaobolixiaobodeMacBook-Pro better-auth-cloudflare-demo % wrangler secret put SECRET_KEY_V1 ▲[WARNING]**Proxy environment variables detected. Well use your proxyforfetch requests.** ⛅️ wrangler4.106.0(update available4.110.0)─────────────────────────────────────────────── ✔ **Enter a secret value:** … ******************************** Creating the secretforthe Workerbetter-auth-cloudflare-demo✨ Success!Uploaded secret SECRET_KEY_V1测试以此类推lixiaobolixiaobodeMacBook-Pro better-auth-cloudflare-demo %curl-XPOST https://better-auth-cloudflare-demo.shakingwaves.workers.dev/api/auth/sign-up/email-HContent-Type: application/json-d{email:testexample.com,password:12345678,name:test}{token:IBHF3ATPz4akhtFc05AqXgevqpkvq4Vn,user:{name:test,email:testexample.com,emailVerified:false,image:null,createdAt:2026-07-10T12:05:30.596Z,updatedAt:2026-07-10T12:05:30.596Z,id:tDVU8UApXsLcm8OZqeXJ6VtH3PZu1ena}}curl-sS-XPOST https://better-auth-cloudflare-demo.shakingwaves.workers.dev/api/auth/sign-in/email-HContent-Type: application/json-d{email:testexample.com,password:12345678}{redirect:false,token:nZNqQpSCzDWFwwJ1gCaokeYAgM5uxWOa,user:{name:test,email:testexample.com,emailVerified:false,image:null,createdAt:2026-07-10T12:05:30.596Z,updatedAt:2026-07-10T12:05:30.596Z,id:tDVU8UApXsLcm8OZqeXJ6VtH3PZu1ena}}