Skip to main content

Overview

Autumn provides React hooks for managing customer data, subscriptions, plans, events, and referrals. All hooks are built on TanStack Query and return standard query results with additional methods.

useCustomer

Fetches or creates an Autumn customer and provides billing actions.
import { useCustomer } from 'autumn-js/react';

function BillingComponent() {
  const { data: customer, attach, check, isLoading } = useCustomer();
  
  if (isLoading) return <div>Loading...</div>;
  
  return (
    <div>
      <h1>Welcome, {customer?.email}</h1>
      <button onClick={() => attach({ planId: 'plan_pro' })}>
        Subscribe to Pro
      </button>
    </div>
  );
}

Parameters

errorOnNotFound
boolean
If true, throws an error when customer is not found instead of returning null.
expand
CustomerExpand[]
Array of fields to expand in the response (e.g., ['subscriptions']).
queryOptions
UseQueryOptions
TanStack Query options for customizing the query behavior.

Return Value

Returns a query result with customer data and billing methods:
data
Customer | null | undefined
The customer object. undefined while loading, null if not found.
isLoading
boolean
true while the initial query is loading.
isError
boolean
true if the query encountered an error.
error
AutumnClientError | null
The error object if the query failed.
refetch
() => Promise<...>
Refetch the customer data.

Billing Methods

attach

Attaches a plan to the customer. Handles new subscriptions, upgrades, and downgrades.
const { attach } = useCustomer();

const handleSubscribe = async () => {
  const result = await attach({
    planId: 'plan_pro',
    freeTrial: { days: 14 },
    quantities: { seats: 5 },
  });
  
  // Automatically redirects to checkout if payment required
  if (result.nextAction?.url) {
    window.location.href = result.nextAction.url;
  }
};
planId
string
required
ID of the plan to attach.
quantities
Record<string, number>
Feature quantities to set (e.g., { seats: 5 }).
freeTrial
{ days: number }
Free trial configuration.
discounts
string[]
Discount codes to apply.
returnUrl
string
URL to redirect to after checkout.
openInNewTab
boolean
Open checkout in a new tab instead of redirecting.

previewAttach

Previews billing changes without making any changes. Use this to show customers what they’ll be charged.
const { previewAttach } = useCustomer();

const preview = await previewAttach({
  planId: 'plan_pro',
  quantities: { seats: 5 },
});

console.log('Total:', preview.total);
console.log('Line items:', preview.lineItems);

updateSubscription

Updates an existing subscription. Use to modify feature quantities, cancel, or change plan configuration.
const { updateSubscription } = useCustomer();

// Update quantities
await updateSubscription({
  planId: 'plan_pro',
  quantities: { seats: 10 },
});

// Cancel subscription
await updateSubscription({
  planId: 'plan_pro',
  action: 'cancel',
});
planId
string
required
ID of the plan to update.
quantities
Record<string, number>
New feature quantities.
action
'cancel'
Action to perform (currently only 'cancel' is supported).

previewUpdateSubscription

Previews subscription update changes without applying them.
const { previewUpdateSubscription } = useCustomer();

const preview = await previewUpdateSubscription({
  planId: 'plan_pro',
  quantities: { seats: 10 },
});

console.log('Prorated charge:', preview.proratedAmount);

check

Checks feature access and balance locally (no API call). This is computed from the customer data.
const { check, data: customer } = useCustomer();

if (!customer) return null;

const result = check({ featureId: 'api_calls' });

if (!result.allowed) {
  return <div>You've reached your API call limit</div>;
}

return <div>Remaining: {result.balance}</div>;
featureId
string
required
ID of the feature to check.
Returns:
allowed
boolean
Whether the customer has access to this feature.
balance
number
Remaining balance for the feature (for usage-based features).

multiAttach

Attaches multiple plans in a single operation.
const { multiAttach } = useCustomer();

await multiAttach({
  plans: [
    { planId: 'plan_pro', quantities: { seats: 5 } },
    { planId: 'plan_addon', freeTrial: { days: 7 } },
  ],
});

setupPayment

Creates a payment setup session to add or update payment methods.
const { setupPayment } = useCustomer();

const result = await setupPayment({
  returnUrl: 'https://example.com/billing',
});

// Redirect to Stripe setup page
window.location.href = result.url;

openCustomerPortal

Opens the Stripe customer billing portal.
const { openCustomerPortal } = useCustomer();

const handleManageBilling = async () => {
  const result = await openCustomerPortal({
    returnUrl: 'https://example.com/settings',
  });
  
  window.location.href = result.url;
};

useListPlans

Fetches all available plans.
import { useListPlans } from 'autumn-js/react';

function PricingPage() {
  const { data: plans, isLoading } = useListPlans();
  
  if (isLoading) return <div>Loading plans...</div>;
  
  return (
    <div>
      {plans?.map(plan => (
        <div key={plan.id}>
          <h3>{plan.name}</h3>
          <p>{plan.price} / {plan.interval}</p>
        </div>
      ))}
    </div>
  );
}

