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/plugins/payments.md

View on GitHub
# better-auth Payment Plugins

Complete guide for payment integrations: Stripe and Polar.

---

## Stripe Integration

### Installation

```bash
bun add better-auth stripe
```

### Server Configuration

```typescript
import { betterAuth } from "better-auth";
import { stripe } from "better-auth/plugins";
import Stripe from "stripe";

const stripeClient = new Stripe(process.env.STRIPE_SECRET_KEY!);

export const auth = betterAuth({
  plugins: [
    stripe({
      stripeClient,
      // Webhook secret for event validation
      webhookSecret: process.env.STRIPE_WEBHOOK_SECRET!,
      // Sync user data to Stripe Customer
      syncUserToCustomer: true,
      // Map subscription status to user fields
      subscriptionConfig: {
        // Plans available
        plans: [
          {
            id: "pro",
            priceId: "price_xxx",
            features: ["feature1", "feature2"],
          },
          {
            id: "enterprise",
            priceId: "price_yyy",
            features: ["feature1", "feature2", "feature3"],
          },
        ],
      },
    }),
  ],
});
```

### Client Configuration

```typescript
import { stripeClient } from "better-auth/client/plugins";

const authClient = createAuthClient({
  plugins: [stripeClient()],
});
```

### Create Checkout Session

```typescript
// Create Stripe Checkout for subscription
const { data } = await authClient.stripe.createCheckoutSession({
  planId: "pro",
  successUrl: "https://your-app.com/success",
  cancelUrl: "https://your-app.com/pricing",
});

// Redirect to Stripe Checkout
window.location.href = data.url;
```

### Customer Portal

```typescript
// Open Stripe Customer Portal for subscription management
const { data } = await authClient.stripe.createPortalSession({
  returnUrl: "https://your-app.com/settings",
});

window.location.href = data.url;
```

### Check Subscription Status

```typescript
// Get current subscription
const { data: subscription } = await authClient.stripe.getSubscription();

if (subscription?.status === "active") {
  console.log("Plan:", subscription.planId);
  console.log("Features:", subscription.features);
}
```

### Webhook Handler

```typescript
// Route: /api/stripe/webhook
app.post("/api/stripe/webhook", async (req, res) => {
  const sig = req.headers["stripe-signature"];

  // better-auth handles webhook internally
  const result = await auth.api.stripe.handleWebhook({
    body: req.body,
    signature: sig,
  });

  res.json({ received: true });
});
```

### Webhook Events Handled

better-auth automatically handles:

| Event | Action |
|-------|--------|
| `customer.subscription.created` | Creates subscription record |
| `customer.subscription.updated` | Updates subscription status |
| `customer.subscription.deleted` | Marks subscription as canceled |
| `invoice.payment_succeeded` | Updates payment status |
| `invoice.payment_failed` | Marks payment as failed |

### Access Control by Plan

```typescript
// Server-side middleware
const session = await auth.api.getSession({ headers: req.headers });

if (session?.subscription?.planId !== "pro") {
  return res.status(403).json({ error: "Pro plan required" });
}
```

---

## Polar Integration

Polar is an open-source alternative to Patreon/Stripe for developers.

### Installation

```bash
bun add better-auth @polar-sh/sdk
```

### Server Configuration

```typescript
import { betterAuth } from "better-auth";
import { polar } from "better-auth/plugins";
import { Polar } from "@polar-sh/sdk";

const polarClient = new Polar({
  accessToken: process.env.POLAR_ACCESS_TOKEN!,
});

export const auth = betterAuth({
  plugins: [
    polar({
      polarClient,
      // Organization ID
      organizationId: process.env.POLAR_ORGANIZATION_ID!,
      // Webhook secret
      webhookSecret: process.env.POLAR_WEBHOOK_SECRET!,
      // Available products
      products: [
        {
          id: "supporter",
          priceId: "price_xxx",
          type: "subscription",
        },
        {
          id: "lifetime",
          priceId: "price_yyy",
          type: "one-time",
        },
      ],
    }),
  ],
});
```

### Client Configuration

```typescript
import { polarClient } from "better-auth/client/plugins";

const authClient = createAuthClient({
  plugins: [polarClient()],
});
```

