secondsky/claude-skills / plugins/better-auth/skills/better-auth
better-auth
VerifiedSkill for integrating Better Auth - comprehensive TypeScript authentication framework for Cloudflare D1, Next.js, Nuxt, and 15+ frameworks. Use when adding auth, encountering D1 adapter errors, or implementing OAuth/2FA/RBAC features.
references/v1.5-features.md
View on GitHub# better-auth v1.5.x New Features
Major release with 600+ commits, 70 new features, 200 bug fixes, and 7 new packages.
---
## New CLI (`npx auth`)
Replaces `@better-auth/cli` (deprecated in future release).
```bash
npx auth init # Interactive project scaffolding
npx auth migrate # Run database migrations
npx auth generate # Generate auth schema
npx auth upgrade # Upgrade to latest version
```
### Adapter-Specific Schema Generation
```bash
npx auth generate --adapter prisma
npx auth generate --adapter drizzle
```
---
## Remote MCP Auth Client
Framework-agnostic auth client for MCP servers separate from the Better Auth instance.
```typescript
import { createMcpAuthClient } from "better-auth/plugins/mcp/client";
const mcpAuth = createMcpAuthClient({
authURL: "https://my-app.com/api/auth",
});
// Handler wrapper
const handler = mcpAuth.handler(async (req, session) => {
return new Response("OK");
});
// Direct token verification
const session = await mcpAuth.verifyToken(token);
```
### Framework Adapters
```typescript
import { mcpAuthHono } from "better-auth/plugins/mcp/client/adapters";
const middleware = mcpAuthHono(mcpAuth);
```
---
## OAuth 2.1 Provider (`@better-auth/oauth-provider`)
Turns Better Auth into a full OAuth 2.1 authorization server with OIDC compatibility. Replaces the deprecated OIDC Provider plugin.
```typescript
import { betterAuth } from "better-auth";
import { jwt } from "better-auth/plugins";
import { oauthProvider } from "@better-auth/oauth-provider";
export const auth = betterAuth({
plugins: [
jwt(),
oauthProvider({
loginPage: "/sign-in",
consentPage: "/consent",
}),
],
});
```
### Key Features
- **OAuth 2.1 + OIDC**: `authorization_code`, `refresh_token`, `client_credentials` grants with `openid` scope
- **MCP-ready**: Works as authorization server for MCP tools and agents
- **Dynamic Client Registration**: Public and confidential clients
- **JWT & JWKS**: Sign access tokens as JWTs, verify via `/jwks`
- **Consent & authorization flows**: Built-in consent, account selection, post-login redirect
- **Token introspection & revocation**: RFC 7662 and RFC 7009 compliant
- **Per-endpoint rate limiting**: Configurable per OAuth endpoint
- **HTTPS enforcement** for redirect URIs (HTTP only for localhost)
- **`prompt=none` support** for silent authentication
- **Scope narrowing at consent**
### Migration from OIDC Provider
See the [migration guide](https://www.better-auth.com/docs/plugins/oauth-provider#from-oidc-provider-plugin).
---
## Typed Error Codes
Machine-readable `code` field in every error response.
```typescript
import { defineErrorCodes } from "@better-auth/core";
export const MY_ERROR_CODES = defineErrorCodes({
USER_NOT_FOUND: "User not found",
INVALID_TOKEN: "The provided token is invalid",
});
// In route handlers:
throw APIError.from("BAD_REQUEST", MY_ERROR_CODES.USER_NOT_FOUND);
```
Error response format:
```json
{
"code": "USER_NOT_FOUND",
"message": "User not found"
}
```
Error codes are fully typed and auto-completed from all registered plugins.
---
## i18n Plugin (`@better-auth/i18n`)
Type-safe error message translations with automatic locale detection.
```typescript
import { i18n } from "@better-auth/i18n";
export const auth = betterAuth({
plugins: [
i18n({
defaultLocale: "en",
detection: ["header", "cookie"],
translations: {
fr: { USER_NOT_FOUND: "Utilisateur non trouvé" },
de: { USER_NOT_FOUND: "Benutzer nicht gefunden" },
},
}),
],
});
```
### Detection Strategies
- **`header`** - `Accept-Language` header (default)
- **`cookie`** - Custom cookie (configurable name, default `"locale"`)
- **`session`** - User profile field (configurable, default `"locale"`)
- **`callback`** - Custom function receiving endpoint context
### Error Response with Translation
```json
{
"code": "INVALID_EMAIL_OR_PASSWORD",
"message": "Email ou mot de passe invalide",
"originalMessage": "Invalid email or password"
}
```
---
## Unified Before & After Hooks
Plugin hooks and global hooks now share the same `AuthMiddleware` type.
```typescript
import { createAuthMiddleware } from "better-auth/api";
export const auth = betterAuth({
hooks: {
before: createAuthMiddleware(async (ctx) => {
console.log("Request to:", ctx.path);
}),
after: createAuthMiddleware(async (ctx) => {
console.log("Response:", ctx.context.returned);
}),
},
});
```
Plugin hooks with matchers:
```typescript
hooks: {
before: [{
matcher: (ctx) => ctx.path === "/sign-in/email",
handler: createAuthMiddleware(async (ctx) => { /* ... */ }),
}],
},
```
---
## Dynamic Base URL
Allowlist-based multi-domain support for Vercel previews, reverse proxies, multi-domain setups.
```typescript
export const auth = betterAuth({
baseURL: {
allowedHosts: [
"myapp.com",
"*.vercel.app",
"preview-*.myapp.com",
"localhost:3000",
],
fallback: "https://myapp.com",
protocol: "auto", // "http" | "https" | "auto"
},
});
```
### Wildcard Patterns
| Pattern | Matches |
|---------|---------|
| `myapp.com` | Exact match |
| `*.vercel.app` | Any subdomain |
| `preview-*.myapp.com` | Prefix match |
| `localhost:*` | Any port |
### Cross-Subdomain Cookies
```typescript
export const auth = betterAuth({
baseURL: {
allowedHosts: ["auth.example1.com", "auth.example2.com"],
protocol: "https",
},
advanced: {
crossSubDomainCookies: {
enabled: true,
},
},
});
```
`allowedHosts` are automatically added to `trustedOrigins`.
---
## Secret Key Rotation
Non-destructive rotation of `BETTER_AUTH_SECRET` without invalidating sessions.
```typescript
export const auth = betterAuth({
secrets: [
{ version: 2, value: "new-secret-key-at-least-32-chars" },
{ version: 1, value: "old-secret-key-still-used-to-decrypt" },
],
});
```
Or via environment variable:
```bash
BETTER_AUTH_SECRETS="2:new-secret-key,1:old-secret-key"
```
First key is active (encryption), all keys are tried for decryption.
---
## Cloudflare D1 Native Support
Pass D1 binding directly — no adapter required.
```typescript
import { betterAuth } from "better-auth";
export default {
async fetch(request, env) {
const auth = betterAuth({
database: env.DB, // D1 binding, auto-detected
});
return auth.handler(request);
},
} satisfies ExportedHandler<{ DB: D1Database }>;
```
Uses D1's `batch()` API for atomicity (no interactive transactions).
---
## Adapter Extraction
Database adapters in separate packages for smaller bundles.
| Package | Description |
|---------|-------------|
| `@better-auth/drizzle-adapter` | Drizzle ORM |
| `@better-auth/prisma-adapter` | Prisma |
| `@better-auth/kysely-adapter` | Kysely |
| `@better-auth/mongo-adapter` | MongoDB |
| `@better-auth/memory-adapter` | In-memory |
Main `better-auth` re-exports all adapters. Use `better-auth/minimal` for smallest bundle:
```typescript
import { drizzleAdapter } from "@better-auth/drizzle-adapter";
import { betterAuth } from "better-auth/minimal";
export const auth = betterAuth({
database: drizzleAdapter(db, { provider: "pg" }),
});
```
---
## Verification on Secondary Storage
Store verification tokens in Redis instead of (or in addition to) the database.
```typescript
export const auth = betterAuth({
secondaryStorage: { /* Redis config */ },
verification: {
storeIdentifier: "hashed",
storeInDatabase: false,
},
});
```
Per-identifier overrides:
```typescript
verification: {
storeIdentifier: {
default: "plain",
overrides: {
"email-verification": "hashed",
"password-reset": "hashed",
},
},
},
```
---
## Rate Limiter Improvements
- Rejected requests no longer count against the limit
- Hardened defaults: sign-in/sign-up 3 req/10s, password reset/OTP 3 req/60s
- IPv6 subnet support with configurable prefix size
- Plugin-level rate limit rules
- Automatic expired entry cleanup
```typescript
export const auth = betterAuth({
advanced: {
ipAddress: {
ipv6Subnet: 64,
},
},
});
```
---
## Seat-Based Billing (Stripe)
Per-seat billing for organizations with automatic sync.
```typescript
import { stripe } from "@better-auth/stripe";
import { organization } from "better-auth/plugins";
export const auth = betterAuth({
plugins: [
organization(),
stripe({
stripeClient,
stripeWebhookSecret: "whsec_...",
subscription: {
enabled: true,
plans: [{
name: "team",
priceId: "price_base_monthly",
seatPriceId: "price_per_seat",
}],
},
organization: { enabled: true },
}),
],
});
```
Also supports usage-based billing via `lineItems`, `scheduleAtPeriodEnd`, and `billingInterval` tracking.
---
## Update Session Endpoint
Update custom additional session fields without re-authentication.
```typescript
// Client
await authClient.updateSession({
theme: "dark",
language: "en",
});
// Server
await auth.api.updateSession({
body: { theme: "dark" },
headers: await headers(),
});
```
Only custom additional fields allowed. Core fields (`token`, `userId`, `expiresAt`, etc.) cannot be updated.
---
## Additional Features
### Authentication & Sessions
- `verifyPassword` API for server-side password verification
- `setShouldSkipSessionRefresh` for specific requests
- `deferSessionRefresh` for read-replica setups
- Awaitable social provider config
- Limit enumeration on sign-up with email verification
- Form data support for email sign-in/sign-up
- Auto-detect `VERCEL_URL` and `NEXTAUTH_URL` for base URL
### OAuth & Providers
- Railway OAuth provider
- Trusted providers callback
- Case-insensitive email matching for social account linking
### Plugin Improvements
- `magic-link`: `allowedAttempts` option
- `email-otp`: Change email flow with OTP, richer sign-in
- `phone-number`: Additional fields in `signUpOnVerification`
- `two-factor`: `twoFactorCookieMaxAge`, server-side trust device expiration
- `one-tap`: Button mode for Google sign-in
- `anonymous`: Delete anonymous user endpoint
- `admin`: Optional password on user creation
### Core
- `BetterAuthPluginRegistry` type system: `getPlugin()`, `hasPlugin()`
- Version accessible at runtime via `AuthContext`
- Redis secondary storage extracted to `@better-auth/redis-storage`
---
## Cloudflare Workers Compatibility
All v1.5 features work on Cloudflare Workers:
- D1 native support (no adapter needed)
- `better-auth/minimal` for smallest bundle
- Use `nodejs_compat` or `nodejs_als` compatibility flag
- In-memory rate limiting (Redis not available on Workers)
- Verification tokens in KV (via secondary storage)
```toml
# wrangler.toml
compatibility_flags = ["nodejs_compat"]
compatibility_date = "2024-09-23"
```
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| reverse-engineer-anythingmorluto/reaReverse engineer native, managed, Electron/JavaScript, packaged, firmware, and browser targets with REA, and build agent environments (AgentEnv bundles) of web applications from a live instance or a capture, and of Linux desktop apps with a task from a request. Use shipped-artifact or requested runtime evidence to explain features, compare versions, decompile code, or guide a reconstruction. Skip REA for ordinary source-repository architecture analysis. | Stars: 471k | Updated | Claude CodeCodex | Verified | Install |
| diagnosing-superpowersobra/superpowersUse when a superpowers session went wrong and your human partner wants to know why — repeated work, ignored plans, stumbles, poor results, a skill that didn't fire, "it took too long", "why is it so expensive", "what is it doing" — or wants to build a bug report for the superpowers maintainers, for the current session or a past one identified by id or path, on any harness. | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| dispatching-parallel-agentsobra/superpowersUse when facing 2+ independent tasks that can be worked on without shared state or sequential dependencies | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| executing-plansobra/superpowersUse when executing an implementation plan in the current session as the implementer yourself — your human partner chose inline execution, or no subagent tool is available | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |