bởi cypress

Better Auth is a framework-agnostic authentication library for TypeScript with a rich plugin ecosystem covering OAuth, passkeys, SSO, MFA, Stripe billing, and more. Designed for backend and full-stack TypeScript apps.
Better Auth is a framework-agnostic authentication and authorization library for TypeScript. It provides session management, OAuth2 social providers, plugin architecture, and database adapters out of the box. The typical buyer is a TypeScript backend developer building a Node.js/Bun/Edge application who needs production-grade auth without vendor lock-in.
adapters/ - Database adapter implementations (Drizzle, Kysely, Prisma, MongoDB, memory)api/ - HTTP route handlers, middleware, rate limiting, and endpoint wiringauth/ - Core betterAuth factory and configuration baseclient/ - Framework clients for React, Vue, Svelte, Solid, and vanilla fetchcontext/ - Request context utilitiescookies/ - Cookie management helperscrypto/ - Cryptographic primitivesdb/ - Database abstraction and query utilitiesintegrations/ - Framework integration helpersoauth2/ - OAuth2 authorization and token handlingplugins/ - Built-in plugin implementationssocial-providers/ - Pre-built OAuth2 provider configurationstest-utils/ - Testing helperstypes/ - Shared TypeScript typesutils/ - General utility functionsindex.ts - Main entry point re-exporting the full public APIstate.ts - Global state managementversion.ts - Package version constantnpm install better-auth
npm install @better-auth/core
# Pick your database adapter:
npm install @better-auth/drizzle-adapter drizzle-orm
npm install @better-auth/kysely-adapter kysely
npm install @better-auth/prisma-adapter @prisma/client
npm install @better-auth/memory-adapter
# Required peer deps for cryptography / JWT:
npm install jose zod better-call
No native build steps required. For Edge runtimes (Cloudflare Workers, Vercel Edge) no additional linking is needed.
Copy the source into your project at src/lib/better-auth/source/ or install via npm (). If using the source block directly, point your imports at the local path.
Khởi chạy sandbox cách ly và chạy phía máy chủ — không cần cài đặt cục bộ.
Tetrees AI Review cho phiên bản này
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
Quy trình avcp-2026-08-04.1 · SHA-256 a38264d635f5f58a…
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.
Đã đánh giá 4 thg 8, 2026
Đưa sản phẩm này thẳng vào AI IDE, trình tạo web hoặc cloud IDE của bạn.
Kết nối Tetrees với AI IDE tương thích để liệt kê sản phẩm bạn sở hữu và nhận ZIP đã xác minh mà không cấp quyền tải lên của người bán.
Chưa có đánh giá.
Sign in to join the discussion
Loading discussion…
better-authConfigure tsconfig.json to enable decorators and module resolution:
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"strict": true,
"paths": {
"better-auth": ["./src/lib/better-auth/source/index.ts"],
"better-auth/*": ["./src/lib/better-auth/source/*"]
}
}
}
BETTER_AUTH_SECRET=your-32-char-secret-minimum
BETTER_AUTH_URL=https://your-app.com
DATABASE_URL=postgresql://user:pass@host/db
Wire the auth handler into your server (see examples below).
For Prisma adapter, run npx prisma generate after schema changes.
import { betterAuth } from "better-auth";
function betterAuth(config: BetterAuthConfig): BetterAuthInstance
The main factory function. Call once at startup with your database adapter, secret, and plugin list. The returned instance exposes a handler for HTTP and a api object for server-side calls.
import { APIError } from "better-auth";
class APIError extends Error {
constructor(status: number, message?: string, headers?: Headers)
}
Throw this inside custom plugins or route handlers to return structured HTTP error responses. Better Auth's handler catches it and serializes it correctly.
import { createAdapterFactory } from "better-auth/adapters";
function createAdapterFactory(
config: AdapterFactoryConfig
): AdapterFactory
Use this to build a custom database adapter when none of the built-ins fit. It accepts model/field name transformers and a query executor. Prefer the built-in adapters unless you have a non-standard data layer.
import { getCurrentAdapter } from "better-auth";
function getCurrentAdapter(context: AuthContext): Adapter
Retrieves the active adapter from the current request context. Useful inside plugin hooks when you need raw database access during request handling.
A minimal local development setup using the in-memory adapter, no external database required.
import express from "express";
import { betterAuth } from "better-auth";
import { memoryAdapter } from "better-auth/adapters/memory-adapter";
const auth = betterAuth({
secret: process.env.BETTER_AUTH_SECRET!,
baseURL: process.env.BETTER_AUTH_URL ?? "http://localhost:3000",
database: memoryAdapter(),
emailAndPassword: {
enabled: true,
},
});
const app = express();
app.use(express.json());
// Mount all auth routes under /api/auth
app.all("/api/auth/*", async (req, res) => {
const response = await auth.handler(req);
res.status(response.status);
response.headers.forEach((value, key) => res.setHeader(key, value));
res.send(await response.text());
});
app.listen(3000, () => console.log("Listening on :3000"));
Production setup wiring a PostgreSQL Drizzle adapter with a GitHub 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!,
},
},
});
export type Auth = typeof auth;
When you use a data layer not covered by a built-in adapter.
import { createAdapterFactory } from "better-auth/adapters";
const myAdapter = createAdapterFactory({
adapterId: "my-custom-orm",
adapterName: "My Custom ORM Adapter",
createAdapter(config, options) {
return {
async findOne({ model, where }) {
// translate to your ORM query
return myOrm[model].findFirst({ where });
},
async findMany({ model, where, limit, offset }) {
return myOrm[model].findMany({ where, take: limit, skip: offset });
},
async create({ model, data }) {
return myOrm[model].create({ data });
},
async update({ model, where, update }) {
return myOrm[model].update({ where, data: update });
},
async delete({ model, where }) {
return myOrm[model].delete({ where });
},
async count({ model, where }) {
return myOrm[model].count({ where });
},
};
},
});
import { betterAuth } from "better-auth";
export const auth = betterAuth({
secret: process.env.BETTER_AUTH_SECRET!,
baseURL: process.env.BETTER_AUTH_URL!,
database: myAdapter({}),
});
index.ts - Barrel export: re-exports betterAuth, all core types, APIError, adapter utilities, and third-party types from jose, zod, and better-call.state.ts - Holds global mutable state used across the auth lifecycle.version.ts - Exports the current package version string.adapters/ - Re-exports all database adapters; adapters/index.ts also exposes createAdapterFactory and deprecated aliases like createAdapter.api/ - All HTTP route definitions (sign-in, sign-up, sign-out, session, OAuth callback, password reset, email verification), middleware (origin check, authorization), and rate limiter.auth/ - betterAuth factory split into full.ts (all features), minimal.ts (tree-shaken), and base.ts (shared logic). Trusted origins validation is in trusted-origins.ts.client/ - Isomorphic client SDK. Framework-specific bindings live in subdirectories (react/, vue/, svelte/, solid/, lynx/). vanilla.ts is the framework-agnostic base.context/ - Utilities for constructing and reading the per-request auth context.cookies/ - Cookie parsing, signing, and serialization helpers.crypto/ - Wrappers over the Web Crypto API used for hashing, HMAC, and random bytes.db/ - Internal database query builder and schema inference utilities.integrations/ - Thin adapters for specific server frameworks.oauth2/ - OAuth2 authorization code flow implementation, PKCE, state generation.plugins/ - Built-in plugin implementations (2FA, magic link, passkey, etc.).social-providers/ - Provider-specific OAuth2 configurations for GitHub, Google, Discord, and others.test-utils/ - Test server factory and mock helpers for integration testing.types/ - Shared TypeScript interfaces for config, plugins, sessions, and users.utils/ - Miscellaneous helpers: URL, date, object, and string utilities.BETTER_AUTH_SECRET too short: The secret must be at least 32 characters; shorter values cause silent HMAC failures at runtime. Use openssl rand -base64 32 to generate one.initGetModelName/initGetFieldName from createAdapterFactory to map custom names instead of renaming your schema.better-call: If your bundler sees dual-module errors, add better-call and better-auth to esmExternals or set "type": "module" in your package.json.BETTER_AUTH_URL must match the authorized redirect URI registered with the provider exactly, including trailing slash.getCurrentAdapter called outside request context: This function reads from async local storage and returns undefined outside an active request handler. Only call it inside plugin hooks or middleware.I have a TypeScript Node.js project and I want to integrate Better Auth from the
source block located at `source/` (entry point: `source/index.ts`).
Please read `USAGE.md` in full before writing any code.
Tasks:
1. Install all dependencies listed in the "Required dependencies" section.
2. Create `src/auth.ts` that calls `betterAuth` with the appropriate adapter
for my database (ask me which one if not specified).
3. Mount the auth HTTP handler on my existing server framework (ask me which
framework I use if not specified).
4. Add the required environment variables to `.env.example`.
5. If I need social OAuth login, add at least one provider configuration.
6. Show me how to protect a route server-side using the session API.
7. Point out any tsconfig changes needed to resolve imports from `source/`.
Upstream package: `better-auth` / `@better-auth/core`
Documentation reference: `USAGE.md`
Source root: `source/`
Do not invent APIs. Only use exports visible in `source/index.ts`,
`source/adapters/index.ts`, and the symbols documented in `USAGE.md`.
Proceed step by step and ask clarifying questions before writing code.
Better Auth is released under the MIT License. See source/LICENSE.md if present in the source block, or refer to the official repository. Upstream package: better-auth by the Better Auth maintainers.
This product’s unique contribution is clean room implementation of valuable code block into AVCP compatible standard.
Hướng dẫn cài đặt đầy đủ và prompt tích hợp sẽ mở khóa sau khi mua.
Automation, Utilities & Developer Tools
Miễn phí