Unit based usage

How to set up and record unit based usage in your application

Unit based usage (sometimes called seat based usage) is probably the most common usage type for SaaS applications, examples are:

  • Users
  • Seats
  • Monthly active users (MAU)

The starter kit has built-in support for seat based usage and monthly active contacts.

Registering usage

Usage of features is calculated in the getFeatureCounts function in the billing service.

The function is called with the billing account id and should return an object with the feature counts.

export const getFeatureCounts = async (args: { accountId: string }) => {
return {
users: 10,
}
}

Checking usage limits

Client

The @saas-ui-pro/billing package contains hooks to check usage limits.

import { useLimitReached } from '@saas-ui-pro/billing'
const members = 10 // eg the number of users in the workspace returned from the API.
const limitReached = useLimitReached('users', members.length)

This will compare the supplied member count to the usage limit configured in the active plan of the user.

The BillingProvider containing the plans and user subscription info can be found in apps/web/features/billing/providers/billing-provider.tsx.

You should never depend only on the client to check for usage limits, always make sure to check the usage limits on the server as well.

Server

The billing service of the API has a limitReached function that can be used to check if a limit has been reached.

It works the same way as the client side hook, but it takes the account id as argument and returns a boolean value.

// packages/api/modules/my-module/my-module.service.ts
import { limitReached, throwIfLimitReached } from '#modules/billing'
const limitReached = await limitReached({
planId,
featureId: 'users',
quantity: 10,
}) // true or false
throwIfLimitReached({
planId,
featureId: 'users',
quantity: 10,
}) // throws an error if the limit is reached

Was this helpful?