npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@stackproviders/better-auth-billing

v1.0.2

Published

Extensible billing, subscription, and credits plugin for Better Auth

Readme

@stackproviders/better-auth-billing

Extensible billing, subscription, and credits plugin for Better Auth — robust monetization built directly into your authentication layer.

npm version TypeScript License: MIT

Better Auth Billing bridges the gap between identity and revenue. It extends Better Auth to provide out-of-the-box endpoints for handling trials, subscriptions, checkout sessions, and credit management, linked directly to your users or organizations.

An incredibly powerful, developer- and AI-friendly tool.


🚀 Installation

Install via your preferred package manager (Note: better-auth is a required peer dependency).

# npm
npm install @stackproviders/better-auth-billing better-auth

# pnpm (Recommended)
pnpm add @stackproviders/better-auth-billing better-auth

# yarn
yarn add @stackproviders/better-auth-billing better-auth

🛠 Integration & Setup

To use the plugin, simply add it to your Better Auth server configuration and the client configuration.

1. Server Configuration (auth.ts or auth.server.ts)

import { betterAuth } from "better-auth";
import { billingPlugin } from "@stackproviders/better-auth-billing";

export const auth = betterAuth({
  // ... your other plugins and settings
  plugins: [
    billingPlugin({
      targetModel: "organization", // Or "user" depending on your SaaS model
      trialDays: 14, // Set default trial days
      onSubscribe: async (targetId, planId, subscriptionId, event) => {
        console.log(`Subscribed: ${targetId} on ${planId}`);
        // Connect to your payment gateway logic here
      },
      onCancel: async (targetId, subscriptionId) => {
        console.log(`Cancelled: ${subscriptionId} for ${targetId}`);
      }
    }),
  ],
});

2. Client Configuration (auth.client.ts)

For fully typed client-side methods:

import { createAuthClient } from "better-auth/client";
import { billingClient } from "@stackproviders/better-auth-billing/client";

export const authClient = createAuthClient({
  // ... your client config
  plugins: [
    billingClient()
  ],
});

💻 Full Usage Examples

Once configured, the plugin exposes billing methods globally on your authClient.

Fetching Billing Status

Instantly retrieve the active subscription or trial state for the current user/organization.

import { authClient } from "@/lib/auth.client";

async function checkBillingStatus() {
  const { data, error } = await authClient.billing.status();

  if (error) {
    console.error("Failed to parse billing status", error);
    return;
  }

  // AI & Dev Friendly State machine
  switch (data.status) {
    case "active":
      console.log("User is on plan:", data.planName);
      break;
    case "trialing":
      console.log(`Trial ends in ${data.trialDaysLeft} days!`);
      break;
    case "expired":
      console.warn("Trial or subscription has expired.");
      break;
    default:
      console.log("Inactive or no organization selected.");
  }
}

Starting a Trial

Start a risk-free trial.

async function startFreeTrial() {
  const { data, error } = await authClient.billing.startTrial();
  if (data?.success) {
    console.log(`Trial activated for ${data.trialDays} days`);
  }
}

Subscribing to a Plan

Assuming you've seeded billingPlan records in your database, pass the planId to subscribe.

async function upgradePlan(planId: string) {
  const { data, error } = await authClient.billing.subscribe({
    planId: planId
  });

  if (data?.success) {
    console.log("Upgraded to new subscription!", data.subscription);
  }
}

Credit Management (Top-ups and Deductions)

Add and deduct credits with ease:

// Add Credits (e.g. after a stripe transaction is handled)
await authClient.billing.credits.add({
  amount: 1500,
  description: "One-time AI Credits Top-up",
});

// Deduct Credits (e.g. when a user generates an AI image)
const deductResult = await authClient.billing.credits.deduct({
  amount: 50,
  description: "Image Generation",
});

if (deductResult.error) {
  console.log("Not enough credits!");
} else {
  console.log("Remaining Balance:", deductResult.data.balance);
}

🏗 Schema Extensions

By adding billingPlugin, it will automatically inject necessary tables/fields directly into Better Auth's schema context. You'll need to run your sync tools (e.g., npx @better-auth/cli generate or Prisma integrations) to commit these to your database.

The models injected include:

  • billingPlan
  • subscription
  • checkoutSession
  • creditBalance
  • creditTransaction
  • usageRecord

🤖 AI & Developer Friendly

This SDK aims to serve modern development environments by remaining purely type-safe across server boundaries.

When configuring your AI-agents or Copilot, remember that all billing interactions run via REST mappings hooked directly into the $InferServerPlugin properties of the billingClient. You never need manual AST inference to figure out route targets.

Endpoints Hooked Automatically

| Endpoint | Method | Action | | --- | --- | --- | | /billing/status | GET | Check current subscription/trial status | | /billing/plans | GET | Retrieve available billing plans | | /billing/start-trial | POST | Trigger trial for an organization/user | | /billing/create-checkout| POST | Spawn a checkout session URL | | /billing/subscribe | POST | Move to ACTIVE subscription | | /billing/credits/add | POST | Allocate credit points | | /billing/credits/deduct | POST | Use credit points |


📚 Links & References

License

MIT © StackProviders