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
If true, throws an error when customer is not found instead of returning null.
Array of fields to expand in the response (e.g., ['subscriptions']).
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.
true while the initial query is loading.
true if the query encountered an error.
The error object if the query failed.
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;
}
};
ID of the plan to attach.
Feature quantities to set (e.g., { seats: 5 }).
Free trial configuration.
URL to redirect to after checkout.
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',
});
ID of the plan to update.
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>;
ID of the feature to check.
Returns:
Whether the customer has access to this feature.
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
Return Value
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
Filter events by feature ID.
Number of events per page.
customRange
{ start: Date, end: Date }
Custom date range for filtering events.
Return Value
Array of event objects for the current page.
Current page number (0-indexed).
Whether more pages are available.
Whether previous pages exist.
Navigate to the next page.
Navigate to the previous page.
goToPage
({ pageNum: number }) => void
Navigate to a specific page.
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
Feature ID to aggregate events for.
Time range preset (e.g., 'last_7_days', 'last_30_days', 'this_month').
binSize
'hour' | 'day' | 'week' | 'month'
Aggregation interval.
Custom property to group by.
customRange
{ start: Date, end: Date }
Custom date range (overrides range parameter).
Return Value
Array of aggregated data points.
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
ID of the referral program.
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.
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}`);
}
}