> ## Documentation Index
> Fetch the complete documentation index at: https://better-auth-razorpay.amankushwaha.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Free trials

> Configure time-limited free trials for Razorpay subscriptions and handle trial lifecycle callbacks with the better-auth-razorpay plugin.

The better-auth-razorpay plugin supports time-limited free trials on subscription plans. When a trial is configured, the plugin delays the first charge by setting Razorpay's `start_at` to the current time plus the trial duration. Trials are limited to one per reference (user or organization).

## Configure a trial on a plan

Add `freeTrial` to any plan in the plugin's `subscription.plans` array.

```ts auth.ts theme={null}
import { betterAuth } from "better-auth";
import { razorpay } from "@amank-root/better-auth-razorpay";

export const auth = betterAuth({
  plugins: [
    razorpay({
      keyId: process.env.RAZORPAY_KEY_ID!,
      keySecret: process.env.RAZORPAY_KEY_SECRET!,
      razorpayWebhookSecret: process.env.RAZORPAY_WEBHOOK_SECRET,
      createCustomerOnSignUp: true,
      subscription: {
        enabled: true,
        plans: [
          {
            planId: "plan_monthly_pro",
            annualPlanId: "plan_annual_pro",
            name: "pro",
            totalCount: 12,
            limits: { projects: 20, storage: 100 },
            freeTrial: {
              days: 14,
              onTrialStart: async (subscription) => {
                console.log("Trial started:", subscription.id);
              },
              onTrialEnd: async ({ subscription }, ctx) => {
                console.log("Trial ended:", subscription.id);
              },
              onTrialExpired: async (subscription, ctx) => {
                console.log("Trial expired without conversion:", subscription.id);
              },
            },
          },
        ],
      },
    }),
  ],
});
```

**days** `number` *required*

Number of days the trial lasts. The plugin computes `start_at = now + days` and passes it to Razorpay when creating the subscription.

**onTrialStart** `function`

Called when the trial begins, after the subscription is created and the local row is stored.

**onTrialEnd** `function`

Called when the trial period ends and the first charge is attempted.

**onTrialExpired** `function`

Called if the trial expires without the customer converting to a paid subscription.

## How trial start is computed

When a user upgrades to a plan that has `freeTrial.days`, the plugin checks whether any previous subscription for the same `referenceId` already had a `trialStart` value. If a trial was already used, the subscription starts immediately and `TRIAL_ALREADY_USED` is not thrown (the trial is simply skipped).

If this is the first trial for that reference, the plugin:

1. Creates the local subscription row with status `"created"`.
2. Computes `start_at` as the current Unix timestamp plus `freeTrial.days * 86400` seconds.
3. Sends `start_at` to Razorpay in the subscription create request.
4. Stores `trialStart` on the local row when the `subscription.authenticated` or activation webhook arrives.

> [!NOTE]
>
> Razorpay begins billing from `start_at`. Until that time, the customer can use the subscription without being charged.

## Trial status in React

Use `useSubscriptionStatus` to check whether the current subscription is in a trial state. `isTrialing` returns `true` when the subscription status is `authenticated` and `trialStart` is set while `trialEnd` is still `null`.

```tsx components/trial-banner.tsx theme={null}
"use client";

import { authClient } from "@/lib/auth-client";
import {
  useSubscriptionList,
  useSubscriptionStatus,
} from "@amank-root/better-auth-razorpay/react";

export function TrialBanner() {
  const { data: subscriptions, isLoading } = useSubscriptionList(authClient);

  if (isLoading) return null;

  const sub = subscriptions?.[0];
  const status = useSubscriptionStatus(sub);

  if (!status.isTrialing) return null;

  const daysLeft = sub?.trialEnd
    ? Math.max(0, Math.ceil((new Date(sub.trialEnd).getTime() - Date.now()) / 86400000))
    : sub?.trialStart
      ? 14 // fallback if trialEnd not yet set
      : 0;

  return (
    <div>
      <p>
        You are on a free trial. {daysLeft} day{daysLeft !== 1 ? "s" : ""} remaining.
      </p>
    </div>
  );
}
```

> [!WARNING]
>
> `isTrialing` is a client-side helper based on the local row. It does not guarantee that Razorpay has not already attempted the first charge if the trial period elapsed while the user was offline. Always verify the latest status from webhooks or refetch queries before making entitlement decisions on the server.

## Trial lifecycle callbacks

The callbacks run on the server and receive the local subscription object.

### onTrialStart

Fires immediately after the subscription is created with a trial. Use it to provision trial features or send a welcome email.

```ts auth.ts theme={null}
freeTrial: {
  days: 14,
  onTrialStart: async (subscription) => {
    await sendEmail({
      to: subscription.referenceId,
      subject: "Your 14-day trial has started",
    });
  },
}
```

### onTrialEnd

Fires when the trial period ends and Razorpay attempts the first charge. The subscription may transition to `active` or `halted` depending on whether the charge succeeds.

```ts auth.ts theme={null}
freeTrial: {
  days: 14,
  onTrialEnd: async ({ subscription }, ctx) => {
    await analytics.track("trial_ended", {
      subscriptionId: subscription.id,
      plan: subscription.plan,
    });
  },
}
```

### onTrialExpired

Fires if the trial expires without conversion. This typically happens when the customer never completes the authorization flow or the first charge fails repeatedly.

```ts auth.ts theme={null}
freeTrial: {
  days: 14,
  onTrialExpired: async (subscription, ctx) => {
    await downgradeUser(subscription.referenceId);
  },
}
```

## One trial per reference

The plugin enforces a single trial per `referenceId` (user ID or organization ID). If a user cancels their trial subscription and later upgrades to the same plan again, they will not receive a second trial. This prevents repeated trial abuse without requiring you to track trial usage manually.

If you need to reset trial eligibility for a specific customer, delete the old subscription rows from your database or create a new Razorpay customer for that reference.

## Common errors

| Error code | When it occurs |
| - | - |
| `TRIAL_ALREADY_USED` | The reference ID already consumed a trial in a previous subscription. |
| `SUBSCRIPTION_PLAN_NOT_FOUND` | The plan name passed to upgrade does not exist in the plugin config. |
| `CUSTOMER_NOT_FOUND` | The user does not have a `razorpayCustomerId`. Enable `createCustomerOnSignUp`. |


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.