### Create Checkout

```typescript
// Create Polar Checkout
const { data } = await authClient.polar.createCheckout({
  productId: "supporter",
  successUrl: "https://your-app.com/success",
});

window.location.href = data.url;
```

### Check Subscription

```typescript
const { data: subscription } = await authClient.polar.getSubscription();

if (subscription?.status === "active") {
  console.log("Product:", subscription.productId);
}
```

### Webhook Handler

```typescript
// Route: /api/polar/webhook
app.post("/api/polar/webhook", async (req, res) => {
  const result = await auth.api.polar.handleWebhook({
    body: req.body,
    headers: req.headers,
  });

  res.json({ received: true });
});
```

---

## Usage-Based Billing

### Stripe Metered Billing

```typescript
stripe({
  stripeClient,
  subscriptionConfig: {
    plans: [
      {
        id: "api-usage",
        priceId: "price_metered_xxx",
        type: "metered",
      },
    ],
  },
}),

// Report usage
await auth.api.stripe.reportUsage({
  userId: session.user.id,
  quantity: 100,  // API calls used
  timestamp: Date.now(),
});
```

### Usage Tracking

```typescript
// Track API usage per request
app.use(async (req, res, next) => {
  const session = await auth.api.getSession({ headers: req.headers });

  if (session?.subscription?.type === "metered") {
    await auth.api.stripe.incrementUsage({
      userId: session.user.id,
      quantity: 1,
    });
  }

  next();
});
```

---

## Free Trials

### Stripe Trial

```typescript
stripe({
  subscriptionConfig: {
    plans: [
      {
        id: "pro",
        priceId: "price_xxx",
        trialDays: 14,  // 14-day free trial
      },
    ],
  },
}),
```

### Check Trial Status

```typescript
const { data: subscription } = await authClient.stripe.getSubscription();

if (subscription?.status === "trialing") {
  const trialEnd = new Date(subscription.trialEnd);
  console.log("Trial ends:", trialEnd);
}
```

---

## Common Patterns

### Feature Flags by Plan

```typescript
// shared/features.ts
export const PLAN_FEATURES = {
  free: ["basic-feature"],
  pro: ["basic-feature", "advanced-feature", "priority-support"],
  enterprise: ["basic-feature", "advanced-feature", "priority-support", "custom-integrations"],
};

// Usage
const subscription = await authClient.stripe.getSubscription();
const features = PLAN_FEATURES[subscription?.planId || "free"];

if (features.includes("advanced-feature")) {
  // Allow access
}
```

### Upgrade Prompts

```typescript
function FeatureGate({ feature, children }) {
  const { data: subscription } = useSubscription();
  const hasFeature = subscription?.features?.includes(feature);

  if (!hasFeature) {
    return (
      <UpgradePrompt
        feature={feature}
        requiredPlan="pro"
      />
    );
  }

  return children;
}
```

---

## Common Issues

### Stripe: "Webhook signature verification failed"
- Ensure raw body is passed (not parsed JSON)
- Verify webhook secret matches Dashboard setting
- Check webhook URL is accessible

### Stripe: "Customer not found"
- Enable `syncUserToCustomer: true`
- Verify user signed up after plugin was configured

### Polar: "Invalid organization"
- Check `organizationId` is correct
- Verify API token has organization access

### General: "Subscription not updating"
- Check webhook endpoint is registered
- Verify webhook events are enabled
- Check server logs for webhook errors

---

## Environment Variables

### Stripe

```env
STRIPE_SECRET_KEY=sk_live_xxx
STRIPE_WEBHOOK_SECRET=whsec_xxx
STRIPE_PUBLISHABLE_KEY=pk_live_xxx
```

### Polar

```env
POLAR_ACCESS_TOKEN=pat_xxx
POLAR_ORGANIZATION_ID=org_xxx
POLAR_WEBHOOK_SECRET=whsec_xxx
```

---

## Official Resources

- Stripe Plugin: https://better-auth.com/docs/plugins/stripe
- Polar Plugin: https://better-auth.com/docs/plugins/polar
- Stripe Docs: https://stripe.com/docs
- Polar Docs: https://docs.polar.sh
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