出品者:Minh N.

Better Auth is a comprehensive, framework-agnostic authentication and authorization library for TypeScript with a rich plugin ecosystem covering 2FA, SSO, passkeys, multi-tenancy, and more.
Better Auth is a framework-agnostic TypeScript authentication library that provides sessions, OAuth2, email/password, and plugin-based extensibility out of the box. It targets backend TypeScript developers who need a complete auth system without being locked into a specific framework or third-party service. The source ships the full auth server, adapter layer, client utilities, and plugin system.
adapters/ - Database adapter factories and built-in adapters (Drizzle, Kysely, Prisma, MongoDB, in-memory)api/ - HTTP route handlers, middleware (auth, origin check), and rate limitingauth/ - Core betterAuth instance factories (full, minimal, base)client/ - Vanilla and framework-specific clients (React, Vue, Svelte, Solid, Lynx)context/ - Request context and adapter resolution utilitiescookies/ - Cookie parsing, signing, and managementcrypto/ - Cryptographic primitives used internallydb/ - Database abstraction, model definitions, and query buildersintegrations/ - Framework integration helpersoauth2/ - OAuth2 authorization code flow, token exchange, PKCEplugins/ - Built-in plugin implementations (2FA, organization, etc.)social-providers/ - Social OAuth provider configurationstest-utils/ - Testing helpers and mock utilitiestypes/ - Shared TypeScript types and interfacesutils/ - General utilities (ID generation, JSON, error codes)index.ts - Package entry point; re-exports everythingstate.ts - Global auth state managementversion.ts - Package version constantnpm install better-auth
npm install @better-auth/core
# Choose your database adapter:
npm install @better-auth/drizzle-adapter # for Drizzle ORM
npm install @better-auth/kysely-adapter # for Kysely
npm install @better-auth/memory-adapter # for in-memory (testing)
# Peer deps for adapters:
npm install drizzle-orm # if using drizzle adapter
npm install kysely # if using kysely adapter
npm install zod # schema validation (peer dep)
npm install jose # JWT / JWK utilities (peer dep)
隔離されたサンドボックスを起動しサーバー側で実行 — ローカル設定不要。
このバージョンの Tetrees AI Review
This TypeScript cli / script completed archive review. Structure, dependency manifests, documentation, functional source, and common risk patterns were checked by the Tetrees verification pipeline; runtime phases are stated separately.
Deterministic AVCP artifact review
パイプライン avcp-2026-08-04.1 · SHA-256 59a77c643e05ec32…
This version-scoped review deterministically inspects the submitted archive for structure, dependencies, documentation, functional source, and common malicious or high-risk signals. Build and test phases are reported as passed only after an isolated sandbox audition. It is not a guarantee of perfect security.
レビュー日 2026年8月4日
この製品をお使いのAI IDE・Webビルダー・クラウドIDEに直接取り込みます。
Tetreesを対応AI IDEに接続し、所有製品の一覧取得と検証済みZIPの取得を、販売者のアップロード権限を公開せずに行えます。
まだレビューがありません。
Sign in to join the discussion
Loading discussion…
No native build steps, pod installs, or Expo prebuild required. Runs in any Node.js >=18 environment.
Drop the source: Place source/ at src/better-auth/ in your project, or import directly from the better-auth npm package if you are not vendoring.
tsconfig.json – ensure moduleResolution is bundler or node16+ and strict is enabled:
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"strict": true,
"skipLibCheck": true
}
}
.env file:BETTER_AUTH_SECRET=your-32-char-secret-here
BETTER_AUTH_URL=http://localhost:3000
DATABASE_URL=postgresql://user:pass@localhost:5432/mydb
Wire to your server – export the auth handler and mount it. Better Auth returns a handler compatible with standard Request/Response.
Database – configure one adapter (see examples below). The memory adapter works without any DB for testing.
import { betterAuth } from "better-auth";
// or from source:
import { betterAuth } from "./auth/full";
const auth = betterAuth(options: BetterAuthOptions): BetterAuth;
The main entry point. Call once at application startup with your configuration object. Returns an auth instance exposing .handler, .api, and .options. Pass it your database adapter, secret, base URL, and any plugins.
import { createAdapterFactory } from "better-auth";
const myAdapter = createAdapterFactory(
(options: AdapterFactoryOptions) => (config: AdapterFactoryConfig) => Adapter
);
Use this to build a custom database adapter if the built-in ones do not cover your ORM. Replaces the deprecated createAdapter export. Returns a factory function suitable for passing to betterAuth({ database: myAdapter(...) }).
import { APIError } from "better-auth";
throw new APIError("UNAUTHORIZED", {
message: "You must be logged in.",
});
A structured error class for throwing from plugin route handlers or middleware. The framework catches it and serializes it into a proper HTTP error response with the correct status code. Use it inside custom plugins or route extensions to communicate errors back to the client.
Minimal working auth server using the in-memory adapter. Good for rapid prototyping and CI testing without a real database.
import { betterAuth } from "better-auth";
import { memoryAdapter } from "better-auth/adapters/memory-adapter";
export const auth = betterAuth({
secret: process.env.BETTER_AUTH_SECRET!,
baseURL: process.env.BETTER_AUTH_URL ?? "http://localhost:3000",
database: memoryAdapter(),
emailAndPassword: {
enabled: true,
},
});
// Express wiring
import express from "express";
const app = express();
app.all("/api/auth/*", async (req, res) => {
const response = await auth.handler(req as any);
res.status(response.status);
response.headers.forEach((value, key) => res.setHeader(key, value));
res.send(await response.text());
});
app.listen(3000);
Production setup connecting Better Auth to a PostgreSQL database via Drizzle and enabling GitHub as a social provider.
import { betterAuth } from "better-auth";
import { drizzleAdapter } from "better-auth/adapters/drizzle-adapter";
import { db } from "./db"; // your Drizzle db instance
import * as schema from "./db/schema";
export const auth = betterAuth({
secret: process.env.BETTER_AUTH_SECRET!,
baseURL: process.env.BETTER_AUTH_URL!,
database: drizzleAdapter(db, {
provider: "pg",
schema,
}),
socialProviders: {
github: {
clientId: process.env.GITHUB_CLIENT_ID!,
clientSecret: process.env.GITHUB_CLIENT_SECRET!,
},
},
emailAndPassword: {
enabled: true,
},
});
export type Auth = typeof auth;
Demonstrates building a simple plugin that adds a protected route and throws APIError when access is denied.
import { betterAuth, APIError } from "better-auth";
import { memoryAdapter } from "better-auth/adapters/memory-adapter";
const adminPlugin = {
id: "admin",
endpoints: {
adminOnly: {
method: "GET",
path: "/admin/data",
handler: async (ctx: any) => {
const session = ctx.context.session;
if (!session || session.user.role !== "admin") {
throw new APIError("FORBIDDEN", {
message: "Admins only.",
});
}
return { data: "secret" };
},
},
},
} as const;
export const auth = betterAuth({
secret: process.env.BETTER_AUTH_SECRET!,
baseURL: "http://localhost:3000",
database: memoryAdapter(),
plugins: [adminPlugin],
});
index.ts - Main entry; re-exports betterAuth, all types, utils, adapter helpers, and third-party types from jose, zod, and better-call.state.ts - Holds mutable global state shared across the auth instance lifecycle.version.ts - Exports the package version string; used in telemetry and user-agent headers.adapters/ - Aggregates all database adapters; exposes createAdapterFactory and deprecated createAdapter alias.api/ - Defines all HTTP endpoints (sign-in, sign-up, sign-out, session, callback, password, etc.) and middleware pipeline.auth/ - Houses betterAuth (full), betterAuthMinimal, and betterAuthBase factory variants plus trusted-origins logic.client/ - Browser/SSR client SDK; framework-specific hooks for React, Vue, Svelte, Solid; vanilla fetch client.context/ - Resolves the current adapter and builds the request context passed to every route handler.cookies/ - Utilities for reading, writing, and signing cookies in a framework-agnostic way.crypto/ - Hashing, random bytes, and HMAC utilities used by sessions and tokens.db/ - Core database abstraction: model registry, field resolution, query helpers.integrations/ - Thin shims for Next.js, Hono, SvelteKit, and other frameworks.oauth2/ - Full OAuth2/OIDC authorization code flow, PKCE, token refresh, and introspection.plugins/ - Bundled plugins: two-factor auth, organization/multi-tenant, magic link, passkey, etc.social-providers/ - Pre-built OAuth configurations for GitHub, Google, Discord, and others.test-utils/ - Test server factory, mock adapters, and assertion helpers.types/ - Shared interfaces: BetterAuthOptions, Session, User, Account, plugin types.utils/ - ID generation (generateId), JSON helpers, error code constants.BETTER_AUTH_SECRET: The library will throw at startup if the secret is absent or shorter than 32 characters. Set a sufficiently long random string in your .env.baseURL in OAuth redirects: The callback URL registered with your OAuth provider must exactly match BETTER_AUTH_URL + /api/auth/callback/<provider>. Trailing slashes cause mismatches."type": "commonjs", use a bundler (esbuild, tsup) or switch to "type": "module" with NodeNext module resolution.drizzleAdapter(db, { provider: "pg" }) without schema causes runtime field-resolution errors. Always pass your full Drizzle schema object.skipLibCheck: false errors: Third-party type re-exports (jose, zod, better-call) can produce conflicts. Set "skipLibCheck": true in tsconfig.json.BroadcastChannel (some SSR contexts), import the session atom directly and manage refresh manually.I have the Better Auth source code in `src/better-auth/` and a USAGE.md guide in the same directory.
The upstream package is `better-auth` / `@better-auth/core`.
Please help me integrate Better Auth into my existing TypeScript project step-by-step:
1. Read USAGE.md and the file excerpts carefully before writing any code.
2. Set up the `betterAuth` instance (from `better-auth` or `src/better-auth/auth/full.ts`) with my chosen database adapter.
3. Mount the auth handler to my existing server (Express / Hono / Next.js – specify which I use).
4. Add email/password and at least one social OAuth provider.
5. Wire the client SDK (vanilla or React) to call the auth endpoints.
6. Show me how to protect a route by checking the session from the auth context.
7. If I need a custom plugin, show me how to throw `APIError` from a plugin route handler.
Only use exports that appear in USAGE.md or the source file excerpts. Do not invent APIs.
Ask me clarifying questions if you need to know my framework, database ORM, or provider choices before writing code.
Better Auth is released under the MIT License. See source/LICENSE.md if present in your vendored copy, or review the license at the upstream repository.
Upstream project: better-auth on npm | GitHub | Documentation
This product’s unique contribution is clean room implementation of valuable code block into AVCP compatible standard.
完全なインストールガイドと統合プロンプトは購入後に解放されます。
Automation, Utilities & Developer Tools
無料