Skip to content

secondsky/claude-skills / plugins/better-auth/skills/better-auth

better-auth

Verified

Skill 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.

FileKindSize
SKILL.mdskill md29.2 KB
assets/auth-flow-diagram.mdmarkdown24.0 KB
references/advanced-features.mdmarkdown14.7 KB
references/cloudflare-worker-drizzle.tsscript12.7 KB
references/cloudflare-worker-kysely.tsscript9.7 KB
references/configuration-guide.mdmarkdown10.7 KB
references/database-schema.tsscript10.8 KB
references/databases/mongodb.mdmarkdown5.3 KB
references/databases/mysql.mdmarkdown6.8 KB
references/databases/postgresql.mdmarkdown8.4 KB
references/error-catalog.mdmarkdown12.9 KB
references/framework-comparison.mdmarkdown8.2 KB
references/frameworks/api-frameworks.mdmarkdown9.2 KB
references/frameworks/expo-mobile.mdmarkdown8.7 KB
references/frameworks/nextjs.mdmarkdown5.4 KB
references/frameworks/nuxt.mdmarkdown6.0 KB
references/frameworks/remix.mdmarkdown6.1 KB
references/frameworks/sveltekit.mdmarkdown6.3 KB
references/integrations/electron.mdmarkdown8.2 KB
references/migration-guide-1.4.0.mdmarkdown23.2 KB
references/migration-guide-1.5.0.mdmarkdown6.3 KB
references/nextjs/README.mdmarkdown1.1 KB
references/nextjs/postgres-example.tsscript4.0 KB
references/plugins/api-tokens.mdmarkdown10.0 KB
references/plugins/authentication.mdmarkdown9.2 KB
references/plugins/enterprise.mdmarkdown9.1 KB
references/plugins/payments.mdmarkdown8.0 KB
references/plugins/sso.mdmarkdown9.4 KB
references/plugins/test-utils.mdmarkdown5.5 KB
references/react-client-hooks.tsxother12.8 KB
references/setup-guide.mdmarkdown8.9 KB
references/v1.4-features.mdmarkdown8.2 KB
references/v1.5-features.mdmarkdown11.0 KB
references/v1.6-features.mdmarkdown6.1 KB
scripts/generate-secret.shexecutablescript2.0 KB
scripts/setup-d1-drizzle.shexecutablescript10.2 KB
scripts/test-auth-health.shexecutablescript2.1 KB
scripts/validate-config.tsscript4.3 KB

references/v1.6-features.md

View on GitHub
# better-auth v1.6.x New Features

OpenTelemetry, passkey pre-auth, case-insensitive queries, performance improvements.

---

## OpenTelemetry Instrumentation (Experimental)

Distributed tracing for auth API calls, hooks, and database operations.

### Setup

Register a TracerProvider in the application. Better Auth automatically emits spans via the `better-auth` tracer.

```typescript
import { NodeTracerProvider } from "@opentelemetry/sdk-trace-node";
import { SimpleSpanProcessor, ConsoleSpanExporter } from "@opentelemetry/sdk-trace-base";

const provider = new NodeTracerProvider({
    spanProcessors: [new SimpleSpanProcessor(new ConsoleSpanExporter())],
});
provider.register();
```

No additional auth configuration needed.

### Supported Spans

#### Endpoint Spans

| Span Name | When Emitted |
|-----------|-------------|
| `{METHOD} {route}` | Every auth API call (e.g. `GET /get-session`) |
| `handler {route}` | Endpoint handler execution |
| `hook before {route} {source}` | Before-hook runs |
| `hook after {route} {source}` | After-hook runs |
| `onRequest {pluginId}` | Plugin onRequest hook |
| `onResponse {pluginId}` | Plugin onResponse hook |
| `middleware {route} {pluginId}` | Plugin middleware |

#### Database Spans

| Span Name | When Emitted |
|-----------|-------------|
| `db {operation} {model}` | All adapter operations |
| `db {operation}.before {model}` | Database before-hook |
| `db {operation}.after {model}` | Database after-hook |

Operations: `create`, `findOne`, `findMany`, `update`, `updateMany`, `delete`, `deleteMany`, `count`

### Span Attributes

- `http.route` - Route template (low cardinality)
- `better_auth.operation_id` - Operation identifier (e.g. `getSession`)
- `db.operation.name` - Database operation name
- `db.collection.name` - Database collection/model name
- `better_auth.hook.type` - Hook type (`before`, `after`, `onRequest`, etc.)
- `better_auth.context` - Execution context (`"user"` or `"plugin:{pluginId}"`)
- `http.response.status_code` - HTTP response status (onResponse only)