Parameters

queryOptions
UseQueryOptions
TanStack Query options.

Return Value

data
Plan[]
Array of plan objects.
Plus standard TanStack Query properties (isLoading, isError, error, refetch, etc.).

useListEvents

Fetches events for the current customer with pagination.
import { useListEvents } from 'autumn-js/react';

function EventsLog() {
  const {
    list: events,
    page,
    hasMore,
    nextPage,
    prevPage,
    isLoading,
  } = useListEvents({
    featureId: 'api_calls',
    limit: 50,
  });
  
  if (isLoading) return <div>Loading...</div>;
  
  return (
    <div>
      <table>
        {events?.map(event => (
          <tr key={event.id}>
            <td>{event.timestamp}</td>
            <td>{event.value}</td>
          </tr>
        ))}
      </table>
      
      <div>
        <button onClick={prevPage} disabled={page === 0}>
          Previous
        </button>
        <span>Page {page + 1}</span>
        <button onClick={nextPage} disabled={!hasMore}>
          Next
        </button>
      </div>
    </div>
  );
}

Parameters

featureId
string
Filter events by feature ID.
limit
number
default:"100"
Number of events per page.
customRange
{ start: Date, end: Date }
Custom date range for filtering events.
queryOptions
UseQueryOptions
TanStack Query options.

Return Value

list
Event[]
Array of event objects for the current page.
page
number
Current page number (0-indexed).
hasMore
boolean
Whether more pages are available.
hasPrevious
boolean
Whether previous pages exist.
nextPage
() => void
Navigate to the next page.
prevPage
() => void
Navigate to the previous page.
goToPage
({ pageNum: number }) => void
Navigate to a specific page.
resetPagination
() => void
Reset to page 0.

useAggregateEvents

Aggregates events by time period or custom grouping.
import { useAggregateEvents } from 'autumn-js/react';

function UsageChart() {
  const { list: data, total, isLoading } = useAggregateEvents({
    featureId: 'api_calls',
    range: 'last_30_days',
    binSize: 'day',
  });
  
  if (isLoading) return <div>Loading...</div>;
  
  return (
    <div>
      <h3>Total usage: {total}</h3>
      <Chart data={data} />
    </div>
  );
}

Parameters

featureId
string
required
Feature ID to aggregate events for.
range
string
Time range preset (e.g., 'last_7_days', 'last_30_days', 'this_month').
binSize
'hour' | 'day' | 'week' | 'month'
Aggregation interval.
groupBy
string[]
Custom property to group by.
customRange
{ start: Date, end: Date }
Custom date range (overrides range parameter).
queryOptions
UseQueryOptions
TanStack Query options.

Return Value

list
AggregatedEvent[]
Array of aggregated data points.
total
number
Total aggregated value across all bins.

useReferrals

Manages referral codes for the current customer.
import { useReferrals } from 'autumn-js/react';

function ReferralProgram() {
  const { data, refetch, redeemCode, isLoading } = useReferrals({
    programId: 'referral_program_123',
  });
  
  const handleCreateCode = async () => {
    const result = await refetch();
    console.log('Your code:', result.data?.code);
  };
  
  const handleRedeemCode = async (code: string) => {
    await redeemCode({ code });
  };
  
  return (
    <div>
      {data?.code ? (
        <div>Your referral code: {data.code}</div>
      ) : (
        <button onClick={handleCreateCode}>Create Referral Code</button>
      )}
    </div>
  );
}

Parameters

programId
string
required
ID of the referral program.
queryOptions
UseQueryOptions
TanStack Query options. Note: Query is disabled by default, call refetch() to create a code.

Return Value

data
{ code: string } | undefined
The created referral code data.
refetch
() => Promise<...>
Create or fetch a new referral code.
redeemCode
(params: { code: string }) => Promise<...>
Redeem a referral code for the current customer.

Advanced: Direct Client Usage

For non-React contexts, use the client directly:
import { createAutumnClient } from 'autumn-js/react';

const client = createAutumnClient({
  backendUrl: 'https://api.example.com',
  pathPrefix: '/api/autumn',
  includeCredentials: true,
});

const customer = await client.getOrCreateCustomer();
const plans = await client.listPlans();

Error Handling

All hooks handle errors using TanStack Query’s error handling:
const { error, isError } = useCustomer();

if (isError && error instanceof AutumnClientError) {
  console.error('Failed to load customer:', error.message);
  console.error('Error code:', error.code);
}
For mutations (billing methods), use try/catch:
const { attach } = useCustomer();

try {
  await attach({ planId: 'plan_pro' });
} catch (error) {
  if (error instanceof AutumnClientError) {
    alert(`Failed to subscribe: ${error.message}`);
  }
}

Build docs developers (and LLMs) love