Appearance
Cloudflare 上的 Better Auth
🌐 Better Auth on Cloudflare
一个基于 TypeScript 的轻量级身份验证服务,针对 Cloudflare Workers 进行了优化
🌐 A TypeScript-based lightweight authentication service optimized for Cloudflare Workers
技术栈概览
🌐 Stack Summary
🔥 Hono
一个基于网络标准构建的快速、轻量级的网络框架。
🔒 Better Auth 一个用于 TypeScript 的综合认证框架。
🧩 Drizzle ORM
一个轻量级、高性能的 TypeScript ORM,设计时考虑了开发者体验(DX)。
🐘 Postgres 与 Neon 一个为云优化的无服务器 Postgres。
准备工作
🌐 Preparation
1. 安装
🌐 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. 环境变量
🌐 2. Environment Variables
设置以下环境变量,将你的应用连接到 Better Auth 和 Neon。
🌐 Set the following environment variables to connect your application to Better Auth and Neon.
参考官方指南:
🌐 Refer to official guides:
必需文件:
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. 牧马人
🌐 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. 毛毛雨
🌐 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. 更好的身份验证实例
🌐 1. 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:
(文档: 更好的身份验证 - 选项)
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://better-auth.nodejs.cn/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. 更好的身份验证架构
🌐 2. 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://better-auth.nodejs.cn/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. 将模式应用到数据库
🌐 3. 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. 安装处理器
🌐 4. 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 实现高效开发。
- 开发环境和生产环境之间的无缝过渡。
- 使用脚本一致地应用更改。
你可以使用针对你的工作流程定制的脚本来扩展此设置。例如:
🌐 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 文档:
结束语
🌐 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