Appearance
Cloudflare 上的 Better Auth
¥Better Auth on Cloudflare
一个基于 TypeScript 的轻量级身份验证服务,针对 Cloudflare Workers 进行了优化
¥A TypeScript-based lightweight authentication service optimized for Cloudflare Workers
技术栈概览
¥Stack Summary
🔥 Hono 一个基于 Web 标准构建的快速、轻量级 Web 框架。
¥🔥 Hono\ A fast, lightweight web framework built on web standards.
🔒 Better Auth 一个全面的 TypeScript 身份验证框架。
¥🔒 Better Auth\ A comprehensive authentication framework for TypeScript.
🧩 Drizzle ORM 一个轻量级、高性能的 TypeScript ORM,以开发者体验 (DX) 为核心构建。
¥🧩 Drizzle ORM\ A lightweight, high-performance ORM for TypeScript, built with DX in mind.
🐘 Postgres 与 Neon 一个针对云环境优化的无服务器 Postgres 数据库。
¥🐘 Postgres with Neon\ A serverless Postgres optimized for the cloud.
准备工作
¥Preparation
1. 安装
¥ Installation
sh
# Hono
# > Select cloudflare-workers template
npm create hono
# Better Auth
npm install better-auth
# Drizzle ORM
npm install drizzle-orm
npm install --save-dev drizzle-kit
# Neon
npm install @neondatabase/serverlesssh
# Hono
# > Select cloudflare-workers template
pnpm create hono
# Better Auth
pnpm add better-auth
# Drizzle ORM
pnpm add drizzle-orm
pnpm add -D drizzle-kit
# Neon
pnpm add @neondatabase/serverlesssh
# Hono
# > Select cloudflare-workers template
yarn create hono
# Better Auth
yarn add better-auth
# Drizzle ORM
yarn add drizzle-orm
yarn add --dev drizzle-kit
# Neon
yarn add @neondatabase/serverlesssh
# Hono
# > Select cloudflare-workers template
bun create hono
# Better Auth
bun add better-auth
# Drizzle ORM
bun add drizzle-orm
bun add -d drizzle-kit
# Neon
bun add @neondatabase/serverless2. 环境变量
¥ Environment Variables
设置以下环境变量,将你的应用连接到 Better Auth 和 Neon。
¥Set the following environment variables to connect your application to Better Auth and Neon.
参考官方指南:
¥Refer to official guides:
所需文件:
¥Required Files:
Plain
# Used by Wrangler in local development
# In production, these should be set as Cloudflare Worker Secrets.
BETTER_AUTH_URL=
BETTER_AUTH_SECRET=
DATABASE_URL=Plain
# Used for local development and CLI tools such as:
#
# - Drizzle CLI
# - Better Auth CLI
BETTER_AUTH_URL=
BETTER_AUTH_SECRET=
DATABASE_URL=3. Wrangler
设置环境变量后,运行以下脚本为 Cloudflare Workers 配置生成类型:
¥After setting your environment variables, run the following script to generate types for your Cloudflare Workers configuration:
sh
npx wrangler types --env-interface CloudflareBindings
# OR
npm run cf-typegensh
pnpm wrangler types --env-interface CloudflareBindings
# OR
pnpm cf-typegensh
yarn wrangler types --env-interface CloudflareBindings
# OR
yarn cf-typegensh
bunx wrangler types --env-interface CloudflareBindings
# OR
bun run cf-typegen然后,确保你的 tsconfig.json 文件包含生成的类型。
¥Then, make sure your tsconfig.json includes the generated types.
json
{
"compilerOptions": {
"types": ["worker-configuration.d.ts"]
}
}4. Drizzle
要使用 Drizzle Kit CLI,请将以下 Drizzle 配置文件添加到项目根目录。
¥To use the Drizzle Kit CLI, add the following Drizzle configuration file to the root of your project.
ts
import { defineConfig } from 'drizzle-kit';
export default defineConfig({
out: './drizzle',
schema: './src/db/schema.ts',
dialect: 'postgresql',
dbCredentials: {
url: process.env.DATABASE_URL!,
},
});应用
¥Application
1. Better Auth 实例
¥ Better Auth Instance
使用 Cloudflare Workers 绑定创建 Better Auth 实例。
¥Create a Better Auth instance using Cloudflare Workers bindings.
有很多可用的配置选项,远不止本示例所能涵盖。请参考官方文档,并根据你的项目需求进行配置:
¥There are many available configuration options, far more than can be covered in this example. Please refer to the official documentation and configure it according to your project’s needs:
(文档:Better Auth - 选项)
¥(Docs: Better Auth - Options)
ts
import { neon } from '@neondatabase/serverless';
import { drizzle } from 'drizzle-orm/neon-http';
import { drizzleAdapter } from 'better-auth/adapters/drizzle';
import { betterAuth } from 'better-auth';
import { betterAuthOptions } from './options';
import * as schema from "../db/schema"; // Ensure the schema is imported
/**
* Better Auth Instance
*/
export const auth = (env: CloudflareBindings): ReturnType<typeof betterAuth> => {
const sql = neon(env.DATABASE_URL);
const db = drizzle(sql);
return betterAuth({
...betterAuthOptions,
database: drizzleAdapter(db, { provider: 'pg' }),
baseURL: env.BETTER_AUTH_URL,
secret: env.BETTER_AUTH_SECRET,
// Additional options that depend on env ...
});
};ts
import { BetterAuthOptions } from 'better-auth';
/**
* Custom options for Better Auth
* * Docs: https://www.better-auth.com/docs/reference/options
*/
export const betterAuthOptions: BetterAuthOptions = {
/**
* The name of the application.
*/
appName: 'YOUR_APP_NAME',
/**
* Base path for Better Auth.
* @default "/api/auth"
*/
basePath: '/api',
// .... More options
};2. Better Auth 架构
¥ Better Auth Schema
要创建 Better Auth 所需的表,请先将以下文件添加到根目录:
¥To create the required tables for Better Auth, first add the following file to the root directory:
ts
/**
* Better Auth CLI configuration file
* * Docs: https://www.better-auth.com/docs/concepts/cli
*/
import { neon } from '@neondatabase/serverless';
import { drizzle } from 'drizzle-orm/neon-http';
import { drizzleAdapter } from 'better-auth/adapters/drizzle';
import { betterAuth } from 'better-auth';
import { betterAuthOptions } from './src/lib/better-auth/options';
const { DATABASE_URL, BETTER_AUTH_URL, BETTER_AUTH_SECRET } = process.env;
const sql = neon(DATABASE_URL!);
const db = drizzle(sql);
export const auth: ReturnType<typeof betterAuth> = betterAuth({
...betterAuthOptions,
database: drizzleAdapter(db, { provider: 'pg', schema }), // schema is required in order for bettter-auth to recognize
baseURL: BETTER_AUTH_URL,
secret: BETTER_AUTH_SECRET,
});然后,执行以下脚本:
¥Then, execute the following script:
sh
npx @better-auth/cli@latest generate --config ./better-auth.config.ts --output ./src/db/schema.tssh
pnpm dlx @better-auth/cli@latest generate --config ./better-auth.config.ts --output ./src/db/schema.tssh
yarn dlx @better-auth/cli@latest generate --config ./better-auth.config.ts --output ./src/db/schema.tssh
bunx @better-auth/cli@latest generate --config ./better-auth.config.ts --output ./src/db/schema.ts3. 将架构应用于数据库
¥ Apply Schema to Database
生成 schema 文件后,运行以下命令创建并应用数据库迁移:检查你的 Wrangler 配置,确保其正确读取 process.env,以便 wrangler dev 后续能够正常工作。你需要配置 node_compatibility。
¥After generating the schema file, run the following commands to create and apply the database migration: Check your wrangler config to read the process.env correctly for the wrangler dev to work later. You need node_compatibility setup.
sh
npx drizzle-kit generate
npx drizzle-kit migratesh
pnpm drizzle-kit generate
pnpm drizzle-kit migratesh
yarn drizzle-kit generate
yarn drizzle-kit migratesh
bunx drizzle-kit generate
bunx drizzle-kit migrate4. 挂载处理程序
¥ Mount the handler
将 Better Auth 处理程序挂载到 Hono 端点,确保挂载路径与 Better Auth 实例中的 basePath 设置匹配。
¥Mount the Better Auth handler to a Hono endpoint, ensuring that the mount path matches the basePath setting in your Better Auth instance.
ts
import { Hono } from 'hono';
import { auth } from './lib/better-auth';
const app = new Hono<{ Bindings: CloudflareBindings }>();
app.on(['GET', 'POST'], '/api/*', (c) => {
return auth(c.env).handler(c.req.raw);
});
export default app;高级
¥Advanced
本示例基于 Hono、Better Auth 和 Drizzle 的官方文档编写。然而,它超越了简单的集成,并提供了以下优势:
¥This example is assembled based on the official documentation of Hono, Better Auth, and Drizzle. However, it goes beyond simple integration and offers the following benefits:
通过集成 Cloudflare CLI、Better Auth CLI 和 Drizzle CLI 实现高效开发。
¥Efficient development through integration of Cloudflare CLI, Better Auth CLI, and Drizzle CLI.
开发环境和生产环境之间的无缝过渡。
¥Seamless transition between development and production environments.
使用脚本一致地应用更改。
¥Apply changes consistently using a script.
你可以使用定制的脚本扩展此设置,以适应你的工作流程。例如:
¥You can extend this setup with custom scripts tailored to your workflow. For example:
json
{
"scripts": {
"dev": "wrangler dev",
"deploy": "pnpm run cf-gen-types && wrangler secret bulk .dev.vars.production && wrangler deploy --minify",
"cf-gen-types": "wrangler types --env-interface CloudflareBindings",
"better-auth-gen-schema": "pnpm dlx @better-auth/cli@latest generate --config ./better-auth.config.ts --output ./src/db/schema.ts"
},
}注意:有关高级用法和最新选项,请参阅每个工具的官方 CLI 文档:
¥NOTE:\ Refer to the official CLI documentation for each tool for advanced usage and the most up-to-date options:
结束语
¥In Closing
现在,你拥有一个运行在 Cloudflare Workers 上的轻量级、快速且全面的身份验证服务。通过利用服务绑定,此设置允许你构建延迟极低的微服务架构。
¥You now have a lightweight, fast, and comprehensive authentication service running on Cloudflare Workers. By leveraging Service Bindings, this setup allows you to build microservice-based architectures with minimal latency.
本指南仅演示一个基本示例,因此对于 OAuth 或速率限制等高级用例,请参阅官方文档并根据你的服务需求定制配置。
¥This guide demonstrates only a basic example, so for advanced use cases like OAuth or rate limiting, refer to the official documentation and tailor the configuration to your service’s needs.
你可以在此处找到完整的示例源代码:GitHub 代码库
¥You can find the full example source code here:
GitHub Repository