Skip to content

Better Auth

将 Hono 与 Better Auth 结合使用进行身份验证。

¥Using Hono with Better Auth for authentication.

Better Auth 是一个与框架无关的 TypeScript 身份验证和授权框架。它提供一套全面的开箱即用功能,并包含一个插件生态系统,可简化高级功能的添加。

¥Better Auth is a framework-agnostic authentication and authorization framework for TypeScript. It provides a comprehensive set of features out of the box and includes a plugin ecosystem that simplifies adding advanced functionalities.

配置

¥Configuration

  1. 安装框架:

    ¥Install the framework:

sh
# npm
npm install better-auth

# bun
bun add better-auth

# pnpm
pnpm add better-auth

# yarn
yarn add better-auth
  1. .env 文件中添加所需的环境变量:

    ¥Add the required environment variables in the .env file:

sh
BETTER_AUTH_SECRET=<generate-a-secret-key> (e.g. D27gijdvth3Ul3DjGcexjcFfgCHc8jWd)
BETTER_AUTH_URL=<url-of-your-server> (e.g. http://localhost:1234)
  1. 创建 Better Auth 实例

    ¥Create the Better Auth instance

ts
import { betterAuth } from 'better-auth'
import { prismaAdapter } from 'better-auth/adapters/prisma'

import prisma from '@/db/index'
import env from '@/env'

export const auth = betterAuth({
  database: prismaAdapter(prisma, {
    provider: 'postgresql',
  }),
  // Allow requests from the frontend development server
  trustedOrigins: ['http://localhost:5173'],
  emailAndPassword: {
    enabled: true,
  },
  socialProviders: {
    github: {
      clientId: env.GITHUB_CLIENT_ID,
      clientSecret: env.GITHUB_CLIENT_SECRET,
    },
    google: {
      clientId: env.GOOGLE_CLIENT_ID,
      clientSecret: env.GOOGLE_CLIENT_SECRET,
    },
  },
})

export type AuthType = {
  user: typeof auth.$Infer.Session.user | null
  session: typeof auth.$Infer.Session.session | null
}

以上代码:

¥The above code:

  • 设置数据库以使用 Prisma ORM 和 PostgreSQL

    ¥Sets up the database to use Prisma ORM and PostgreSQL

  • 指定受信任的来源

    ¥Specifies the trusted origins

    • 受信任的来源是指被允许向身份验证 API 发出请求的应用。通常情况下,这就是你的客户端(前端)。

      ¥A trusted origin is the app that's allowed to make requests to the auth API. Normally, that's your client (frontend)

    • 所有其他来源将被自动阻止。

      ¥All the other origins are automatically blocked

  • 它支持电子邮件/密码身份验证并配置社交登录提供程序。

    ¥It enables email/password authentication and configures social login providers.

  1. 生成 Prisma schema 文件所需的所有模型、字段和关系:

    ¥Generate all the required models, fields, and relationships to the Prisma schema file:

sh
bunx @better-auth/cli generate
  1. routes/auth.ts 中为身份验证 API 请求创建 API 处理程序

    ¥Create the API Handler for the auth API requests in routes/auth.ts

此路由使用 Better Auth 提供的处理程序将所有 POSTGET 请求发送到 /api/auth 端点。

¥This route uses the handler provided by Better Auth to serve all POST and GET requests to the /api/auth endpoint.

ts
import { Hono } from 'hono'
import { auth } from '../lib/auth'
import type { AuthType } from '../lib/auth'

const router = new Hono<{ Bindings: AuthType }>({
  strict: false,
})

router.on(['POST', 'GET'], '/auth/*', (c) => {
  return auth.handler(c.req.raw)
})

export default router
  1. 挂载路由

    ¥Mount the route

以下代码挂载路由。

¥The code below mounts the route.

ts
import { Hono } from "hono";
import type { AuthType } from "../lib/auth"
import auth from "@/routes/auth";

const app = new Hono<{ Variables: AuthType }>({
  strict: false,
});

const routes = [auth, ...other routes] as const;

routes.forEach((route) => {
  app.basePath("/api").route("/", route);
});

export default app;

另请参阅

¥See also

Hono v4.11 中文网 - 粤ICP备13048890号