Better Auth
Hono と Better Auth を組み合わせて認証を行います。
Better Auth は、特定のフレームワークに依存しない TypeScript 向けの認証・認可フレームワークです。包括的な機能をすぐに利用でき、高度な機能の追加を容易にするプラグインエコシステムも備えています。
設定
- フレームワークをインストールします。
sh
# npm
npm install better-auth
# bun
bun add better-auth
# pnpm
pnpm add better-auth
# yarn
yarn add better-auth.envファイルに必要な環境変数を追加します。
sh
BETTER_AUTH_SECRET=<generate-a-secret-key> (e.g. D27gijdvth3Ul3DjGcexjcFfgCHc8jWd)
BETTER_AUTH_URL=<url-of-your-server> (e.g. http://localhost:1234)- Better Auth のインスタンスを作成します
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
}上記のコードは、次の設定を行います。
- Prisma ORM と PostgreSQL を使うようデータベースを設定します
- 信頼するオリジンを指定します
- 信頼するオリジンとは、認証 API へのリクエストを許可するアプリで、通常はクライアント(フロントエンド)です
- その他のオリジンはすべて自動的にブロックされます
- メールアドレスとパスワードによる認証を有効にし、ソーシャルログインのプロバイダーを設定します。
- 必要なすべてのモデル、フィールド、リレーションを Prisma のスキーマファイルに生成します。
sh
bunx @better-auth/cli generateroutes/auth.tsに認証 API のリクエストを処理する API ハンドラーを作成します
このルートは Better Auth が提供するハンドラーを使い、/api/auth エンドポイントへのすべての POST および GET リクエストを処理します。
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- ルートをマウントします
次のコードでルートをマウントします。
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;