> **Note**: This feature is experimental. Span structure may change in future releases.

---

## Passkey Pre-Auth Registration

Register passkeys before the user has a session. Enables passkey-first onboarding flows.

### Server Configuration

```typescript
import { passkey } from "@better-auth/passkey";

export const auth = betterAuth({
    plugins: [
        passkey({
            registration: {
                requireSession: false,
                resolveUser: async ({ ctx, context }) => {
                    // Validate context (e.g., signed token)
                    return { id: "user-id", name: "user@example.com" };
                },
                extensions: { credProps: true },
            },
            authentication: {
                extensions: { credProps: true },
            },
        }),
    ],
});
```

### Client Usage

```typescript
// Generate registration options with context
await auth.api.generatePasskeyRegistrationOptions({
    context: "signed-registration-token",
});

// Register passkey with same context
await authClient.passkey.addPasskey({
    name: "Primary passkey",
    context: "signed-registration-token",
});
```

### WebAuthn Extensions

Pass extensions on registration and authentication:

```typescript
const result = await authClient.passkey.addPasskey({
    name: "My Passkey",
    extensions: { credProps: true },
    returnWebAuthnResponse: true,
});

console.log(result.webauthn?.clientExtensionResults);
```

---

## Case Insensitive Queries

Database queries support `mode: "insensitive"` across all adapters (Drizzle, Prisma, Kysely, MongoDB, Memory).

```typescript
adapter.findOne({
    model: "user",
    where: [{
        field: "email",
        value: "user@example.com",
        mode: "insensitive",
    }],
});
```

Each adapter uses the most efficient case-insensitive strategy its database supports. Internal API for plugin authors.

---

## Breaking: `freshAge` Uses `createdAt`

`freshAge` check now uses `createdAt` instead of `updatedAt`.

Previously, session refreshes reset the freshness window, allowing sessions to stay "fresh" indefinitely. Now freshness is tied to session creation time.

**Impact**: Sensitive operations (password changes, payment confirmations) may require more frequent re-authentication.

```typescript
export const auth = betterAuth({
    session: {
        freshAge: 60 * 5, // 5 minutes from createdAt
    },
});
```

Set `freshAge: 0` to disable freshness checks.

---

## Breaking: InResponseTo Validation Default ON

SAML `InResponseTo` validation is now enabled by default for SP-initiated flows.

Prevents replay attacks where captured assertions are reused. IdP-initiated SSO is not affected.

To opt out:

```typescript
import { sso } from "@better-auth/sso";

sso({
    saml: {
        enableInResponseToValidation: false,
    },
});
```

---

## Non-Blocking Scrypt

Password hashing now uses native `node:crypto` scrypt on the libuv thread pool instead of blocking the main thread.

Falls back to pure JavaScript implementation on runtimes without `node:crypto` support. Existing password hashes remain fully compatible.

---

## Reduced Package Size

| Package | v1.5.6 | v1.6.0 | Reduction |
|---------|--------|--------|-----------|
| `better-auth` | 4,236 KB | 2,265 KB | 46% |

---

## Two Release Tracks

- **`main`** (stable): Bug fixes, security, additive improvements, non-breaking features
- **`next`** (beta): New features, refactors, breaking changes after beta cycle

```bash
npm install better-auth          # Latest stable
npm install better-auth@beta     # Next minor in progress
```

Contributors declare release intent per PR via changesets.

---

## Behavior Changes

- **SCIM endpoint authorization enforcement**: Management endpoints require proper authentication
- **Passkey ownership normalized**: Prevents cross-user access
- **Cookie cache `maxAge` alignment**: Matches session `expiresIn` to prevent stale cached data

## Deprecations

- **OIDC Provider plugin**: Deprecated in favor of `@better-auth/oauth-provider`. Will be removed in next minor version.

---

## Upgrade

```bash
npx auth upgrade
```

Review breaking changes above. Most users require no code changes.
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: 471kUpdated Claude CodeCodexVerifiedInstall
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: 322kUpdated Claude CodeCodexVerifiedInstall
dispatching-parallel-agentsobra/superpowersUse when facing 2+ independent tasks that can be worked on without shared state or sequential dependenciesStars: 322kUpdated Claude CodeCodexVerifiedInstall
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 availableStars: 322kUpdated Claude CodeCodexVerifiedInstall