本文へ移動

Hono と Auth.js の統合 ​

このガイドでは、Auth.js(旧 NextAuth.js)を使って Hono アプリケーションに認証を追加する方法を示します。

IMPORTANT

@hono/auth-js パッケージのクライアント側の統合は、現在 React のみ対応しています。

クイックスタート ​

5 分で認証を動かしてみましょう。

  1. インストール → npm install @hono/auth-js @auth/core
  2. 環境変数の設定 → 以下の .env の例をコピー
  3. データベースのテーブル作成 → スキーマのマイグレーションを実行
  4. 認証ルートの追加 → Hono の設定をコピー
  5. テスト → クライアントの例を使用

インストール ​

bash
npm install hono @hono/auth-js @auth/core @auth/drizzle-adapter

セットアップ ​

ステップ 1:環境変数 ​

プロジェクトのルートに .env ファイルを作成します。

properties
AUTH_SECRET=your-auth-secret-here
GITHUB_ID=your-github-client-id
GITHUB_SECRET=your-github-client-secret
GOOGLE_ID=your-google-client-id
GOOGLE_SECRET=your-google-client-secret

TIP

次のコマンドで強力な AUTH_SECRET を生成できます。 openssl rand -base64 32 または、npx auth secret を使ってください。

ステップ 2:データベースの設定 ​

NOTE

最新のスキーマは、Auth.js の Drizzle アダプターのドキュメントからコピーしてください。

SQLite と Drizzle ORM を組み合わせたスキーマを示します。

ts
import { createClient } from '@libsql/client'
import { drizzle } from 'drizzle-orm/libsql'

const client = createClient({
  url: 'DATABASE_URL',
  authToken: 'DATABASE_AUTH_TOKEN',
})
export const db = drizzle(client)
ts
import {
  integer,
  sqliteTable,
  text,
  primaryKey,
} from 'drizzle-orm/sqlite-core'
import type { AdapterAccountType } from 'next-auth/adapters'

export const users = sqliteTable('user', {
  id: text('id')
    .primaryKey()
    .$defaultFn(() => crypto.randomUUID()),
  name: text('name'),
  email: text('email').unique(),
  emailVerified: integer('emailVerified', { mode: 'timestamp_ms' }),
  image: text('image'),
})

export const accounts = sqliteTable(
  'account',
  {
    userId: text('userId')
      .notNull()
      .references(() => users.id, { onDelete: 'cascade' }),
    type: text('type').$type<AdapterAccountType>().notNull(),
    provider: text('provider').notNull(),
    providerAccountId: text('providerAccountId').notNull(),
    refresh_token: text('refresh_token'),
    access_token: text('access_token'),
    expires_at: integer('expires_at'),
    token_type: text('token_type'),
    scope: text('scope'),
    id_token: text('id_token'),
    session_state: text('session_state'),
  },
  (account) => ({
    compoundKey: primaryKey({
      columns: [account.provider, account.providerAccountId],
    }),
  })
)

export const sessions = sqliteTable('session', {
  sessionToken: text('sessionToken').primaryKey(),
  userId: text('userId')
    .notNull()
    .references(() => users.id, { onDelete: 'cascade' }),
  expires: integer('expires', { mode: 'timestamp_ms' }).notNull(),
})

export const verificationTokens = sqliteTable(
  'verificationToken',
  {
    identifier: text('identifier').notNull(),
    token: text('token').notNull(),
    expires: integer('expires', { mode: 'timestamp_ms' }).notNull(),
  },
  (verificationToken) => ({
    compositePk: primaryKey({
      columns: [
        verificationToken.identifier,
        verificationToken.token,
      ],
    }),
  })
)

export const authenticators = sqliteTable(
  'authenticator',
  {
    credentialID: text('credentialID').notNull().unique(),
    userId: text('userId')
      .notNull()
      .references(() => users.id, { onDelete: 'cascade' }),
    providerAccountId: text('providerAccountId').notNull(),
    credentialPublicKey: text('credentialPublicKey').notNull(),
    counter: integer('counter').notNull(),
    credentialDeviceType: text('credentialDeviceType').notNull(),
    credentialBackedUp: integer('credentialBackedUp', {
      mode: 'boolean',
    }).notNull(),
    transports: text('transports'),
  },
  (authenticator) => ({
    compositePK: primaryKey({
      columns: [authenticator.userId, authenticator.credentialID],
    }),
  })
)

基本的な使い方 ​

ルートの設定 ​

Hono アプリケーションに API ルートを作成します。

ts
import { Hono } from 'hono'
import {
  initAuthConfig,
  verifyAuth,
  authHandler,
} from '@hono/auth-js'
import { DrizzleAdapter } from '@auth/drizzle-adapter'
import Google from '@auth/core/providers/google'
import GitHub from '@auth/core/providers/github'
import { db } from './db'
import {
  users,
  accounts,
  authenticators,
  sessions,
  verificationTokens,
} from './schema'

const v1Router = new Hono()
  .use(
    '*',
    initAuthConfig((c) => ({
      adapter: DrizzleAdapter(c.get('db'), {
        usersTable: users,
        accountsTable: accounts,
        authenticatorsTable: authenticators,
        sessionsTable: sessions,
        verificationTokensTable: verificationTokens,
      }),
      secret: c.env.AUTH_SECRET,
      providers: [
        GitHub({
          clientId: c.env.GITHUB_ID,
          clientSecret: c.env.GITHUB_SECRET,
        }),
        Google({
          clientId: c.env.GOOGLE_ID,
          clientSecret: c.env.GOOGLE_SECRET,
        }),
      ],
      session: { strategy: 'jwt' },
    }))
  )
  .use('*', verifyAuth())
  .use('/auth/*', authHandler())

const app = new Hono().route('/api/v1', v1Router)
export default app

使用例 ​

ルートの保護 ​

ts
app.get('/protected', (c) => {
  const auth = c.get('authUser')
  if (!auth) return c.json({ error: 'Unauthorized' }, 401)
  return c.json(auth)
})

クライアント側の統合(React) ​

tsx
import {
  SessionProvider,
  useSession,
  signIn,
} from '@hono/auth-js/react'

function App() {
  const { data: session } = useSession()
  return session ? (
    <p>Hello {session.user?.name}</p>
  ) : (
    <button onClick={() => signIn('github')}>
      Sign in with GitHub
    </button>
  )
}

export default function Root() {
  return (
    <SessionProvider>
      <App />
    </SessionProvider>
  )
}

設定リファレンス ​

Hono アプリケーションの Auth.js を、次の設定でカスタマイズできます。

  • アダプター → データベースに接続します(上の例は Drizzle)
  • プロバイダー → GitHub、Google、または任意の Auth.js プロバイダー
  • セッション → "jwt"(ステートレス)または "database"(永続化)
  • コールバック → サインインやセッションのイベントを処理します

例:

ts
initAuthConfig((c) => ({
  adapter: DrizzleAdapter(c.get('db'), {
    /* tables */
  }),
  secret: c.env.AUTH_SECRET,
  providers: [
    GitHub({
      clientId: c.env.GITHUB_ID,
      clientSecret: c.env.GITHUB_SECRET,
    }),
    Google({
      clientId: c.env.GOOGLE_ID,
      clientSecret: c.env.GOOGLE_SECRET,
    }),
  ],
  session: { strategy: 'jwt' },
  callbacks: {
    async session({ session }) {
      return session
    },
  },
}))

詳細情報 ​

  • Auth.js ドキュメント – プロバイダー、スキーマのリファレンス
  • Hono ドキュメント – ルーティングとミドルウェアのパターン
  • 実装例:ロールに基づくアクセス、パスワードのリセット、メールアドレスの確認

MIT ライセンスで公開されています。