# Changelog (/docs/changelog)
What has changed here, newest first.
**Four features move from planned to live**, each documented to the same depth
as quests: a model page for the vocabulary, then the build.
* [Battlepass](/docs/battlepass/model): seasons, free and premium lanes, claim one tier or all of them
* [Store](/docs/store/model): listings in your own currencies, the purchase gate, Shopify orders, purchase history
* [Leaderboard](/docs/leaderboard/model): the XP and quests boards, and the fan's own row
* [Newsfeed](/docs/newsfeed/model): members-only posts, reactions and threaded comments
* [Predictions](/docs/predictions/model): the lock, one final pick, the split and payout. Runs on quests today, moving to its own surface
**New pages for the pieces they share.**
* [Linking accounts](/docs/linking): connecting Discord, X, Twitch and more, with typed errors and expiry
* [Prizes and inventory](/docs/inventory/prizes): prize detail forms, loot box claims, personalisation
* [Membership](/docs/membership): one gate across the battlepass, the store and the newsfeed
**Corrections to existing pages**, where they had fallen behind the package:
* `fetchRewards` on `Quest.Provider` is a flag, not a function
* `resolveQuestRewardChrome` takes `{ reward, quest }` and returns `imageSrc`
* A fan's linked accounts come from `useLinkedSocials`, not the profile, which omits expiry dates
* `Parser` and `resolveMessage` are imported from `@xborglabs/fanbase-react`
* Template routing no longer uses `getApiType`, which returns the submit path rather than a family. Every typed template sends `{ text }`
* A bare `npm install` now works, and installs a `latest` tag that trails `alpha` and `beta`
[Hooks](/docs/reference/hooks), [Components](/docs/reference/components) and
[API endpoints](/docs/reference/api) now cover every feature.
**Built to be read by an agent.** The whole point of these pages. Hand them to
Claude, Cursor or Codex and review the diff.
* Every page has a Markdown source and a copy button
* The whole site at [/llms.txt](/llms.txt) and [/llms-full.txt](/llms-full.txt)
* Any request asking for Markdown by content type gets Markdown back, not HTML
* Sequenced prompts to paste in [Integrate with an agent](/docs/agents)
**[Create](/create).** Set your own colours, fonts, corner radii and shadow and
watch neutral components take them. Get code returns what you built as:
* CSS custom properties
* A Tailwind `@theme` block
* A React component using `useQuestsList()` with your values applied
**The showcase.** One quest per template family, so you can see the requirement
UI you write and the payload your submit sends:
* Poll, quiz, prediction, text answer
* Visit link, image upload, empty-body check-in
Three simulated partner products run that quest through the same state machine,
so changing what is true about the fan moves all three at once.
**The documentation itself**, covering the live surface: fan sign-in, questing,
rewards and claims.
* Installation, environment and a quickstart
* The concept model: how it fits together, tenancy, the quest model
* Seven guides, from sign-in through to using your own design system
* Reference for the provider, hooks, components, quest templates and endpoints
**A check against stale pages.** Every change runs a drift check that fails the
build on:
* A hardcoded package version in prose
* An SDK export named here that the published package does not have
* A broken internal link
# Introduction (/docs)
The FanBase SDK puts fan accounts, quests and rewards inside your own product.
Sign in, complete a quest, claim a reward. All of it rendered by your components.
There is no FanBase UI to accept and no iframe. The packages ship logic, state
and unstyled primitives. Everything a fan sees is yours.
## Start here [#start-here]
Provider, sign-in, and a live quest list.
Registry auth, the alpha tag, peer deps.
Two prompts to paste, then review the diff.
The layer model and the quest state machine.
## What is live today [#what-is-live-today]
A fan signs in with Discord, Google, X or Twitch, sees the quests you configured,
completes one, and claims the reward. That path is live and every page here
covers it.
Battlepass, predictions, store, newsfeed and leaderboard are not in the package.
[Feature status](/docs/status) tracks each one.
## Popular topics [#popular-topics]
The main build. One view, every template.
Reward slugs, claim payloads, lootbox polling.
Why `INACTIVE` must never reach a fan.
`asChild`, and what to take from the SDK.
## Two packages [#two-packages]
| Package | What it is |
| -------------------------- | ------------------------------------------------------------------------------------------------------------ |
| `@xborglabs/fanbase-core` | Framework-free logic. API client, quest state machine, template registry, reward resolution, string catalog. |
| `@xborglabs/fanbase-react` | React bindings. Provider, hooks, and slot-based components that render your markup. |
Core has no React dependency, so a Vue or Svelte binding is possible later.
React is the only one that exists today.
## Built to be read by a coding agent [#built-to-be-read-by-a-coding-agent]
Most partners hand these docs to Claude, Cursor or Codex and review the diff.
That is the intended path. The package ships the files an agent reads:
```
node_modules/@xborglabs/fanbase-react/llms.txt
node_modules/@xborglabs/fanbase-react/quest-templates.md
node_modules/@xborglabs/fanbase-react/quest-description.md
node_modules/@xborglabs/fanbase-react/quest-rewards.md
node_modules/@xborglabs/fanbase-react/prompt.md
node_modules/@xborglabs/fanbase-react/skills/fanbase/SKILL.md
```
`llms.txt` is the entry point. The whole site is also at [/llms.txt](/llms.txt)
and [/llms-full.txt](/llms-full.txt). A first integration usually takes under
half an hour.
Every page also works read top to bottom without an agent.
## Getting access [#getting-access]
Two things, one on each side. From us, a community provisioned on the platform
and its environment values. From you, a GitHub token with `read:packages` on the
`@xborglabs` org. [Installation](/docs/getting-started/installation) covers both.
# Linking accounts (/docs/linking)
Separate from sign-in, and the reason most social quests work at all. A fan signs in with Google, opens a Discord quest, and needs their Discord linked before they can do it.
## How it works [#how-it-works]
Five steps, and your app owns two of them:
1. A quest tells you an account is missing.
2. You send the fan to the proxy to connect it.
3. The proxy sends them back to your callback page with a token.
4. You redeem the token.
5. The quest re-checks and opens up.
Linking needs a fan who is already signed in. It never signs anyone in, and never touches their session.
## 1. Know what is missing [#1-know-what-is-missing]
Do not scan the fan's accounts yourself. The quest's state machine already knows, and tells you why the quest is closed:
```tsx
import { useQuest } from '@xborglabs/fanbase-react'
const { state } = useQuest()
const reason = state.machine.reason
```
| `state.machine.reason` | Means | Show |
| --------------------------- | ------------------------------------------------- | --------------------------------------------------- |
| `SOCIAL_NOT_LINKED` | The quest needs an account the fan has not linked | A connect button |
| `SOCIAL_EXPIRED` | They linked it, but the link has expired | A reconnect prompt, over the same button |
| `SERVER_SELECTION_REQUIRED` | A Riot account is linked with no region | A region picker. This one is not solved by linking. |
`state.disabledReasonLabel` already says which account, in a sentence you can show. [Quest detail](/docs/quests/detail#social-and-bind-quests) covers where it goes on the page.
## 2. Send them to connect [#2-send-them-to-connect]
A plain link. No request, no button handler.
```tsx
import { BIND_ACCOUNT_TYPE, buildBindUrl } from '@xborglabs/fanbase-react'
const connectUrl = buildBindUrl({
oauthProxyUrl: proxyUrl,
provider: 'discord',
redirectUrl: `https://yoursite.com/link/callback?accountType=${BIND_ACCOUNT_TYPE.DISCORD}`,
})
Connect Discord
```
`proxyUrl` is the same one you built for sign-in. [Building the sign-in URL](/docs/sign-in#building-the-sign-in-url).
Put the account type in your `redirectUrl`. Worth reading twice: when the fan comes back, nothing in the callback says what they just connected, or even that it was a link rather than a sign-in. The only way your callback page knows is if you told it on the way out. Like sign-in, the redirect URL has to be registered with the proxy.
`provider` is the proxy's lowercase name for the service, `discord` or `twitter`. `BIND_ACCOUNT_TYPE.DISCORD` is the SDK's name for the same account. They are two different vocabularies, which is why both appear above.
## 3. Read the callback [#3-read-the-callback]
On your callback page:
```tsx
import { parseBindCallback } from '@xborglabs/fanbase-react'
const callback = parseBindCallback(window.location.search)
// { token: '…', accountType: 'DISCORD' } or null
```
It returns `null` when there is no token in the URL. Show a message in that case, not a spinner.
It reads the account type from the URL you built in step 2. If it cannot find one, `accountType` is `null`. Keep the type you sent in `sessionStorage` as a backup, the same way sign-in carries the provider through.
## 4. Redeem the token [#4-redeem-the-token]
```tsx
import { useBind } from '@xborglabs/fanbase-react'
const { bind, isPending } = useBind()
await bind({ token: callback.token, accountType })
```
Redeem it on the callback page, straight away. **The token expires five minutes after the redirect.** Not after a form, not behind a "Confirm" button.
The token also works more than once inside those five minutes, so treat it like a password. Keep it out of any URL you share, your logs and your analytics, and drop it once it is redeemed.
## 5. Let the quest re-check [#5-let-the-quest-re-check]
`bind` refreshes the fan's linked accounts and every quest on success. For the quest to see the new account, feed the linked accounts into it:
```tsx
import { Quest, useLinkedSocials } from '@xborglabs/fanbase-react'
const { data: socials = [] } = useLinkedSocials()
const profile = useFanProfile() // wallets still come from the fan profile
```
The quest's button enables on its own, with no page reload.
Use `useLinkedSocials` for this, not the fan profile. It is the only read that includes when a link expires and which Riot region an account is on, and the quest needs both to tell an expired link from a working one. An `authProfile` built from the profile endpoint leaves the fan stuck on an expired link with no way to see why.
Do not refresh the session afterwards. Linking does not change it, and a session refresh here only adds a request.
## What can be linked [#what-can-be-linked]
| `BIND_ACCOUNT_TYPE` | Can also sign in | Notes |
| ------------------- | ---------------- | ----------------------------------------------------- |
| `DISCORD` | yes | |
| `TWITTER` | yes | |
| `TWITCH` | yes | Expires after 30 days |
| `STEAM` | no | |
| `FACEIT` | no | |
| `RIOT` | no | Rank quests need a region, which linking does not set |
| `YOUTUBE` | no | |
| `EPIC` | no | |
| `BATTLENET` | no | Expires after one day |
| `SPOTIFY` | no | |
| `BUSHI` | no | Game-specific. Ask us before relying on it. |
| `APEIRON` | no | Game-specific. Ask us before relying on it. |
Google can sign a fan in, but it cannot be linked. Wallets are not linked this way at all: a wallet quest takes the address as its input. [Quest templates](/docs/quests/templates).
## Expired links [#expired-links]
Twitch and Battle.net links expire. The platform does not stop the fan using an expired one, it just records the date, and the quest machine checks it and reports `SOCIAL_EXPIRED`.
Show a reconnect prompt, pointing at the same connect link as step 2. Relinking replaces the old link. It is not an error, and the fan does not need to disconnect first.
## Riot regions [#riot-regions]
Riot rank quests need to know which region the fan plays on, and linking a Riot account does not record it. The platform has no way to set it through this flow, so a linked Riot account alone cannot clear `SERVER_SELECTION_REQUIRED`.
If Riot rank quests matter to your community, talk to your FanBase contact before you launch them.
## Errors [#errors]
| Error | Means | Show |
| ------------------------------ | ------------------------------------------------------------ | --------------------------------------------------------------- |
| `BindTokenExpiredError` | The five minutes ran out | "That took too long. Try again", and the connect link again |
| `BindAccountTypeMismatchError` | The account type you sent does not match what they connected | A bug in your redirect URL. Log it. |
| `SocialAlreadyBoundError` | This account is linked to a different fan | "Already connected to another account". Retrying will not help. |
| `SocialReconnectionLimitError` | They have relinked too many times | Point them at support. Do not retry automatically. |
Switch on the error class, never the message.
One case raises no error at all. For Discord, X and Twitch, linking also lets the account sign in. If that account already signs in a different fan, the platform links it and quietly skips the sign-in part, and reports success. So after a link, trust `useLinkedSocials`, not the success response.
## Checklist [#checklist]
* A quest missing an account shows a connect link, driven by `state.machine.reason`
* The redirect URL carries the account type
* The callback page redeems the token straight away
* The quest's button enables after linking, with no reload
* `authProfile.socials` comes from `useLinkedSocials`
* An expired Twitch link shows a reconnect prompt
* Each of the four errors shows its own message
* The token never reaches a log or an analytics call
# Membership (/docs/membership)
What a fan pays for, and the check that decides what they can open. It works the same way in three places, so it gets one page.
## Tiers [#tiers]
A community has two membership tiers, set up in the Hub: **Free** and **Premium**. Each has a name, a badge and a **rank**.
Free is rank 1. Every fan who joins the community is on it. Premium is rank 2, and it is the tier fans pay for.
A fan who has not joined the community at all has no tier, and counts as rank 0.
Tiers, prices and what each one unlocks are set in the Hub. The SDK reads membership. It cannot sell or upgrade one: that happens in your product, through your own checkout.
## The rule [#the-rule]
One comparison, the same one the platform uses:
> A fan can open something when their rank is **at or above** the rank it asks for.
Premium opens everything. Free opens nothing paid. A fan with no membership is below both tiers, and joining the community is what puts them on the free one.
## Where it applies [#where-it-applies]
| Feature | What gets locked | How the SDK checks it |
| ----------- | --------------------- | ----------------------------------------------------------------------------------------------------- |
| Battlepass | The premium lane | Inside `Battlepass.Provider`. See [Tier states](/docs/battlepass/season#tier-states). |
| Store | Members-only listings | Inside `Store.Listing`, as the first gate reason. See [The gate](/docs/store/buy#the-gate). |
| Newsfeed | Members-only posts | `resolveNewsfeedPremiumGate`. See [The members-only lock](/docs/newsfeed/feed#the-members-only-lock). |
| Leaderboard | Nothing | The board is public. |
In the battlepass and the store you never check membership yourself. The provider does it and hands you the answer. The newsfeed has no provider, so you call the gate on each post.
## Name the tier [#name-the-tier]
Every gate that locks something tells you which tier would unlock it, by name:
```tsx
reason.requiredTierName // "Premium"
```
Use it rather than hardcoding the word. The name is set in the Hub, so a community can call its paid tier whatever suits its fans, and "For Premium members" stays right when it is renamed.
## Reading it yourself [#reading-it-yourself]
For anything the three features do not cover, like a members-only page of your own:
```tsx
import {
getMembershipRequirement,
resolveMembershipGate,
useMembership,
useMembershipTiers,
} from '@xborglabs/fanbase-react'
const { data: tiers = [] } = useMembershipTiers()
const { data: membership } = useMembership()
const required = getMembershipRequirement(item.requirements) // { tierId } or null
const gate = required
? resolveMembershipGate({ requiredTierId: required.tierId, tiers, membership })
: null
// gate.locked, gate.requiredTier, gate.reason.requiredTierName
```
No `communityId` anywhere. Both hooks resolve it from the `slug` on [`FanbaseProvider`](/docs/reference/provider).
`useMembership().data` also carries the fan's `userId`. It is the only place a signed-in fan's id is available, since the session holds tokens only. The leaderboard uses it to highlight the fan's own row.
## The error to expect [#the-error-to-expect]
Worth reading twice.
For a fan who has not joined the community, the membership read fails with a server error rather than returning nothing. The SDK does not retry it and does not hide it, because a real outage looks identical.
So an error from `useMembership` is normal, and it usually means "not a member". Do not show an error screen for it. Treat it as rank 0: pass `membership: undefined` to the gate, which locks everything paid, and offer the fan a way to join.
```tsx
const { data: membership, isError } = useMembership()
// isError here most often means "not a member yet", not "something broke"
const gate = resolveMembershipGate({ requiredTierId: required.tierId, tiers, membership: isError ? undefined : membership })
```
The providers already do this. It only matters when you read membership yourself.
## Joining comes first [#joining-comes-first]
A fan who has not joined the community gets a different reason from the quest machine, `COMMUNITY_GUEST`, and it takes priority over a membership lock. That is the right order: joining is the step that puts them on the free tier, so it is the first thing to ask for.
## XP is not membership [#xp-is-not-membership]
Two numbers on a fan look like rank and are unrelated. Membership rank is whether they are Free or Premium. Their XP level is how much they have earned. A brand new Premium member can be level 1, and a free fan can be level 40.
The fan's XP comes from `useCommunityXP`. It drives the battlepass ladder and any XP bar in your product. [The leaderboard model](/docs/leaderboard/model#four-numbers-called-rank) lists all four numbers that get called rank.
## Checklist [#checklist]
* Every lock names the tier that would open it
* A fan with no membership sees paid content locked, not an error
* An error from `useMembership` leads to a join prompt, not an error screen
* A Premium fan opens everything a free fan does
* XP bars read `useCommunityXP`, never membership rank
# Fan sign-in (/docs/sign-in)
[Quickstart](/docs/getting-started/quickstart) has the minimum version. This page covers the parts you hit second.
## How it works [#how-it-works]
Your app builds a sign-in URL and sends the fan to the FanBase OAuth proxy. The proxy runs the handshake with Discord, Google, X or Twitch. The fan approves. The proxy returns them to your callback with a one-time token. You exchange that token for a session.
The proxy exists so you never handle provider client secrets and never register your app with four different providers.
## Providers [#providers]
`google`, `discord`, `twitter`, `twitch`. Lowercase, exact.
Which ones you offer is your choice. Most gaming and esports partners lead with Discord because most quests involve a Discord account and it saves the fan a second linking step later.
## Building the sign-in URL [#building-the-sign-in-url]
```tsx
import { buildOAuthProxyUrl, buildLoginUrl } from '@xborglabs/fanbase-react'
const proxyUrl = buildOAuthProxyUrl({
oauthProxyUrl: import.meta.env.VITE_FANBASE_OAUTH_PROXY_URL,
proxySecret: import.meta.env.VITE_FANBASE_OAUTH_PROXY_SECRET,
})
```
Build this once. It resolves the secret against the proxy base, and the trailing slash on the base is load-bearing when the proxy sits on a path. [Environment](/docs/getting-started/environment#the-trailing-slash-on-the-proxy-url).
```tsx
const loginUrl = buildLoginUrl({
oauthProxyUrl: proxyUrl,
provider: 'discord',
redirectUrl: 'https://yoursite.com/auth/callback?provider=discord',
})
```
`redirectUrl` is absolute and has to be registered with the proxy. Local ports and preview deploys included. Send us every URL you need.
## Carrying the provider through [#carrying-the-provider-through]
The proxy returns to your callback with `?token=` only. It does not tell you which provider was used, and the exchange needs it.
Two ways, and doing both costs nothing:
```tsx
sessionStorage.setItem('fanbase.provider', provider)
const redirectUrl = new URL(import.meta.env.VITE_FANBASE_OAUTH_REDIRECT_URL)
redirectUrl.searchParams.set('provider', provider)
```
The query param survives a new tab. `sessionStorage` survives a redirect chain that drops params. Between them you are covered.
## The callback page [#the-callback-page]
```tsx
import { useEffect, useState } from 'react'
import { useFanbase, parseOAuthCallbackToken } from '@xborglabs/fanbase-react'
import { useNavigate } from 'react-router-dom'
export function AuthCallback() {
const { state, actions } = useFanbase()
const navigate = useNavigate()
const [error, setError] = useState(null)
useEffect(() => {
if (!state.ready) return
const token = parseOAuthCallbackToken(window.location.href)
if (!token) {
setError('No sign-in token found. Please try again.')
return
}
const provider =
new URLSearchParams(window.location.search).get('provider') ??
sessionStorage.getItem('fanbase.provider')
if (!provider) {
setError('Could not determine the sign-in method.')
return
}
actions
.loginWithToken({ provider, token })
.then(() => {
sessionStorage.removeItem('fanbase.provider')
navigate('/quests', { replace: true })
})
.catch(() => setError('Sign-in failed. Please try again.'))
}, [state.ready])
if (error) return navigate('/')} />
return
}
```
Three things this page gets right that a rushed version does not.
**It waits for `state.ready`.** The provider restores an existing session from your adapter on mount. Exchanging a token before that finishes leaves you in an inconsistent state. This is the single most common callback bug.
**It handles a missing token.** Fans land on callback URLs from history and bookmarks. Show something rather than hanging on a spinner.
**It replaces the history entry.** The token is single-use, so a back button that returns here would fail. `replace: true` removes it from history.
Under the hood the exchange is `POST /v1/user/auth/{provider}/login`.
## Session state [#session-state]
```tsx
const { state, actions } = useFanbase()
state.ready // provider has finished restoring
state.session // null, or { accessToken, refreshToken }
```
Signed in means `state.session` is non-null with both tokens. The SDK attaches the access token as a Bearer header on every request. Nothing is stored in cookies, so no third-party cookie behaviour to work around.
## Session adapter [#session-adapter]
Any object with `get`, `set` and `clear`. The SDK does not care where the session lives.
```tsx
const session = {
get: () => JSON.parse(localStorage.getItem('fanbase.session') ?? 'null'),
set: (s) => localStorage.setItem('fanbase.session', JSON.stringify(s)),
clear: () => localStorage.removeItem('fanbase.session'),
}
```
`localStorage` is the default for a browser SPA. If your security posture wants tokens out of JS-readable storage, write an adapter that talks to your own backend and keeps them in httpOnly cookies. Nothing else in your integration changes.
## Signing out [#signing-out]
```tsx
actions.logout()
```
Clears the adapter and the in-memory session. Local to your app; it does not sign the fan out of Discord.
## Linking social accounts [#linking-social-accounts]
Separate from sign-in. A fan signs in with Google and then needs a Discord account linked to complete a Discord quest. Same proxy round trip, different intent, and a few traps of its own, including a token that expires in five minutes. [Linking accounts](/docs/linking) covers the whole flow.
## Fan profile [#fan-profile]
Some quests are gated on what the fan has linked. To evaluate that, the machine needs the fan's linked accounts and wallets.
Linked accounts come from `useLinkedSocials`. Wallets come from the fan profile at `GET /v1/user/profile`:
```tsx
import { useLinkedSocials } from '@xborglabs/fanbase-react'
const { data: socials = [] } = useLinkedSocials()
const { data: profile } = useQuery({
queryKey: ['fanbase', 'profile'],
queryFn: () => meta.http.get('/v1/user/profile'),
enabled: !!state.session,
})
const authProfile = { socials, wallets: profile?.wallets }
```
Do not take the socials from the profile as well. The profile leaves out when each link expires and which Riot region an account is on, and without those the machine cannot tell an expired link from a working one. `useLinkedSocials` is the only read that has both.
`meta.http` from `useFanbase()` is the SDK's authenticated client, so the tenant header and Bearer token are handled.
Fetch these once after sign-in and hold them. Every quest detail view needs them and refetching per quest is wasted. [Quest detail](/docs/quests/detail#passing-the-fan-profile) shows where they go.
## Checklist [#checklist]
* Sign-in URL sends the fan to the provider's consent screen
* Callback exchanges the token with the same provider that started it
* `state.session` has both tokens
* Refresh keeps the fan signed in
* `logout()` clears it
* Landing on the callback with no token shows a message, not a spinner
* Every redirect URL you use is registered, local ports included
# Feature status (/docs/status)
What is in the SDK today and what is coming. Updated as things ship.
Statuses: **Live** in the package and documented. **In build** being worked on. **Planned** agreed and scoped, not started. **Exploring** under discussion.
## Live [#live]
In the `alpha` and `beta` packages, and documented here.
| Feature | Notes |
| -------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
| Fan sign-in | Discord, Google, X, Twitch, through the OAuth proxy. [Guide](/docs/sign-in) |
| Linking accounts | Discord, X, Twitch, Steam, Riot and more, with typed errors and expiry. [Guide](/docs/linking) |
| Quests | The full loop: list, detail, all template families, submit. [Guide](/docs/quests/detail) |
| Predictions | Options, a lock, one final pick, a visible split, payout on resolution. Runs on the quest system today. [Guide](/docs/predictions/model) |
| Rewards and claims | Every reward type, and the loot box reveal. [Guide](/docs/quests/rewards) |
| Quest descriptions | Structured content rendered into your design. [Guide](/docs/quests/descriptions) |
| Battlepass | Seasons, free and premium lanes, claim one or claim all. [Guide](/docs/battlepass/model) |
| Store | Listings, filters, the purchase gate, Shopify orders, purchase history. [Guide](/docs/store/model) |
| Leaderboard | XP and quest boards, and the fan's own row. [Guide](/docs/leaderboard/model) |
| Newsfeed | The feed, members-only posts, reactions and threaded comments. [Guide](/docs/newsfeed/model) |
| Prizes and inventory | Prize detail forms, loot box claims, owned items. [Guide](/docs/inventory/prizes) |
| Personalisation | Profile pictures, borders and backgrounds, equipped per community. [Guide](/docs/inventory/personalization) |
| Membership | One gate across the battlepass, store and newsfeed. [Guide](/docs/membership) |
| Display strings | A catalog with an i18n adapter. [Guide](/docs/design/display-strings) |
The leaderboard and the newsfeed are not in the `latest` tag yet. [Which tag](/docs/getting-started/installation#which-tag).
## In build [#in-build]
| Feature | Notes |
| ------- | --------------------------------------------------------------------------------------------------------------------------- |
| Events | Time-boxed competitions with their own leaderboard and prizes by finishing position. Quests can already belong to an event. |
## Planned [#planned]
Priority order. Dates are not committed until the item moves to In build.
| Feature | Notes |
| -------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- |
| Predictions as their own surface | Moving predictions off the quest system into a surface of their own. The behaviour stays the same; where your code reads it from changes. |
| Avatar system | Fan avatars beyond the three personalisation slots. |
## Exploring [#exploring]
| Item | Notes |
| ----------------------------- | -------------------------------------------------------------------------------- |
| Self-serve community creation | Sign up, get configuration and prompts, integrate without us in the loop. |
| Non-React bindings | Core has no framework dependency, so Vue or Svelte is possible. No timeline. |
| Wallet connect | Wallet quests take a typed address today. A connector is a bigger piece of work. |
## Not in the SDK [#not-in-the-sdk]
Available on the platform but through other surfaces, not these packages.
| | Where it lives |
| -------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Connecting Shopify | Configured in the Hub. The SDK shows a Shopify-fulfilled purchase and its delivery status, but never talks to Shopify itself. [Shopify orders](/docs/store/buy#shopify-orders). |
| Buying or upgrading a membership | Your own checkout. The SDK reads membership and gates on it. [Membership](/docs/membership). |
| Admin and content creation | The Hub. Quests, seasons, listings and posts are all created there. Deliberately not in a client SDK. |
| Community data export | Data API with an API key. Server-to-server. |
## Asking for something [#asking-for-something]
If a Planned item is what decides your integration, tell your FanBase contact. Partner demand moves this list.
# Integrate with an agent (/docs/agents)
The intended path. Hand your agent the prompts below, review the diff, ship.
Works with Claude Code, Cursor, Codex, Windsurf or anything else that can read files in your repo.
## Before you start [#before-you-start]
[Install the packages](/docs/getting-started/installation) and put your [environment values](/docs/getting-started/environment) in `.env`. The agent needs the packages present, because the files it reads ship inside them.
## What the agent reads [#what-the-agent-reads]
```
node_modules/@xborglabs/fanbase-react/llms.txt
node_modules/@xborglabs/fanbase-react/quest.md
node_modules/@xborglabs/fanbase-react/bind.md
node_modules/@xborglabs/fanbase-react/prize.md
node_modules/@xborglabs/fanbase-react/battlepass.md
node_modules/@xborglabs/fanbase-react/store.md
node_modules/@xborglabs/fanbase-react/newsfeed.md
node_modules/@xborglabs/fanbase-react/leaderboard.md
node_modules/@xborglabs/fanbase-react/prompt.md
node_modules/@xborglabs/fanbase-react/skills/fanbase/SKILL.md
```
`llms.txt` is the entry point. Each of the feature files covers one feature end to end, and each one ends with a "Done when" the agent can check itself against. They ship inside the package, so they always match the version you installed.
After upgrading the packages, have the agent re-copy `skills/fanbase/SKILL.md`. A skill left over from an older version can miss features that `llms.txt` lists.
## Order [#order]
Three prompts, run in sequence. Sign-in first, questing second, then any other feature, one at a time. Do not combine them. A working sign-in is what makes everything after it verifiable, and an agent given everything at once tends to stub the auth and produce something that looks finished and is not.
## Prompt 1: sign-in [#prompt-1-sign-in]
```
Implement Fanbase OAuth in this app.
Read node_modules/@xborglabs/fanbase-react/llms.txt first, sections
Portal, FanbaseProvider, OAuth and Env. Do not invent APIs. If something
is not in that file, stop and ask.
Install if missing: @xborglabs/fanbase-core and @xborglabs/fanbase-react.
This app owns its QueryClient.
Wrap the app in FanbaseProvider with:
- tenant, slug, appId
- httpOptions: { gamerBaseUrl, locale }
- a session adapter { get, set, clear }, localStorage is fine
- our queryClient
Read config from these env keys, see .env:
VITE_FANBASE_TENANT
VITE_FANBASE_COMMUNITY_SLUG
VITE_FANBASE_APP_ID
VITE_FANBASE_GAMER_BASE_URL
VITE_FANBASE_LOCALE
VITE_FANBASE_OAUTH_PROXY_URL
VITE_FANBASE_OAUTH_PROXY_SECRET
VITE_FANBASE_OAUTH_REDIRECT_URL
Sign-in:
1. buildOAuthProxyUrl({ oauthProxyUrl, proxySecret })
2. buildLoginUrl({ oauthProxyUrl, provider, redirectUrl })
provider is one of google, discord, twitter, twitch. It is the
identity provider. Never pass a tenant or community slug here.
3. Carry the provider forward on the redirect as ?provider= and in
sessionStorage. The proxy returns only ?token=.
Callback page, at the exact URL in VITE_FANBASE_OAUTH_REDIRECT_URL:
- Wait for useFanbase().state.ready before doing anything
- parseOAuthCallbackToken(window.location.href)
- actions.loginWithToken({ provider, token })
- Handle a missing token with a message, not an endless spinner
- Replace the history entry after success, the token is single use
Logout is actions.logout().
Done when: the callback exchanges ?token= using the same provider that
started sign-in, state.session has accessToken and refreshToken, a page
refresh keeps the fan signed in, and logout clears the adapter.
```
## Prompt 2: questing [#prompt-2-questing]
Run after sign-in works end to end.
```
Implement Fanbase questing in this app.
Read, in this order:
- node_modules/@xborglabs/fanbase-react/llms.txt
- quest.md, the whole quest feature, including its reward catalog
- quest-templates.md, for requirement UI and submit payloads
- quest-description.md, for Parser, Quest.Description and the theme object
- bind.md, for linking an account a quest needs
- prize.md, for prize detail forms and the lootbox claim
- skills/fanbase/SKILL.md, an agent skill. If your tool loads skills from the
project, it finds this one and follows `llms.txt` without being told to.
Do not invent template names or payload shapes. If a template is not in
quest-templates.md, route it to the default empty-body branch.
List page:
- useQuestsList() only. One GET /v1/quests for the whole page.
- No per-quest detail calls and no allocation fetches for cards.
- Render our own card component from each row.
- Resolve quest status through resolveMessage('Quests.status.' + status).
Never render the raw enum, INACTIVE does not mean what it looks like.
Detail page:
- Quest.Provider with questId, and quest={row} seeded from the list.
Let the provider own that row. Do not copy it into local state.
- Pass fetchRewards, a flag, so the claim button knows a reward is waiting.
- Pass authProfile={{ socials, wallets }}. socials from useLinkedSocials(),
never from the profile, which omits expiry dates. wallets from
GET /v1/user/profile. Without it, gated quests stay disabled.
- Pass claimPayload, built with toAllocationClaimPayload, when a prize
requires details such as an email.
- Quest.Frame wraps our UI.
- Quest.Description with a theme object mapping to our classes.
- Requirement UI switched on a family you map from template.name, using the
Catalog in quest.md. Never switch on getApiType or getQuestType: they return
the submit path and a number, not a family.
- typed families (text, answer, prediction, quiz, poll, email, wallet,
image) use actions.submit(payload), not Quest.Submit
- empty-body families (visit, bind, progress, auto, unknown) use
Quest.Submit
- visit: an outbound , then a CTA bound to
state.canSubmit. Do not build a separate enabled flag.
- bind: a plain to buildBindUrl, carrying the account type in the
redirect URL, plus the CTA. The callback redeems with useBind() within
five minutes. Follow bind.md.
- CTA copy comes from state.buttonLabel. Disabled state comes from
state.canSubmit or state.canClaim. Show state.disabledReasonLabel when
the fan cannot act.
Rewards:
- resolveQuestRewardChrome({ reward, quest }) for presentation. It returns
undefined for an unknown slug: render nothing then.
- Show rewards before completion, from quest.rewards, not only after
- Claim with Quest.Claim or actions.claimAllAllocated(), never actions.claim()
alone, which claims a single allocation and leaves the rest
- give_lootboxes: after claim, poll getQuestRewardAllocations until
lootboxOpening.selectedItem appears, then useLootboxes for the possible
items and resolveLootboxSelectedItem for the winner. Cover the wait with
an animation and cap it with a timeout.
- Only call claimLootbox when resolvePrizeClaimState says
REQUIREMENTS_REQUIRED.
Use our existing design system components and class names throughout.
Add no CSS of your own.
Done when: the list issues exactly one GET /v1/quests, a signed-in fan
can submit and claim at least one quest, statuses render as readable
labels, the description renders through Quest.Description, and a lootbox
claim opens a reveal.
```
## Prompt 3: one more feature [#prompt-3-one-more-feature]
Run once questing works, once per feature. Replace `FEATURE` with one of `battlepass`, `store`, `newsfeed` or `leaderboard`.
```
Implement the Fanbase FEATURE feature in this app.
Read node_modules/@xborglabs/fanbase-react/FEATURE.md in full before
writing anything, then the Membership section of llms.txt. Do not invent
APIs, fields or reason codes. If something is not in those files, stop
and ask.
Follow the file's Process section in order. Each step ends with a
"Done when". Do not move to the next step until the current one holds.
Rules that apply to every feature:
- Never pass a communityId, containerId or COMMUNITY_ID. The SDK resolves
the community from the slug on FanbaseProvider.
- Render the gate and reason values the SDK computes. Never recompute
membership, stock, balance or lock state yourself.
- Name the membership tier that would unlock something, from
requiredTierName. Never write a generic "Premium".
- Structured descriptions go through Parser, plain on cards.
- Every write is already optimistic and already invalidates what it
touched. Do not add your own setQueryData or refetch calls.
Use our existing design system components and class names throughout.
Add no CSS of your own.
Done when: every "Done when" in FEATURE.md holds, and every item in its
Smoke list passes.
```
The feature guides on this site cover the same ground for a person reading: [Battlepass](/docs/battlepass/model), [Store](/docs/store/model), [Newsfeed](/docs/newsfeed/model), [Leaderboard](/docs/leaderboard/model).
## Reviewing what it built [#reviewing-what-it-built]
Agents get this mostly right. The things worth checking by hand:
* **Request count.** Open the network tab on the list page. One `GET /v1/quests`. Fanning out per card is the most common thing to fix.
* **Status labels.** Any raw `INACTIVE` on screen means `resolveMessage` was skipped.
* **The detail page after a submit.** Submit a quest and watch the label and status change without a refresh. If they freeze, the row was mirrored into local state.
* **A social-gated quest signed in.** If it is disabled with no explanation, `authProfile` is not being passed.
* **A premium item as a free fan.** A battlepass tier, a store listing or a post. It should be locked and name the tier. If it shows a claim or buy button, the gate is being skipped.
* **A store purchase that fails.** Check the retry path never mints a new nonce. That is the one mistake that charges a fan twice.
* **No hardcoded community id.** Search the diff for `communityId` and `containerId`. Neither should be a literal.
* **Typecheck.** On a Vite app, `npx tsc -p tsconfig.app.json --noEmit`. The root config is references-only and exits 0 having checked nothing.
* **Your CSS.** No new stylesheet should have appeared.
## When the agent gets stuck [#when-the-agent-gets-stuck]
The prompts say to stop and ask rather than invent. If yours asks a question, the answer is usually in [Quest templates](/docs/quests/templates) or [Hooks](/docs/reference/hooks). If it is in neither, send it to us, because a question an agent has to ask is a page we owe you.
# Completing and claiming (/docs/battlepass/claims)
How a fan takes what they earned. Short on code, because the SDK does most of it, and long on the two ways it goes quietly wrong.
## Claiming one tier [#claiming-one-tier]
`Battlepass.Claim` is the button. Put it inside `Battlepass.Tier` and it knows which tier it belongs to.
```tsx
{canClaim && (
)}
```
Pressing it completes the tier if it is not complete yet, then claims every reward the tier produced.
Every reward, not the first one. A tier your community team gave two rewards to produces two allocations, and the platform only has an endpoint for claiming one at a time. A claim that handles only the first one leaves the second behind with nothing on screen to say so. The SDK claims each in turn, so use the button, or `useBattlepass().actions.claimTier(slot.tier)` if you are wiring your own control.
## The silent failure [#the-silent-failure]
Worth reading twice.
When a free fan completes a premium tier, the platform does not return an error. It quietly reverts the completion and returns success. Your UI shows a claim that worked, and a moment later it has undone itself, with nothing in the response to tell you why.
So the only protection is to not offer the claim in the first place. `canClaim` already accounts for membership, which is what the example above relies on. If you build your own button instead of reading `canClaim`, check the tier state before you enable it:
```tsx
const { slot, canClaim } = useBattlepassTier()
```
Never decide from `slot.tier.isEnabled`. A locked premium tier reports `isEnabled: true`, and a button bound to it is exactly the claim that fails silently.
## Completing without claiming [#completing-without-claiming]
Rare, but some tiers take a completion input before they pay out. Use the hook:
```tsx
import { useCompleteTier } from '@xborglabs/fanbase-react'
const { completeTier, pending, error } = useCompleteTier()
await completeTier(questId) // no input
await completeTier(questId, { text: 'x' }) // with input
```
Do not reach for the quest hooks here. A tier is a quest, so `submitQuest` looks like it should work, but the tier URL is what tells the platform this is a battlepass completion. Send it through the quest endpoint and it is rejected.
## Claiming everything [#claiming-everything]
A "claim all" button is worth having. A fan who comes back after a week can have eight tiers waiting.
```tsx
import { useBattlepass, useClaimAllTiers } from '@xborglabs/fanbase-react'
function ClaimAllButton() {
const { state } = useBattlepass()
const { claimAll, pending, results, needsAttention } = useClaimAllTiers(state.claimableSlots)
const failed = results.filter((result) => !result.ok)
return (
<>
{failed.length > 0 &&
)
}
```
A few details that are easy to get wrong:
**`row.rank` is optional.** It can be missing from a row. Render a placeholder rather than an empty cell or a `0`.
**Name the score column after the resource.** `state.resourceType?.name` is what your community calls it, XP or Points or whatever they chose. The display string is the fallback.
**Highlight the fan with `isLeaderboardViewerRow`.** Put a data attribute or a class on their row and style it. It compares the row against the signed-in fan's id, which the provider reads from their membership.
**The profile link is yours.** FanBase has no public profile page to link to. If your product has profiles, link the name to yours.
Medals for the top three, the fan's avatar and a membership badge are all yours to draw. The row carries what you need: `row.rank`, `row.equippedPersonalization` and `row.membership?.tier`.
## Two empty states [#two-empty-states]
They look alike and mean different things.
| `state.listReason` | Means | Show |
| ------------------ | -------------------------------------------------------------------------- | --------------------------------------------------------------------- |
| `EMPTY` | The board loaded and nobody is on it yet | "No one has scored yet", or similar |
| `SLUG_UNRESOLVED` | The community's main resource is not set up, so there was no board to load | "Not available". This is a configuration problem, not an empty board. |
If you see `SLUG_UNRESOLVED` in production, the community's main resource is missing its slug in the Hub. A quests board never hits it.
## Paging [#paging]
`limit` defaults to 10. The pager buttons disable themselves at either end:
```tsx
import { Leaderboard, resolveMessage, useLeaderboard } from '@xborglabs/fanbase-react'
function Pager() {
const { state } = useLeaderboard()
return (
)
}
```
For "page 3 of 12", read `state.pageMeta.page`, not `state.page`. `state.page` is the page you asked for. `pageMeta.page` is the page the platform actually sent, and if you ask for page 40 of 12, they differ.
The second argument to `resolveMessage` is your i18n adapter, if you have one. Pass `undefined` when you do not. [Display strings](/docs/design/display-strings) covers both.
### Keeping the page in the URL [#keeping-the-page-in-the-url]
Leave `page` off the provider and it keeps the page itself. That is fine until someone presses back and the table does not move.
To keep the page in the URL, pass it in and write it back out:
```tsx
const page = Number(searchParams.get('page') ?? 1)
setSearchParams({ page: String(next) })}
>
```
Once you pass `page`, the provider does what the prop says on every render. Pass it and forget `onPageChange`, and the pager buttons stop working.
### Jumping to the fan [#jumping-to-the-fan]
A "show me" button that jumps to the page the fan is on:
```tsx
import { getLeaderboardPageForRank, useLeaderboard } from '@xborglabs/fanbase-react'
const { state, actions } = useLeaderboard()
const rank = state.viewerRank?.leaderboardRank
const jump = () =>
rank && actions.setPage(getLeaderboardPageForRank({ rank, limit: state.limit }))
```
It assumes every position is filled once. Ties can land it a page early or late, so treat it as close rather than exact.
## The fan's own row [#the-fans-own-row]
```tsx
import { resolveMessage, useLeaderboard } from '@xborglabs/fanbase-react'
function MyRank() {
const { state } = useLeaderboard()
if (state.viewerReason === 'AUTH_REQUIRED') return
if (state.viewerReason === 'UNRANKED' || !state.viewerRank) {
return
)
}
```
| `state.viewerReason` | Means | Show |
| -------------------- | ----------------------------- | ------------------------------------------------------------------- |
| `AUTH_REQUIRED` | Not signed in | A sign-in prompt. "See where you rank" is a good reason to sign in. |
| `UNRANKED` | Signed in, nothing earned yet | A nudge towards their first quest |
Pin this row where it is always visible. A fan at position 3,000 will never page down to find themselves.
Known gap: a signed-in fan who is not a member of the community cannot be highlighted in the table, because the id the highlight compares against comes from their membership. Their own row above still works.
## XP bars elsewhere [#xp-bars-elsewhere]
Not on the board itself, but it trips people up. An XP bar in your nav or on a profile always reads community XP:
```tsx
import { useCommunityXP } from '@xborglabs/fanbase-react'
const { data } = useCommunityXP()
```
Use it even when the board on screen is the quests board. The quests board's own row counts quests, not XP, and wiring an XP bar to it shows a fan's quest count as if it were their level.
## Components [#components]
| Component | Use |
| -------------------------- | ------------------------------------------------- |
| `Leaderboard.Provider` | Reads one page of the board and the fan's own row |
| `Leaderboard.PreviousPage` | Previous page, disabled on the first |
| `Leaderboard.NextPage` | Next page, disabled on the last |
Both pagers take `asChild` and render your element.
For a board without the provider, `useLeaderboardList({ kind, page, limit })` reads a page and `useLeaderboardViewerRank({ kind })` reads the fan's row. Full props in [Components](/docs/reference/components).
## Checklist [#checklist]
* The board renders with no `communityId`, signed in or not
* A row with no rank shows a placeholder
* The score column is named after the resource
* The signed-in fan's row is highlighted in the table
* The fan's own row is pinned and handles both signed out and unranked
* `SLUG_UNRESOLVED` and `EMPTY` show different messages
* The pager text reads from `pageMeta`, and disables at either end
* If the page is in the URL, pressing back moves the table
* XP bars read `useCommunityXP`, never the quests board
# The leaderboard model (/docs/leaderboard/model)
What a leaderboard is, and the vocabulary the next page uses.
## A leaderboard [#a-leaderboard]
A ranking of everyone in the community. It costs nothing to set up, and fans open it without being prompted, which makes it one of the cheapest things you can ship that people come back to.
The leaderboard is read-only. Nothing a fan does on it changes it. They climb it by doing quests and earning XP everywhere else in your product.
What the board ranks by, and the reset before a launch, are set in the Hub. [Leaderboards in the Hub docs](https://fanbase-hub-docs.vercel.app/docs/leaderboards) covers that side.
## Two kinds of board [#two-kinds-of-board]
A community has two boards. Pick which one you show, or show both with a switcher.
| Kind | Ranks fans by |
| --------------------------- | ------------------------------------------------------- |
| `LEADERBOARD_KIND.RESOURCE` | The community's main resource, usually XP. The default. |
| `LEADERBOARD_KIND.QUESTS` | How many quests they have completed |
That is all the scope there is. There are no season boards, date ranges or filters on the community leaderboard. Event leaderboards exist on the platform, but they belong to events, and events are not in the SDK yet.
## Four numbers called rank [#four-numbers-called-rank]
The most common bug on this page, so it gets its own section. Four different integers in the SDK look like a rank. Only one of them is a position on the board.
| Number | Where it lives | What it means |
| ---------------------------- | --------------------------- | ------------------------------------------------- |
| `row.rank` | A row on the board | The fan's position in the standings |
| `viewerRank.leaderboardRank` | The signed-in fan's own row | Their position in the standings |
| `membership.tier.rank` | Membership | Which paid tier they are on. `1` is free. |
| `current.level` | XP | Their level, which is a threshold, not a position |
A fan at position 128 can be level 12 on the Premium tier. Mixing those up puts the wrong number in the wrong column, and it looks plausible enough that nobody notices for a while.
## The fan's own row [#the-fans-own-row]
A fan always wants to see where they are, however far down that is. The SDK reads their own position separately from the page of the board you are showing, so you can pin it at the top or the bottom regardless of which page is open.
A fan who is not signed in has no row. A fan who is signed in but has not earned anything yet is unranked. Both are normal states with their own display strings.
## Membership does not gate it [#membership-does-not-gate-it]
Everyone can see the board, signed in or not, free or paid. Rows can carry the fan's membership tier, and it makes a good badge next to their name, but it changes nothing about who is on the board or where.
# Reactions and comments (/docs/newsfeed/comments)
The writing side. Every write here is optimistic: the screen changes the moment the fan acts, and the SDK rolls it back if the platform refuses.
## Reactions [#reactions]
Two things to render: the counts already on the post, and a picker for adding one.
```tsx
import { useNewsfeedReactionTypes, useReactToPost } from '@xborglabs/fanbase-react'
function Reactions({ post }) {
const { data: types = [] } = useNewsfeedReactionTypes()
const { reactToPost } = useReactToPost()
const react = (reactionTypeId) => reactToPost({ newsId: post.newsId, reactionTypeId })
const unused = types.filter((type) => !post.reactions.some((r) => r.reactionTypeId === type.reactionTypeId))
return (
)
}
```
Counts come from `post.reactions`. Each one says whether this fan has already used it, in `isSelected`. Pressing one they have used takes it back.
The emoji are your community's own, defined in the Hub, not a fixed set. `useNewsfeedReactionTypes` returns the full list for the picker. Offer only the ones not already on the post, since the rest are right there as counts.
If the list of types has not loaded or comes back empty, still show the counts and leave the picker out. Do not build a picker from the counts: that offers only the emoji someone has already used.
The screen updates the moment the fan taps. Do not update your own copy of the post as well. The SDK already has, and doing it twice counts the tap twice.
## The comment section [#the-comment-section]
Check two things before rendering any of it.
```tsx
import { useFanbaseSession } from '@xborglabs/fanbase-react'
function Comments({ post }) {
const session = useFanbaseSession()
if (!post.commentsEnabled) return null
if (!session) return
return
}
```
| Case | Show |
| --------------------------------- | ----------------------------------------------------------------- |
| `post.commentsEnabled` is `false` | Nothing. Your community team switched comments off for this post. |
| Not signed in | A sign-in prompt, and no comment calls |
## Reading comments [#reading-comments]
```tsx
import { NEWSFEED_COMMENT_SORT, buildCommentTree, useNewsfeedComments } from '@xborglabs/fanbase-react'
function CommentThread({ newsId }) {
const [sort, setSort] = useState(NEWSFEED_COMMENT_SORT.NEW)
const { data, fetchNextPage, hasNextPage } = useNewsfeedComments({ newsId, sort })
const tree = buildCommentTree(data?.pages.flatMap((page) => page.results) ?? [])
return (
{tree.map((node) => )}
{hasNextPage && }
)
}
```
Comments arrive as a flat list. `buildCommentTree` nests them: each node is a `comment` and its `children`.
| Sort | Order |
| ------------------------------------- | ------------------------------------- |
| `NEWSFEED_COMMENT_SORT.NEW` | Newest first |
| `NEWSFEED_COMMENT_SORT.TOP` | Highest score first |
| `NEWSFEED_COMMENT_SORT.BEST` | The platform's best-first ranking |
| `NEWSFEED_COMMENT_SORT.CONTROVERSIAL` | The platform's most-contested ranking |
The ranking happens on the server. Changing the sort refetches the thread in the new order.
## Nesting [#nesting]
```tsx
import { COMMENT_INDENT_CAP } from '@xborglabs/fanbase-react'
function CommentNode({ node, newsId, depth }) {
const indent = Math.min(depth, COMMENT_INDENT_CAP)
return (
)
}
```
Replies can go deeper than a screen is wide. `COMMENT_INDENT_CAP` is 5: stop indenting past that and let deeper replies line up at the fifth level. The thread stays readable on a phone.
When a comment has more replies than came back, `hasMoreReplies` is set. Load them with `useNewsfeedCommentReplies({ newsId, commentId })`.
A comment can arrive with `isDeleted` set. Render it as "Comment deleted" rather than dropping it, so any replies under it keep their context.
## Writing a comment [#writing-a-comment]
```tsx
import { usePostComment, validateCommentText } from '@xborglabs/fanbase-react'
function Composer({ newsId, parentId }) {
const [text, setText] = useState('')
const [error, setError] = useState(null)
const { postComment } = usePostComment()
async function submit() {
const checked = validateCommentText(text)
if (!checked.ok) return setError(checked.reason)
await postComment({ newsId, text: checked.text, parentId })
setText('')
}
return (
)
}
```
Always run `validateCommentText` first. It trims the text and checks the length, and it returns the trimmed version for you to send.
| Reason | Means |
| ------------------- | --------------------- |
| `COMMENT_TOO_SHORT` | Empty, or only spaces |
| `COMMENT_TOO_LONG` | Over 500 characters |
Send `checked.text`, not what the fan typed. The platform stores what you send, so sending the raw input keeps the stray spaces the check just removed.
Pass `parentId` to reply to a comment. The comment count on the post goes up the moment the fan posts, on the feed card and on the post page.
A fan's own comments carry `isOwn`. Use it to show edit and delete, through `useUpdateComment` and `useDeleteComment`. Run `validateCommentText` on an edit too.
## Votes [#votes]
```tsx
import { NEWSFEED_COMMENT_VOTE, useCommentVote } from '@xborglabs/fanbase-react'
function Votes({ comment, newsId }) {
const { vote } = useCommentVote()
const up = comment.userVote === NEWSFEED_COMMENT_VOTE.UP
const down = comment.userVote === NEWSFEED_COMMENT_VOTE.DOWN
const cast = (value) =>
vote({ newsId, commentId: comment.commentId, value: comment.userVote === value ? NEWSFEED_COMMENT_VOTE.NONE : value })
return (
<>
{comment.score}
>
)
}
```
| Vote | Value |
| ---------------------------- | ------------------ |
| `NEWSFEED_COMMENT_VOTE.UP` | Upvote |
| `NEWSFEED_COMMENT_VOTE.DOWN` | Downvote |
| `NEWSFEED_COMMENT_VOTE.NONE` | Take the vote back |
Pressing the same vote twice should take it back, which is what `cast` above does. Comments take emoji reactions as well, through `useReactToComment`, the same way posts do.
## Checklist [#checklist]
* Tapping a reaction updates the count straight away, and tapping it again takes it back
* The picker offers only the emoji not already on the post
* Comments are hidden on a post that has them switched off
* A signed-out fan sees a sign-in prompt and nothing else
* Replies nest, and stop indenting past five levels
* "More replies" loads the rest of a thread
* An empty or overlong comment never reaches the platform
* The trimmed text is what gets sent
* Pressing the same vote twice takes it back
# The feed and a post (/docs/newsfeed/feed)
The reading side. There is no provider here: the newsfeed is hooks and helpers, and every piece of the layout is yours.
## The feed [#the-feed]
```tsx
import { Parser, resolveNewsfeedPremiumGate, useMembership, useNewsfeedFeed } from '@xborglabs/fanbase-react'
export function Feed() {
const { data: membership } = useMembership()
const { data, fetchNextPage, hasNextPage, isFetchingNextPage, isLoading } = useNewsfeedFeed()
if (isLoading) return
const posts = data?.pages.flatMap((page) => page.results) ?? []
if (!posts.length) return
return (
<>
{posts.map((post) => (
))}
{hasNextPage && (
)}
>
)
}
```
`useNewsfeedFeed` is an infinite query. Each page is in `data.pages`, and each page's posts are in `results`, so flatten them as above. `fetchNextPage` loads the next 20. An intersection observer calling it works as well as a button.
Do not pass a `communityId`. The hook resolves it from the `slug` on [`FanbaseProvider`](/docs/reference/provider).
Cards render from the row you already have. Do not load a post per card. Everything a card needs is on the row.
## A card [#a-card]
```tsx
function PostCard({ post, membership }) {
const gate = resolveNewsfeedPremiumGate({ post, membership })
return (
{post.publisher.name}
{gate.locked ? (
) : (
)}
Read
)
}
```
The body is structured content, the same format as a quest description. On a card, `isPlain` renders a plain text excerpt. [Quest descriptions](/docs/quests/descriptions) covers the format.
## The members-only lock [#the-members-only-lock]
Run the gate on every card and on the post page. Both.
`resolveNewsfeedPremiumGate` locks a post when the fan's membership is below the tier the post asks for. When it is locked, show the lock and leave the body out. The platform has already stripped the body for that fan, so there is no body to leak, but a card that assumes one and tries to render it shows an empty space where the post should be.
Name the tier, `gate.requiredTier?.name`, rather than a generic "Premium". It tells the fan exactly what unlocks it.
`useMembership` reads the fan's membership. It is the same one the battlepass and the store use. See [Membership](/docs/membership).
## Filters [#filters]
Pass them to the hook. The SDK builds the request.
```tsx
import { useNewsfeedFeed, useNewsfeedPublishers } from '@xborglabs/fanbase-react'
const { data: publishers = [] } = useNewsfeedPublishers()
const feed = useNewsfeedFeed({
publisherIds: selectedPublisherIds,
featured: tab === 'featured' ? true : undefined,
})
```
| Filter | Shows |
| ---------------- | -------------------------------- |
| `publisherIds` | Posts from the publishers picked |
| `featured: true` | Featured posts only |
| `pinned: true` | Pinned posts only |
Filters run on the server, so paging stays correct. Keep the selected tab and publishers in your URL: the SDK holds no filter state.
### A pinned strip [#a-pinned-strip]
Pinned posts already come first on every page of the feed. If you would rather show them as their own strip above it, run a second feed:
```tsx
const pinned = useNewsfeedFeed({ pinned: true })
const main = useNewsfeedFeed({ pinned: false })
```
Hide the pinned strip on a Featured tab. Otherwise a pinned post that is also featured shows up twice.
## A post [#a-post]
```tsx
import { Parser, resolveNewsfeedPremiumGate, useMembership, useNewsfeedPost } from '@xborglabs/fanbase-react'
export function PostPage({ newsId }) {
const { data: membership } = useMembership()
const { data: post, isLoading } = useNewsfeedPost({ newsId })
if (isLoading) return
if (!post) return
const gate = resolveNewsfeedPremiumGate({ post, membership })
return (
{gate.locked ? (
) : (
<>
>
)}
)
}
```
Same gate as the card. Leave `isPlain` off here for the full render.
## Media [#media]
A post's `images` can hold photos and videos in the same list. Tell them apart with `detectNewsfeedMedia`:
```tsx
import { detectNewsfeedMedia } from '@xborglabs/fanbase-react'
function Media({ images = [] }) {
return images.map((image) => {
const { isVideo, isImage } = detectNewsfeedMedia(image)
if (isVideo) return
if (isImage) return
return null
})
}
```
It decides from the file extension, and returns neither for an extension it does not know. Skip those rather than guessing.
## Buttons and links [#buttons-and-links]
A post can carry buttons your community team added, like "Buy tickets", and a link back to where it was first posted.
```tsx
import { isNewsfeedActionUrl, resolveNewsfeedSocialUrl } from '@xborglabs/fanbase-react'
post.actions?.map((action) =>
isNewsfeedActionUrl(action.value) ? (
{action.label}
) : null,
)
{post.socialData && (
View on {post.socialData.platform}
)}
```
Check each button with `isNewsfeedActionUrl` before rendering it as a link. `resolveNewsfeedSocialUrl` builds the right link for X, YouTube and Twitch, including telling a Twitch video from a clip.
## Checklist [#checklist]
* The feed renders with no `communityId`
* Cards render from the feed row, with no request per card
* Members-only posts are locked on the card and on the post page, and name the tier
* The body goes through `Parser`, plain on cards
* Load more fetches the next page
* Changing a filter changes the feed, and the filter is in the URL
* A pinned strip is hidden on the Featured tab
* Videos play and photos show, and unknown files are skipped
# The newsfeed model (/docs/newsfeed/model)
What the newsfeed is made of, and the vocabulary the other two pages use.
## A newsfeed [#a-newsfeed]
Your community's own feed of posts, in your product rather than on a social platform you do not control. Your community team writes the posts in the admin panel, and fans read, react and comment in your app.
Publishers, posts, gating and moderation are handled in the Hub. [Newsfeed in the Hub docs](https://fanbase-hub-docs.vercel.app/docs/newsfeed) covers that side.
## Posts [#posts]
A post reads like a social post, not an article. It has no title. It has:
| Field | What it is |
| -------------- | --------------------------------------------------------------------------- |
| `publisher` | Who posted it, with a name and an avatar |
| `description` | The body, as structured content |
| `images` | Photos and videos |
| `actions` | Buttons linking somewhere, like "Buy tickets" |
| `socialData` | A link to the original, when the post mirrors one from X, YouTube or Twitch |
| `reactions` | Emoji counts, and whether this fan has used each one |
| `commentCount` | How many comments |
| `publishedAt` | When it went out |
Build the card around the publisher and the body. A card that leads with a missing title looks broken.
## Publishers [#publishers]
Every post goes out under a publisher: the club's main account, a player, the merch team. A community can have several. Fans can filter the feed by them, which is the main reason to show publisher chips at all.
## Pinned and featured [#pinned-and-featured]
Two separate flags, set by your community team.
**Pinned** posts stay at the top. The SDK sorts them first on every page of the feed.
**Featured** posts are the editorial pick. A common layout is a "For you" tab showing everything and a "Featured" tab showing only these.
## Members-only posts [#members-only-posts]
A post can be restricted to a membership tier. For a fan below that tier, the platform strips the body before it reaches your app, so there is nothing to accidentally leak. They still see that the post exists, who posted it, and what it would take to read it.
That is deliberate, and it is the reason to keep locked posts in the feed rather than hiding them. A locked post is an advert for membership. [Membership](/docs/membership) covers the gate, which works the same way here as in the battlepass and the store.
## Reactions [#reactions]
Fans react with emoji your community team defined, not a fixed set. A post's reactions come with counts and with whether this fan has already used each one. Reactions update on screen immediately, before the platform confirms.
## Comments [#comments]
Threaded, with replies nested under replies. Comments can be switched off per post. Fans vote comments up and down, react to them, edit their own and delete their own.
A comment has to be between 1 and 500 characters, after trimming whitespace. The SDK checks that before sending, so an empty or overlong comment never leaves the page.
A fan who is not signed in gets a sign-in prompt where the comments would be. Commenting, voting and reacting all need a session.
# Building a prediction (/docs/predictions/build)
One card. Today it sits on top of the quest system, so it uses the quest provider and the quest machine. When predictions move to their own surface, this page will change with them. Keep the card self-contained and the move stays small.
## Finding predictions [#finding-predictions]
They come back in the quest list. Pull them out by template name, and give them their own place in your product:
```tsx
import { useQuestsList } from '@xborglabs/fanbase-react'
const PREDICTION = 'basic.prediction'
const { data: quests = [] } = useQuestsList()
const predictions = quests.filter((q) => q.template?.name === PREDICTION)
const everythingElse = quests.filter((q) => q.template?.name !== PREDICTION)
```
Match on the exact template name. There is no SDK function that returns "prediction" for you.
## Opening one [#opening-one]
Each one opens in `Quest.Provider`, with `fetchRewards` on so a fan who calls it right can claim:
```tsx
import { Quest } from '@xborglabs/fanbase-react'
```
## The card [#the-card]
```tsx
import { resolveMessage, useQuest, useQuestResults } from '@xborglabs/fanbase-react'
function PredictionCard() {
const { state, actions } = useQuest()
const quest = state.quest
const { options = [], lockAt } = quest.template.args
const picked = quest.metrics?.text
const reason = state.machine.reason
const locked = reason === 'PREDICTION_LOCKED'
const closed = locked || reason === 'PREDICTION_SUBMITTED'
const { data } = useQuestResults(quest.questId)
const counts = data?.results ?? {}
const total = Object.values(counts).reduce((sum, n) => sum + n, 0)
return (
}
)
}
```
`formatDate` is yours.
## Sending the pick [#sending-the-pick]
Send the option's **label**, as `{ text: option.label }`. Not its index, and not an id. The label is what your team resolves against, so it is what has to arrive.
Use `actions.submit(payload)`, not `Quest.Submit`. A prediction is a typed template, and `Quest.Submit` sends no body, so the pick would be lost.
One click, one submit. There is no "change my answer". Make that clear before they tap: a confirm step, or a line saying the pick is final, is worth more here than on any other quest.
## Reading back the pick [#reading-back-the-pick]
A fan who already entered has their pick in `quest.metrics.text`. Mark that option as theirs, and disable the rest. Do not show the options as if they could still choose.
## The lock [#the-lock]
Read it from the machine, not the clock:
| `state.machine.reason` | Means | Show |
| ---------------------- | --------------------------- | ------------------------------------ |
| `PREDICTION_LOCKED` | The lock time has passed | Entries closed, and when they closed |
| `PREDICTION_SUBMITTED` | This fan has already picked | Their pick, highlighted |
Both have display strings, `Quests.disabled.PREDICTION_LOCKED` and `Quests.disabled.PREDICTION_SUBMITTED`. [Display strings](/docs/design/display-strings).
Use `lockAt` only to display the deadline. Comparing it to the fan's own clock to decide whether to enable the buttons gets it wrong for anyone whose device clock is off. The machine already knows.
## The split [#the-split]
`useQuestResults(questId)` returns the count per option, keyed by label:
```ts
{ results: { Northwind: 1822, Tidebreak: 1025 } }
```
The total is the sum. Turn counts into percentages yourself, and show them before the fan enters as well as after. That is how a prediction is meant to read.
The hook is typed `unknown`, because the same endpoint serves polls too. Read `results` defensively, as above, and render the options without percentages if it is missing or empty. A brand new prediction has no entries yet.
## After it resolves [#after-it-resolves]
Once your team marks the right answer, a fan who called it has a reward waiting. `state.canClaim` flips, and your normal claim button takes it from there:
```tsx
{state.canClaim && (
)}
```
That only works if the provider has `fetchRewards` on. Without it, the claim button never appears and a fan who got it right is never paid.
If the reward is a raffle entry or a physical prize, the claim may need details first. [Claims that need details](/docs/quests/rewards#claims-that-need-details).
A fan who picked wrong has nothing to claim. Say so plainly. They lost nothing, and the next prediction is the reason to come back.
## Gating [#gating]
A prediction takes the same audience rules as any quest. A members-only prediction shows its card to everyone, but the machine keeps it closed for anyone who does not qualify, with a reason to show. Render that reason rather than hiding the card: "For Premium members" is a better nudge than nothing.
## Checklist [#checklist]
* A prediction renders through its own branch, from the template family
* The pick is sent as the option's label, through `actions.submit`
* The fan knows the pick is final before they tap
* A fan who already entered sees their pick, and the options are disabled
* The lock comes from the machine, and the card says when entries closed
* The split shows before and after entering, and survives having no entries
* `fetchRewards` is on, so a winning fan can claim
* A losing fan sees a clear, kind result, not an error
# The prediction model (/docs/predictions/model)
What a prediction is, how it ends, and the one setting that decides whether it works.
Predictions are their own feature, with their own place in the Hub and in your product. Today they run on the quest system underneath, and that is changing. This page describes the feature. [How it ships today](#how-it-ships-today) covers what that means for your code right now.
## A prediction [#a-prediction]
A prediction asks fans to pick an outcome before it is known. A match result, a roster move, a scoreline, which colourway drops on Friday. Entries close at a set time, and when the thing happens your community team marks what was right. Everyone who picked it gets the reward.
It is free to enter. Nothing is staked and nothing is wagered, and a fan can never end up worse off for answering.
Options, the lock time and resolving the outcome are all done in the Hub. [Predictions in the Hub docs](https://fanbase-hub-docs.vercel.app/docs/predictions) covers that side.
## How it ships today [#how-it-ships-today]
**This will change.** Predictions are moving to a surface of their own in the SDK. Until that ships, a prediction is delivered as a quest, and the code on [Building a prediction](/docs/predictions/build) reflects that. Keep your prediction UI in its own component, so the move is a change to the data it reads rather than a rebuild.
Right now a prediction arrives as a quest whose template is `basic.prediction`. That means it:
* comes back in [`useQuestsList`](/docs/quests/list), mixed in with your quests
* opens through `Quest.Provider`, like a quest
* pays out through the ordinary [rewards and claims](/docs/quests/rewards)
So in your product, treat it as its own thing. Give predictions their own page or their own strip, filter them out of your quest list by template, and do not make a fan look for them among the quests.
## Options [#options]
Each option has:
| Field | What it is |
| ------------- | ---------------------------------------------------------------------------------------------- |
| `label` | The plain answer. This is what your team resolves against, and what the fan's pick is sent as. |
| `description` | Optional. One line under the label, like "Unbeaten at home since March". |
| `imageUrl` | Optional. A small image beside the label. |
The label is the answer. The description is the reason to pick it. Render both.
## The lock [#the-lock]
Every prediction has a lock time, `lockAt`. Before it, fans can enter. After it, entries are closed, whether or not the outcome has been marked yet.
The platform enforces the lock by the clock. The quest machine reports it as `PREDICTION_LOCKED` and your options stop responding.
Show the lock time on the card before it passes. "Closes Saturday 14:00" is the deadline that makes the prediction feel live.
## One pick, final [#one-pick-final]
A fan picks once. The pick is final the moment they submit, and the machine then reports `PREDICTION_SUBMITTED`. A fan who comes back sees what they picked, not the options again.
## The split [#the-split]
How everyone else has picked is visible, as a count per option. That is the one place a prediction behaves differently from a poll. A poll hides its result until you vote, so other people's answers cannot pull yours. A prediction shows it, because being with the crowd or against it is most of the fun.
## Resolution [#resolution]
Until your team marks the right answer, the quest sits locked and unpaid. There is no automatic resolution, because the platform has no way to know what happened at your event.
Once it is resolved, a fan who picked the right option has the quest's reward waiting for them to claim, through the ordinary claim flow. A fan who picked anything else has nothing to claim, and loses nothing.
## It is not betting [#it-is-not-betting]
There is no stake, no odds and no payout that scales with how many people were wrong. Everyone who is right gets the same reward: the one set on the quest.
## What is coming [#what-is-coming]
A standalone predictions surface, outside the quest system. The behaviour on this page stays the same: options, a lock, one final pick, a visible split, a resolution that pays the fans who called it. What changes is where your code reads it from. [Feature status](/docs/status).
# Quest descriptions (/docs/quests/descriptions)
Descriptions are written in the admin panel with formatting: paragraphs, bold, lists, links. They arrive as structured content, not a string, so they can carry that formatting into your design without any HTML from us.
## Rendering [#rendering]
```tsx
import { Quest } from '@xborglabs/fanbase-react'
```
Do not try to render the raw value. It is a node tree, and `JSON.stringify` on a quest description is a recognisable sign of a rushed integration.
## The theme object [#the-theme-object]
You map node types to your own class names. Nothing is styled by us.
```tsx
const descriptionTheme = {
paragraph: 'your-prose-p',
heading: {
h1: 'your-h1',
h2: 'your-h2',
h3: 'your-h3',
},
list: {
ul: 'your-ul',
ol: 'your-ol',
listitem: 'your-li',
},
link: 'your-link',
text: {
bold: 'font-bold',
italic: 'italic',
underline: 'underline',
strikethrough: 'line-through',
},
quote: 'your-blockquote',
code: 'your-code',
}
```
Define it once, export it, use it everywhere a description renders. Full key list in [Components](/docs/reference/components#questdescription).
## Excerpts for cards [#excerpts-for-cards]
A card usually wants a couple of lines of plain text rather than the full render. Extract the text nodes:
```tsx
import { Parser } from '@xborglabs/fanbase-react'
function excerpt(description, max = 120) {
const text = Parser.toPlainText(description)
return text.length > max ? `${text.slice(0, max).trimEnd()}…` : text
}
```
## Empty descriptions [#empty-descriptions]
Not every quest has one. Check before you render a wrapper with nothing in it.
```tsx
{state.quest?.description ? (
) : null}
```
## Links inside descriptions [#links-inside-descriptions]
Community teams put links in descriptions. Style them through `theme.link` and they inherit your link styles.
If the quest is a visit-link quest, the CTA is what the machine watches, not a link in the description. See [Visit-link quests](/docs/quests/detail#visit-link-quests).
# Quest detail (/docs/quests/detail)
The main build, and the one page worth reading twice.
## The shape [#the-shape]
```tsx
import { Quest } from '@xborglabs/fanbase-react'
export function QuestDetailPage({ questId }) {
const profile = useFanProfile()
return (
)
}
```
`Quest.Provider` loads the quest, runs the state machine and exposes both through `useQuest()`. `Quest.Frame` wraps your UI. Everything inside is yours.
`fetchRewards` is a flag that asks the provider to load the fan's reward allocations, which is what tells the claim button a reward is waiting. It is off by default. Keep it on here and off on the list. [Rewards and claims](/docs/quests/rewards#claim-state).
## Passing the fan profile [#passing-the-fan-profile]
`authProfile` is how the machine learns what the fan has linked.
Leave it out and the machine has to assume nothing is linked, so every social-gated and wallet-gated quest stays disabled with no obvious cause. It looks like a bug in the machine and it is a missing prop.
```tsx
const { data: socials = [] } = useLinkedSocials()
authProfile={{ socials, wallets: profile?.wallets }}
```
Take the socials from `useLinkedSocials`, not the profile. The profile leaves out expiry dates, so an expired Twitch link would look fine to the machine and the fan could never tell why the quest will not open. See [Fan profile](/docs/sign-in#fan-profile).
## Seeding from the list row [#seeding-from-the-list-row]
You have the row from the list already, and rendering a title instantly beats a spinner.
Pass it as the `quest` prop and let the provider own it from there:
```tsx
```
Do not copy the row into your own `useState` and feed that in. It is the natural thing to reach for and it pins the page: your state never updates, so after a submit the status, the button label and the CTA all stay where they were. It reads as a state management bug in your own code and it is this.
If you need the fresh value after an action, take it from `state.quest` inside the provider rather than from your copy.
**Not confirmed yet.** A trial saw the page stay pinned even with the row passed
straight through and nothing mirrored. We have not reproduced it, so we cannot say
whether seeding pins the page or only the mirrored version does.
If your page stops updating after a submit and you are already doing the above,
drop the `quest` prop. The provider fetches the quest itself and the page updates.
It costs one extra `GET /v1/quests/{questId}` and the instant title render.
## Reading state [#reading-state]
```tsx
const { state, actions } = useQuest()
state.quest // the quest
state.quest.template.name // which template
state.quest.template.args // template settings from the admin panel
state.buttonLabel // label for the current state
state.canSubmit // can the fan act
state.canClaim // is a reward waiting
state.disabledReasonLabel // why not, in readable language
```
Render those. Do not recompute them.
`disabledReasonLabel` is worth surfacing rather than hiding. “Link your Discord account to start this quest” turns a dead button into a next step, and the machine has already written the sentence.
Guard it on the way out, though. Some reasons still arrive with an unsubstituted
`{quest}` token in them, and `You need to log in to start this {quest}.` is worse
in front of a fan than no message at all:
```tsx
function reason(label) {
if (!label) return null
return label.includes('{') ? null : label
}
```
Dropping the message and leaving the button disabled is the safe fallback. If you
would rather keep the sentence, substitute the quest title in yourself rather than
passing the token through.
## The requirement router [#the-requirement-router]
The one branch you write. Resolve the template name to its family, render the input,
submit accordingly.
Branch on the family, never on `template.name` directly. The name that arrives is a
wire value like `basic.auto-complete`, and the families are a grouping you map it into
with `familyOf`, a short function you own. [Quest templates](/docs/quests/templates#routing) has it in full.
Do not use `getApiType` for this. It returns the submit path, `accept` or `complete`,
not the family, so a switch on it never matches `'poll'` and every quest silently goes
to your default branch.
```tsx
import { familyOf } from './quest-families' // see Quest templates
function QuestBody() {
const { state, actions } = useQuest()
const template = state.quest?.template
if (!template) return null
switch (familyOf(template.name)) {
case 'poll':
return
case 'text':
return
case 'prediction':
return
case 'quiz':
return
case 'image':
return
case 'visit':
return
case 'bind':
return
default:
return
}
}
```
Two families, two submit paths:
**Typed templates** carry a payload. Call `actions.submit(payload)` with the shape the template expects. Do not use `Quest.Submit` for these, it submits with no body.
**Empty-body templates** carry nothing. Use `Quest.Submit`, or `actions.submit()` with no argument.
[Quest templates](/docs/quests/templates) maps every live template name to its family and payload shape. Do not invent a template name or a payload shape. If a name arrives that you do not recognise, fall through to the default branch above, which handles it as empty-body and lets the machine decide.
## Visit-link quests [#visit-link-quests]
The fan has to open a link before they can complete it. Render an outbound link, then let the machine take it from there.
```tsx
function VisitLink({ args }) {
const { state } = useQuest()
return (
<>
Open link
>
)
}
```
Keep the CTA bound to `state.canSubmit`. The machine is what the platform verifies
against, and a button wired to your own click handler instead is not tracking the
thing that decides whether a submit is accepted.
**`canSubmit` does not clear for visit-link quests.** A trial ran the machine
against a live one and it held at `VISIT_LINK_MISSION` every time: no payload,
`{ visited: true }`, a full `authProfile`, community membership. Passing an
`event` changed the reason to `EVENT_JOIN_NOT_ALLOWED` instead of clearing it.
So the CTA above stays disabled. We have not tested whether bypassing the machine
gets a submit accepted, so there is no workaround here yet. If a visit-link quest
is on your critical path, talk to your FanBase contact first.
## Social and bind quests [#social-and-bind-quests]
Follow, join, subscribe. These need the fan's account linked before the machine will let them act.
```tsx
function BindAccount({ args }) {
const { state } = useQuest()
if (!state.canSubmit && state.disabledReasonLabel) {
return (
<>
{state.disabledReasonLabel}
Link account
>
)
}
return
}
```
Payload is empty. Linking is the work. `connectUrl` is yours: it wraps `buildBindUrl`, with the account type in the redirect so your callback page knows what came back. [Linking accounts](/docs/linking) has the whole flow.
## Components [#components]
| Component | Use |
| ------------------- | --------------------------------------- |
| `Quest.Provider` | Loads the quest, runs the machine |
| `Quest.Frame` | Wraps your detail UI |
| `Quest.Description` | Renders structured description content |
| `Quest.Submit` | Submit CTA for empty-body templates |
| `Quest.Accept` | Accept step, where a template has one |
| `Quest.Complete` | Complete step, where a template has one |
| `Quest.Claim` | Claim CTA when a reward is waiting |
All take `asChild` and render your element. Full props in [Components](/docs/reference/components).
## After a submit [#after-a-submit]
The quest advances, and `state` follows it. Take your values from `state`, not from a copy, and the page updates on its own. If the reward became claimable, `state.canClaim` flips and you show the claim CTA. [Rewards and claims](/docs/quests/rewards).
## Checklist [#checklist]
* Signed-in fan can submit at least one quest of each family you support
* Social-gated quests show a reason and a link button, not a dead disabled button
* After a submit, status and button label both change without a manual refresh
* An unrecognised template name renders something usable rather than crashing
* Description renders through `Quest.Description`, not as raw JSON
# Listing quests (/docs/quests/list)
The list page. Short, because the SDK does most of it.
## One hook [#one-hook]
```tsx
import { useQuestsList } from '@xborglabs/fanbase-react'
export function QuestsPage() {
const { data: quests, isLoading, error } = useQuestsList()
if (isLoading) return
if (error) return
if (!quests?.length) return
return (
{quests.map((quest) => (
))}
)
}
```
One call, one `GET /v1/quests`, the whole list scoped to your tenant.
## Do not fan out [#do-not-fan-out]
Cards render from the row you already have. Do not call quest detail per card, and do not fetch reward allocations for cards.
It is tempting when a card wants a completion state or a reward image, and it turns one request into fifty on a busy page. Everything a card needs is on the row. If something genuinely is not, tell us rather than fanning out.
## What a row has [#what-a-row-has]
Title, description, template, status, dates, rewards, image. Enough for a card without any extra call.
Two of those need care when rendering:
**Status** comes back as a raw enum. `INACTIVE` does not mean the quest is off, it means the fan has not started it. Resolve it through the string catalog. [Display strings](/docs/design/display-strings).
**Description** is structured content, not a string. On a card you usually want a plain-text excerpt rather than the full render. [Quest descriptions](/docs/quests/descriptions).
## Cards without sign-in [#cards-without-sign-in]
The list works signed out. That is usually what you want, since a fan seeing what is on offer is the reason they sign in.
Quest detail is a different story. Submitting and claiming need a session, and reward fetching needs one too. Detail for a signed-out fan renders, with the machine reporting that sign-in is required.
## Filtering and grouping [#filtering-and-grouping]
Filter and sort client-side off the rows you have. Common groupings: active first, then completed. By tag, if your community team uses tags. By reward type.
Tags are set in the admin panel, so your community team can reorganise a quest page without a deploy if you group by them.
## Opening a quest [#opening-a-quest]
Route to a detail page and pass the row through as seed data so the detail view has something to render immediately.
```tsx
navigate(`/quests/${quest.id}`, { state: { quest } })
```
How you hand that row to `Quest.Provider` matters. Read [Quest detail](/docs/quests/detail#seeding-from-the-list-row) before wiring it, there is one specific way to do it that keeps the page updating after a submit.
# The quest model (/docs/quests/model)
What a quest is made of, and the vocabulary the rest of the docs uses.
## A quest [#a-quest]
Something you ask a fan to do, and what they get for doing it. Created in the admin panel, delivered to your app through the API.
Every quest has a title, a description, a template, a status, an optional date window, and zero or more rewards.
## Templates [#templates]
The template decides what the fan has to do and what your UI has to render. A poll template needs options and a choice. A photo submission needs an upload. A follow template needs a linked social account.
Dozens of template names are live, and they group into a handful of families that behave the same way in code. You do not write a branch per template name, you write one per family. [Quest templates](/docs/quests/templates) is the full map.
Two families matter most:
**Typed templates** take a payload. Text, answer, prediction, quiz, poll, email, wallet, image. You collect input and submit it.
**Empty-body templates** take no payload. Visit a link, bind an account, progress-tracked, automatic. The fan does something, you tell the SDK it happened.
Templates arrive with `args`, a bag of template-specific settings from the admin panel. A poll's options are in `args`, as is a visit quest's URL.
Treat `args` as readable by anyone using your app. It reaches the browser, so do not build a mechanic whose fairness depends on a value in there staying hidden. If you need a quest whose answer cannot be seen ahead of time, ask us which template to use rather than assuming a given one hides it.
## Requirements and gates [#requirements-and-gates]
Some quests can only be acted on under certain conditions. Signed in. Discord account linked. Link opened. Inside the date window.
The state machine evaluates all of it and hands you `canSubmit`, `canClaim`, a button label and a reason. You render the answer, you do not compute it. See [How it fits together](/docs/how-it-works/architecture#the-state-machine).
## Rewards [#rewards]
What the fan gets. Points and resources, physical or digital prizes, personalisation items like avatar parts or borders, and loot boxes.
Each reward carries a slug identifying its type. The SDK resolves a slug into the right presentation. Loot boxes have their own flow because they involve a reveal. [Rewards and claims](/docs/quests/rewards).
## Allocations [#allocations]
A reward that has been assigned to a fan but not necessarily handed over. The gap matters for loot boxes, where allocation happens on claim and the contents resolve a moment later. You poll allocations until the result is there.
## Status [#status]
Quests carry a status enum. The values do not read the way they look. `INACTIVE` means the fan has not started, not that the quest is switched off.
Do not render the raw enum. The SDK ships display strings for all of them. [Display strings](/docs/design/display-strings) is a short page and skipping it is the most common cosmetic bug in a first integration.
## Lifecycle [#lifecycle]
Your app owns four of those nine steps and none of the verification. Whether someone actually followed the account, whether the prediction was right, whether the purchase happened. You do not implement any of it.
# Rewards and claims (/docs/quests/rewards)
What a fan gets for a quest, and the part of the build fans remember.
## Reward types [#reward-types]
Every reward carries a slug identifying its type. Eight are live:
| Slug | What the fan gets | After the claim |
| ---------------------------- | --------------------------------------------------- | --------------------------------- |
| `give_resources` | XP or currency. The most common reward by volume. | Credited. Show the amount. |
| `give_resources_progressive` | The same, at a fixed amount that does not shrink | Credited |
| `give_assets` | An inventory item | In their inventory |
| `give_prizes` | A prize. May need an email or an address first. | Granted, then shipped if physical |
| `give_lootboxes` | A loot box | The reveal |
| `give_personalizations` | A cosmetic: a profile picture, border or background | Ready to equip |
| `assign_discord_role` | A role in your Discord | Assigned on Discord |
| `manual_claim_reward` | Something your team hands over by hand | Nothing automatic. Show the name. |
An unknown slug renders nothing. That keeps a reward type added after you ship from appearing as a broken card.
A `give_resources` reward carries whether the resource is spendable:
```json
{
"slug": "give_resources",
"rewardHandlerArgs": {
"amount": 20,
"resourceTypeId": "urn:xb-resource:…",
"slug": "xp",
"name": "XP",
"isSpendable": false
}
}
```
`isSpendable` is the one to read. A non-spendable resource is progression, XP and
levels, and a spendable one is currency the fan can use in [the store](/docs/store/model).
Showing both with the same treatment is a common early mistake.
A quest can carry several rewards at once, commonly a prize alongside the resources
for completing it, so render them as a list rather than reaching for the first one.
## Showing rewards before completion [#showing-rewards-before-completion]
Fans decide whether a quest is worth doing by looking at the reward, so render it up front. The rewards are on the quest itself, and they render signed out.
```tsx
import { resolveQuestRewardChrome, useQuest } from '@xborglabs/fanbase-react'
function QuestRewards() {
const { state } = useQuest()
const quest = state.quest
return (
)
}
```
Do not branch on slug strings you have hardcoded. `resolveQuestRewardChrome` returns the image, name, amount and a ready-made label like `20 XP` for any live slug, and `undefined` for one it does not know. New reward types then work without a code change.
The amount it gives is the right one for the moment. Before completion that is the configured amount, including any reduction your community team set for later finishers. After completion it is the amount the fan was actually paid, which is locked.
## Claim state [#claim-state]
Whether a reward is waiting to be claimed lives on its allocation, and allocations need a session. Ask the provider to fetch them:
```tsx
```
`fetchRewards` is a flag, and it is off by default. Leave it off on a list, and turn it on for the detail page where the claim button is. With it on, `state.rewards` holds the allocations and `state.canClaim` knows whether one is waiting.
Signed out, there is nothing to fetch and the provider does not try.
## Claiming [#claiming]
When `state.canClaim` is true there is something waiting.
```tsx
```
`buttonLabel` already says the right thing for the claim state, so you do not need your own copy.
A quest with more than one reward has more than one allocation. `Quest.Claim` claims them all. If you are wiring your own control, use `actions.claimAllAllocated()` rather than `actions.claim`, which claims the single allocation you name and leaves the rest waiting.
## Claims that need details [#claims-that-need-details]
Some prizes need something from the fan before they can be sent. An email for a code, an address for merchandise, a wallet for an on-chain item.
Until the fan provides it, the machine holds the claim with `REWARD_REQUIREMENT_REQUIRED`. Collect the details, build the payload with the builder the SDK ships for this call, and hand it to the provider:
```tsx
import { toAllocationClaimPayload } from '@xborglabs/fanbase-react'
const claimPayload = toAllocationClaimPayload(values)
```
The requirements are on the reward, in `rewardHandlerArgs.requirements`. [Prizes and inventory](/docs/inventory/prizes#the-details-form) shows how to turn them into form fields, which is the same for a quest, a loot box and a store purchase.
Do not build the payload by hand. The same three fields are sent in three different shapes to three different endpoints, and `toAllocationClaimPayload` is the one for a quest claim.
Collect the details before the fan presses claim. A claim that fails validation is a worse moment than one extra field.
## Delivery [#delivery]
After a claim, an allocation has two statuses, and together they say where the reward is:
| `claimStatus` | `distributionStatus` | Means | Show |
| ------------- | -------------------- | ------------------------------ | ---------------- |
| `ALLOCATED` | `ALLOCATED` | Waiting to be claimed | The claim button |
| `CLAIMED` | `ALLOCATED` | Claimed, still being delivered | Processing |
| `CLAIMED` | `DISTRIBUTED` | The fan has it | Done |
Physical prizes can sit at claimed and processing for a while. That is fulfilment, not a failure.
## Loot boxes [#loot-boxes]
The one flow with a wait in it, and worth building properly because it is the most fun moment in the product.
The reward slug is `give_lootboxes`. Claiming it opens the box. The contents resolve on the server a moment later, and your overlay covers that gap.
```tsx
import {
buildLootboxListingFallback,
getQuestRewardAllocations,
resolveLootboxSelectedItem,
useFanbase,
useLootboxes,
useQuest,
} from '@xborglabs/fanbase-react'
function LootboxReveal({ lootboxId }) {
const { meta } = useFanbase()
const { state, actions } = useQuest()
const [opening, setOpening] = useState(null)
const [waiting, setWaiting] = useState(false)
const { data: boxes } = useLootboxes({ lootboxIds: [lootboxId] }, Boolean(opening))
async function open() {
setWaiting(true)
await actions.claimAllAllocated()
// the contents are not in the claim response: poll until they land
const found = await pollUntil(
async () => {
const { allocations } = await getQuestRewardAllocations(meta.http, state.questId)
return allocations.find((a) => a.lootboxOpening?.selectedItem)?.lootboxOpening
},
{ intervalMs: 700, timeoutMs: 20000 },
)
setOpening(found ?? null)
setWaiting(false)
}
const possibleItems = boxes?.[0]?.items?.length
? boxes[0].items
: opening?.selectedItem
? buildLootboxListingFallback(opening.selectedItem, lootboxId)
: []
const winner = opening && resolveLootboxSelectedItem(opening.selectedItem, possibleItems, opening.selectedItemId)
return (
<>
{waiting && }
{winner && }
>
)
}
```
`pollUntil` is yours: call the function every interval until it returns something, and give up at the timeout.
Four things to get right:
**Poll, do not assume.** The contents are not in the claim response. Poll the allocations until `lootboxOpening.selectedItem` appears.
**Cap the wait.** A timeout with a fallback message beats a spinner that never ends.
**Show what was possible.** The reveal lands harder next to what could have come out. `useLootboxes` returns the box's possible items. If that list comes back empty, `buildLootboxListingFallback` builds one from the winner so the reveal still has art.
**Use the wait.** An opening animation covering the poll turns latency into anticipation. Most partners overbuild the reveal and underbuild everything else, which for once is the right call.
### When the item needs details [#when-the-item-needs-details]
If the item a fan wins is a prize that needs an address or an email, there is a second claim, for the item itself. Every other win is delivered the moment the box opens.
Check before you offer it:
```tsx
import { resolvePrizeClaimState, toSubmissionData, useClaimLootbox, usePrize } from '@xborglabs/fanbase-react'
const { data: prize } = usePrize(winner?.prizeId ?? '', Boolean(winner?.prizeId))
const { state: claimState } = resolvePrizeClaimState({ opening, prize })
const { claimLootbox } = useClaimLootbox()
if (claimState === 'REQUIREMENTS_REQUIRED') {
// show the details form, then:
await claimLootbox({ transactionId: opening.transactionId, opening, prize, submissionData: toSubmissionData(values) })
}
```
Only `REQUIREMENTS_REQUIRED` allows it. For anything else, `claimLootbox` refuses without sending a request. That matters: claiming a win that was already delivered fails on the platform as a server error, indistinguishable from an outage. Letting the SDK check first means it never gets that far.
The loot box claim uses `toSubmissionData`, not the quest claim's builder. Different endpoint, different shape. [Prizes and inventory](/docs/inventory/prizes#claim-states) covers every claim state.
## Checklist [#checklist]
* Rewards render before completion, signed in or not
* Reward art and labels come from `resolveQuestRewardChrome`, not a local map
* An unknown reward type renders nothing rather than a broken card
* `fetchRewards` is on for the detail page, off for the list
* A quest with two rewards ends with both claimed
* A prize needing an email collects it before the claim
* A loot box claim shows an animation, then the actual item, and has a timeout path
* A won prize that needs details offers its own claim, and nothing else does
# Quest templates (/docs/quests/templates)
The map from template name to what you render and what you submit. Dozens of template names are live. You do not write a branch per name, you write one per family.
## What arrives on the wire [#what-arrives-on-the-wire]
Three different vocabularies show up on a quest, and mixing them up is the most
expensive mistake on this page.
**`template.name` is a namespaced wire value**, lowercase and dotted:
```
basic.auto-complete
basic.submit-wallet
```
**The family names below are not wire values, and no SDK function returns them.**
`text`, `visit`, `bind` and the rest are a grouping you map names into yourself, with
the router under [Routing](#routing). Comparing `template.name === 'visit'` matches
nothing, and because the comparison fails quietly, every quest falls through to your
default branch and the page looks like it works.
Two SDK helpers look like they should do this and do not. `getApiType` returns the
submit path, `accept`, `complete` or `image`, and `getQuestType` returns a number.
Neither is a family. Switching on either one sends every quest to your default branch.
**Requirement codes are a third namespace**, upper snake case, and they are what you
see when the machine holds a quest closed rather than what you switch on:
| Code | Means |
| ------------------------ | -------------------------------------------------------------------------------------------------------- |
| `VISIT_LINK_MISSION` | An outbound link the fan has not opened. See [Visit-link quests](/docs/quests/detail#visit-link-quests). |
| `EVENT_JOIN_NOT_ALLOWED` | The fan cannot join the event this quest belongs to. |
| `SOCIAL_*` | A social account that is not linked. Needs `authProfile`. |
| `WALLET_*` | A wallet that is not linked. Needs `authProfile`. |
| `JOIN_*` | A community membership gate. |
A quest also carries `questType`, a coarse grouping such as `SOCIAL`. It is not the
template and it is not granular enough to route on.
The full list of names ships inside the package, in the Catalog section of
`node_modules/@xborglabs/fanbase-react/quest.md`. The router below covers every
typed name in it. Anything it does not recognise is empty-body, which is the safe
default.
## Families [#families]
Filter by how you submit. Typed families take a payload, empty-body families do not, and that distinction is the one your code actually branches on.
### The same thing as a table [#the-same-thing-as-a-table]
| Family | Submit | You render |
| ------------ | ----------------- | ----------------------------------- |
| `text` | `submit(payload)` | A text field |
| `answer` | `submit(payload)` | A free-form answer field |
| `prediction` | `submit(payload)` | Outcome picker |
| `quiz` | `submit(payload)` | Question with options |
| `poll` | `submit(payload)` | Options, single choice |
| `email` | `submit(payload)` | Email field with validation |
| `wallet` | `submit(payload)` | Wallet address field |
| `image` | `submit(payload)` | File upload with preview |
| `visit` | `Quest.Submit` | Outbound link, then the CTA |
| `bind` | `Quest.Submit` | Link-account button, then the CTA |
| `progress` | `Quest.Submit` | Progress readout, CTA when complete |
| `auto` | `Quest.Submit` | Status, no input |
| `unknown` | `Quest.Submit` | Fall through to the default branch |
Typed families take a payload. Empty-body families do not. That distinction is the one your code branches on.
## Routing [#routing]
Map the template name to a family yourself. Only eight names take a payload, so the map is short, and everything you do not recognise falls through to an empty-body submit:
```ts
// Yours to own. Built from the template catalog in the package's quest.md.
const TYPED = {
'basic.text-submission': 'text',
'basic.answer-submission': 'answer',
'basic.prediction': 'prediction',
'basic.quiz': 'quiz',
'basic.poll': 'poll',
'basic.submit-email': 'email',
'basic.submit-wallet': 'wallet',
'manual.image-submission': 'image',
}
const VISIT = new Set([
'basic.visit-link', 'basic.visit-facebook', 'basic.visit-instagram',
'basic.view-instagram-post', 'basic.view-tiktok-post',
'youtube.visit-channel', 'youtube.watch-video',
])
const BIND = new Set(['twitch.follow', 'twitch.subscribe', 'youtube.subscribe', 'youtube.like', 'steam.wishlist-game'])
const BIND_PREFIXES = ['twitter.', 'discord.', 'spotify.']
export function familyOf(name = '') {
if (TYPED[name]) return TYPED[name]
if (VISIT.has(name)) return 'visit'
if (BIND.has(name) || BIND_PREFIXES.some((p) => name.startsWith(p))) return 'bind'
if (name === 'basic.auto-complete') return 'auto'
return 'other' // progress, gaming, wallet checks and anything new: empty body
}
```
Typed names come first because they are the ones where a wrong guess loses the fan's input. A new empty-body template needs no change here at all. A new typed one does, and the package's changelog is where you would see it.
## Always have a default [#always-have-a-default]
```tsx
default:
return (
)
```
An unrecognised name should render something usable rather than a blank panel. The machine still knows whether the fan can act.
## Template args [#template-args]
`template.args` carries the settings a community team configured for that quest. Options for a poll, a URL for a visit, an accepted file type for an upload.
Read defensively. Args are per-template, optional keys are common, and a key being
present in the admin panel does not mean it arrives populated:
```tsx
const options = template.args?.options ?? []
const url = template.args?.url
```
Types vary across communities for some flags, so compare loosely rather than with a strict `=== true` on a value that might arrive as a string.
Two things worth knowing before you rely on a key:
**A documented key can still be null on live rows.** Text-submission quests on beta
have been observed with `args.text` null across every row on a tenant. Supply your
own fallback label rather than rendering an empty prompt:
```tsx
const prompt = template.args?.text ?? 'Your answer'
```
**Some templates carry matching flags alongside the value.** An answer-family quest
arrives with the comparison rules next to it:
```json
{ "answer": "1WH3NC1", "matchExactly": true, "caseSensitive": true }
```
You submit what the fan typed and let the platform compare. Do not do the comparison
yourself, even though the pieces are sitting right there.
## Payload shapes [#payload-shapes]
Every typed template sends its value under `text`, whatever the family. Only the image upload is different.
| Family | Payload | Notes |
| ------------ | ------------------------ | ------------------------------------------------------------------------------------------- |
| `text` | `{ text: string }` | At least 3 characters |
| `answer` | `{ text: string }` | Not `answer`. The fan's earlier answer reads back from `quest.metrics.answer`. |
| `prediction` | `{ text: option.label }` | The option's label, not its index. [Predictions](/docs/predictions/build#sending-the-pick). |
| `quiz` | `{ text: option }` | The option string itself. The platform marks it. |
| `poll` | `{ text: option }` | The option string itself |
| `email` | `{ text: email }` | |
| `wallet` | `{ text: address }` | A `0x` address |
| `image` | `File[]` | The files, passed straight to `actions.submit` |
| empty-body | none | |
Do not invent a payload shape. If a template needs something not listed here, ask rather than guessing, because the platform validates on submit and a wrong shape fails silently from the fan's point of view.
## Display names [#display-names]
Templates carry a `displayName` for admin-facing surfaces. Fan-facing copy comes from the quest's own title and description, so you rarely need it in your app.
# API endpoints (/docs/reference/api)
The REST surface behind the SDK. Most of it you never call directly, since the hooks cover it. Useful for debugging, and for reading what a hook is doing in your network tab.
Base URL is your `gamerBaseUrl`. Beta and production differ.
## Headers [#headers]
| Header | When |
| ------------------------------------- | ----------------------------- |
| `xb-tenant` | Every request. Your tenant. |
| `Authorization: Bearer ` | Every request once signed in. |
The SDK sets both. If you use `meta.http` from `useFanbase()`, you get them too.
`{communityId}` in the paths below is your community's id. The SDK resolves it from your `slug` with the first call under Community, so you never supply it.
## Auth [#auth]
| Method | Path | Notes |
| ------ | -------------------------------- | ----------------------------------------------------------------------------- |
| `POST` | `/v1/user/auth/{provider}/login` | Exchanges an OAuth callback token for a session. `loginWithToken` calls this. |
## Fan [#fan]
| Method | Path | Notes |
| ------ | -------------------------------- | ------------------------------------------------------------------------------------ |
| `GET` | `/v1/user/profile` | Wallets. Feeds `authProfile.wallets`. |
| `GET` | `/v1/user/socials` | Linked accounts, with expiry dates. `useLinkedSocials`. Feeds `authProfile.socials`. |
| `GET` | `/v1/user/socials/{accountType}` | One linked account |
| `POST` | `/v1/user/socials/bind-token` | Redeems a link token. `useBind`. [Linking accounts](/docs/linking). |
## Community [#community]
| Method | Path | Notes |
| ------ | ---------------------------------------------- | ------------------------------------------------------------------------------------------------- |
| `GET` | `/v1/community/{slug}` | Resolves your slug to a community. Everything scoped to a community starts here. |
| `GET` | `/v1/community/{communityId}/membership` | The fan's membership. Fails for a non-member. [Membership](/docs/membership#the-error-to-expect). |
| `GET` | `/v1/community/{communityId}/membership/tiers` | The community's tiers |
| `GET` | `/v1/community/{communityId}/ranking/xp` | The fan's XP and level. `useCommunityXP`. |
| `GET` | `/v1/community/{communityId}/resource-types` | Currency names. Public. |
## Quests [#quests]
| Method | Path | Notes |
| ------ | -------------------------------------------------------------------- | ------------------------------------------------ |
| `GET` | `/v1/quests` | The list. `useQuestsList`. One call per page. |
| `GET` | `/v1/quests/{id}` | One quest. `Quest.Provider`. |
| `POST` | `/v1/quests/{id}/accept` | Accept step |
| `POST` | `/v1/quests/{id}/complete` | Submit and complete |
| `POST` | `/v1/quests/{id}/refresh` | Re-checks a progress-tracked quest |
| `GET` | `/v1/quests/{id}/results` | Poll and prediction outcomes. `useQuestResults`. |
| `GET` | `/v1/quests/{id}/reward/allocations` | The fan's rewards on a quest. `fetchRewards`. |
| `POST` | `/v1/quests/{questId}/reward/allocations/claim/{rewardAllocationId}` | Claims one reward |
| `GET` | `/v1/quests/history` | The fan's completed quests |
| `GET` | `/v1/quests/{questId}/streak` | The fan's streak on one quest |
| `GET` | `/v1/quests/stats` | Community quest counts |
## Battlepass [#battlepass]
| Method | Path | Notes |
| ------ | ----------------------------------------- | ---------------------------------------------------------------------------------------------- |
| `GET` | `/v1/battlepass/progress` | The live season and the fan's progress. Returns `season: null` when there is no active season. |
| `GET` | `/v1/battlepass/seasons` | Every season, for a switcher |
| `GET` | `/v1/battlepass/seasons/{seasonId}` | One season |
| `POST` | `/v1/battlepass/tiers/{questId}/complete` | Completes a tier. Never use the quest endpoint for a tier. |
A tier's rewards claim through the ordinary quest allocation claim above. There is no battlepass claim endpoint.
## Store [#store]
| Method | Path | Notes |
| ------ | --------------------------------- | -------------------------------------------------------------------------------------------------------------- |
| `GET` | `/v1/store/listings` | Listings, filtered and paged on the server |
| `GET` | `/v1/store/tags` | Tags, for filters |
| `GET` | `/v1/store/carousel` | Featured slides |
| `GET` | `/v1/store/balance` | The fan's balances, one per currency |
| `POST` | `/v1/store/purchase/{listingId}` | Buys a listing. Carries a `nonce`. [Never retry with a new one](/docs/store/buy#never-retry-with-a-new-nonce). |
| `GET` | `/v1/store/purchase` | The fan's purchase history |
| `GET` | `/v1/store/purchase/{purchaseId}` | One purchase, with its delivery status |
## Leaderboard [#leaderboard]
| Method | Path | Notes |
| ------ | ------------------------------------------------ | ------------------------------------ |
| `GET` | `/v1/community/{communityId}/leaderboard/{slug}` | One page of a board. Public. |
| `GET` | `/v1/community/{communityId}/ranking/{slug}` | The fan's own row. `xp` or `quests`. |
## Newsfeed [#newsfeed]
| Method | Path | Notes |
| -------- | -------------------------------------------------------------------------- | ------------------------------ |
| `GET` | `/v1/community/{communityId}/news` | The feed |
| `GET` | `/v1/community/{communityId}/news/{newsId}` | One post |
| `POST` | `/v1/community/{communityId}/news/{newsId}` | Reacts to a post |
| `GET` | `/v1/community/{communityId}/news/publishers` | Publishers |
| `GET` | `/v1/community/{communityId}/news/reactions/types` | The community's reaction emoji |
| `GET` | `/v1/community/{communityId}/news/{newsId}/comments` | Comments |
| `POST` | `/v1/community/{communityId}/news/{newsId}/comments` | Posts a comment or reply |
| `PUT` | `/v1/community/{communityId}/news/{newsId}/comments/{commentId}` | Edits a comment |
| `DELETE` | `/v1/community/{communityId}/news/{newsId}/comments/{commentId}` | Deletes a comment |
| `GET` | `/v1/community/{communityId}/news/{newsId}/comments/{commentId}/replies` | More replies |
| `POST` | `/v1/community/{communityId}/news/{newsId}/comments/{commentId}/vote` | Votes on a comment |
| `POST` | `/v1/community/{communityId}/news/{newsId}/comments/{commentId}/reactions` | Reacts to a comment |
## Prizes and inventory [#prizes-and-inventory]
| Method | Path | Notes |
| -------- | ------------------------------------------------------- | --------------------------------------------------------------------------- |
| `GET` | `/v1/inventory/prizes` | Prizes. `ownedOnly` narrows to the fan's. |
| `GET` | `/v1/inventory/prizes/{prizeId}` | One prize, with the details it asks for |
| `GET` | `/v1/inventory/lootbox` | A loot box's possible items. [The reveal](/docs/quests/rewards#loot-boxes). |
| `POST` | `/v1/inventory/lootbox/claim` | Sends a won prize's details. Only when it is claimable. |
| `GET` | `/v1/community/{communityKey}/inventory/items/{itemId}` | One item the fan holds |
| `GET` | `/v1/inventory/personalizations` | Cosmetics |
| `GET` | `/v1/inventory/personalizations/equipped` | What the fan is wearing |
| `POST` | `/v1/inventory/personalizations/equip` | Equips one |
| `DELETE` | `/v1/inventory/personalizations/equip/{kind}` | Takes one off |
| `POST` | `/v1/inventory/personalizations/equip/batch` | Equips a whole draft |
## Using the client directly [#using-the-client-directly]
```tsx
const { meta } = useFanbase()
const profile = await meta.http.get('/v1/user/profile')
```
Prefer this over your own `fetch`, so the tenant header and token handling stay in one place.
## Server-to-server [#server-to-server]
This SDK is for browser apps and its tokens are fan sessions. Backend integrations that read community data on a schedule use the platform Data API with an API key instead, which is a separate surface. Ask your FanBase contact.
# Components (/docs/reference/components)
Four compounds: `Quest`, `Battlepass`, `Store` and `Leaderboard`. All of them render your markup. None ship CSS.
The newsfeed, prizes and account linking have no compound. They are hooks only, because there is no shared state worth a provider. See [Hooks](/docs/reference/hooks).
## The asChild pattern [#the-aschild-pattern]
```tsx
```
The component attaches behaviour to your element. Your class names and props pass through unchanged.
Without `asChild` you get a bare unstyled element, which is rarely what you want in production.
## Quest.Provider [#questprovider]
Loads a quest, runs the state machine, provides `useQuest()`.
| Prop | Required | Notes |
| -------------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `questId` | yes | The quest to load. |
| `quest` | no | Seed row from the list, for instant render. Let the provider own it, do not mirror it in your own state. See [Quest detail](/docs/quests/detail#seeding-from-the-list-row). |
| `authProfile` | no | `{ socials, wallets }` from the fan profile. Omit it and social and wallet gated quests stay disabled. |
| `fetchRewards` | no | Flag. Loads the fan's reward allocations, which is what the claim button needs. Off by default. Needs a session. |
| `claimPayload` | no | Details a prize claim requires. Build it with `toAllocationClaimPayload`. [Claims that need details](/docs/quests/rewards#claims-that-need-details). |
## Quest.Frame [#questframe]
Wraps your detail UI inside the provider. Structural only.
## Quest.Description [#questdescription]
Renders the structured description.
| Prop | Notes |
| ------- | ------------------------------------ |
| `theme` | Maps node types to your class names. |
Theme keys: `paragraph`, `heading.{h1,h2,h3}`, `list.{ul,ol,listitem}`, `link`, `text.{bold,italic,underline,strikethrough}`, `quote`, `code`.
See [Quest descriptions](/docs/quests/descriptions).
## Quest.Submit [#questsubmit]
Submit CTA for empty-body templates. Visit, bind, progress, automatic.
```tsx
```
Typed templates use `actions.submit(payload)` instead. This component submits with no body.
## Quest.Accept [#questaccept]
Accept step, for templates that have one. Same pattern.
## Quest.Complete [#questcomplete]
Complete step, for templates that have one. Same pattern.
## Quest.Claim [#questclaim]
Claim CTA. Show when `state.canClaim`. Claims every waiting reward on the quest, not only the first.
```tsx
{state.canClaim && (
)}
```
## Disabled state [#disabled-state]
Put `disabled` on your own element, driven by `state.canSubmit` or `state.canClaim`.
```tsx
```
## Battlepass [#battlepass]
[Rendering a season](/docs/battlepass/season)
| Part | Use |
| --------------------- | ---------------------------------------------------------------------------------------------------------- |
| `Battlepass.Provider` | Reads the season, the fan's membership and XP, and derives the lanes. Omit `seasonId` for the live season. |
| `Battlepass.Season` | Season header. Render prop: `{ season, claimsEnabled, currentLevel, maxLevel }`. |
| `Battlepass.Lane` | Every lane in order, paid first. `laneId` renders one. |
| `Battlepass.Tier` | One cell per level in a lane, gaps included. Render prop: `{ slot, level, gate, canClaim }`. |
| `Battlepass.Claim` | Claims one tier, every reward on it. Takes `asChild`. |
| `Battlepass.ClaimAll` | Claims every tier that can settle on its own. Takes `asChild`. |
| `Battlepass.Provider` prop | Notes |
| -------------------------- | ------------------------------------------------------------------------------------ |
| `seasonId` | One season. Leave it off for the live one, including when there is no active season. |
| `authProfile` | As on `Quest.Provider`, for tiers that gate on a linked account. |
## Store [#store]
[Browsing the store](/docs/store/browse) and [Buying](/docs/store/buy)
| Part | Use |
| ------------------- | -------------------------------------------------------------------------- |
| `Store.Provider` | Reads listings, balances, tiers and currency names |
| `Store.Listing` | One listing, with its purchase gate worked out |
| `Store.Description` | A listing's description. `isPlain` for a card. |
| `Store.Checkout` | Holds the chosen price and the fan's details |
| `Store.Purchase` | The buy button. Disables itself while the gate is locked. Takes `asChild`. |
| `Store.Provider` prop | Notes |
| --------------------- | ------------------------------------------------------------------ |
| `enrichRequirements` | Reads back details the fan already saved. Keep it on. |
| `filters` | `{ sort, maxPrice, inStockOnly, tagIds }`. Filtered on the server. |
| `page`, `limit` | Paging. `limit` defaults to 20. |
| `Store.Checkout` prop | Notes |
| --------------------- | ---------------------------------------------------------------------------- |
| `pricingOption` | The price to charge. Pass the sale price yourself: the default is the first. |
| `requirementData` | From `toPurchaseRequirementData`. Clears `REQUIREMENTS_MISSING`. |
## Leaderboard [#leaderboard]
[Rendering a board](/docs/leaderboard/board)
| Part | Use |
| -------------------------- | ------------------------------------------------------ |
| `Leaderboard.Provider` | Reads one page of a board and the fan's own row |
| `Leaderboard.PreviousPage` | Previous page. Disabled on the first. Takes `asChild`. |
| `Leaderboard.NextPage` | Next page. Disabled on the last. Takes `asChild`. |
| `Leaderboard.Provider` prop | Notes |
| --------------------------- | ---------------------------------------------------------------------- |
| `kind` | `LEADERBOARD_KIND.RESOURCE`, the default, or `LEADERBOARD_KIND.QUESTS` |
| `page` | Controlled page. Pass it with `onPageChange`, or leave both off. |
| `onPageChange` | Fires from the pagers. How the page gets into your URL. |
# Hooks (/docs/reference/hooks)
The whole hook surface, grouped by feature. Each group links to the guide that uses it.
Every hook needs `FanbaseProvider` above it. Hooks named after a compound, like `useQuest` or `useBattlepass`, also need that compound's provider, and throw outside one.
All of them are react-query under your own client, so SDK queries show up in devtools alongside yours.
None of them take a `communityId` you have to supply. Anything scoped to a community resolves it from the `slug` on [`FanbaseProvider`](/docs/reference/provider).
## useFanbase() [#usefanbase]
Session, config and the authenticated HTTP client. Available anywhere under `FanbaseProvider`.
```tsx
import { useFanbase } from '@xborglabs/fanbase-react'
const { state, actions, meta } = useFanbase()
```
### state [#state]
| Field | Notes |
| --------- | --------------------------------------------------------------------- |
| `ready` | The provider has finished restoring any stored session. Gate on this. |
| `session` | `{ accessToken, refreshToken }` when signed in, else `null`. |
| `config` | The resolved configuration. |
### actions [#actions]
| Action | Notes |
| ------------------------------------- | ------------------------------------------------------------------------------------------ |
| `loginWithToken({ provider, token })` | Exchanges an OAuth callback token. The provider has to match the one that started sign-in. |
| `bind({ token, accountType })` | Redeems a link token. Never touches the session. [Linking accounts](/docs/linking). |
| `refreshSession()` | Refreshes the tokens. Rarely needed: the client does it on a 401. |
| `logout()` | Clears the adapter and the in-memory session. |
### meta [#meta]
| Field | Notes |
| ------------- | ------------------------------------------------------------------------------------------------------ |
| `http` | Authenticated client. Tenant header, Bearer token and 401 retry handled. For endpoints without a hook. |
| `queryClient` | The react-query client the SDK uses. |
Three narrower hooks read one piece each: `useFanbaseSession()` for the session, `useFanbaseConfig()` for the tenant, slug and app id, and `useFanbaseHttp()` for the client.
## useQuest() [#usequest]
Quest state and actions inside a `Quest.Provider`.
```tsx
import { useQuest } from '@xborglabs/fanbase-react'
const { state, actions } = useQuest()
```
### state [#state-1]
| Field | Notes |
| --------------------- | ------------------------------------------------------------------------------------------ |
| `quest` | The quest, including `template.name`, `template.args` and `rewards`. |
| `rewards` | The fan's reward allocations, when the provider has `fetchRewards` and there is a session. |
| `machine` | The machine's full verdict. `machine.reason` is why the fan cannot act. |
| `canSubmit` | Whether the fan can act now. |
| `canClaim` | Whether a reward is waiting. |
| `buttonLabel` | The label for the current state, already resolved. |
| `disabledReasonLabel` | Why the fan cannot act, in a sentence. Worth showing. |
### actions [#actions-1]
| Action | Notes |
| ------------------------------------- | -------------------------------------------------------- |
| `submit(payload?)` | A payload for typed templates, none for empty-body ones. |
| `accept(payload?)` | The accept step, where a template has one. |
| `complete(payload?)` | The complete step, where a template has one. |
| `claimAllAllocated(payload?)` | Claims every waiting reward. What `Quest.Claim` does. |
| `claimFirstAllocated(payload?)` | Claims the first waiting reward. |
| `claim(rewardAllocationId, payload?)` | Claims one named allocation. |
| `refetch()` | Refetches the quest. |
## Quests [#quests]
[Quests](/docs/quests/model)
| Hook | For |
| ---------------------------- | --------------------------------------------------------------------------------------- |
| `useQuestsList()` | The quest list. One request for the page, never one per card. Works signed out. |
| `useQuest()` | State and actions inside `Quest.Provider`. Above. |
| `useQuestDetail()` | One quest, outside `Quest.Provider` |
| `useQuestResults(questId)` | Entry counts per option for a poll or a [prediction](/docs/predictions/build#the-split) |
| `useQuestHistory()` | The fan's completed quests |
| `usePaginatedQuestHistory()` | The same, a page at a time |
| `useQuestStats()` | Community quest counts over a window of days |
| `useQuestStreak()` | The fan's streak on one quest |
| `useQuestTranslate()` | A translate function for `Quests.*` display strings |
## Battlepass [#battlepass]
[Battlepass](/docs/battlepass/model)
| Hook | For |
| ------------------------------- | --------------------------------------------------------------------- |
| `useBattlepass()` | State and actions inside `Battlepass.Provider` |
| `useBattlepassLane()` | The lane a `Battlepass.Lane` is rendering |
| `useBattlepassTier()` | The slot a `Battlepass.Tier` is rendering, with its gate |
| `useBattlepassProgress()` | The live season and its tiers, outside the provider |
| `useBattlepassSeasons()` | Every season, for a season switcher |
| `useBattlepassSeason(seasonId)` | One season with its tiers |
| `useCompleteTier()` | Completes a tier that takes an input |
| `useClaimAllTiers(slots)` | Claims every tier that can settle on its own, and hands back the rest |
## Store [#store]
[Store](/docs/store/model)
| Hook | For |
| ---------------------------------------------- | ------------------------------------------------------- |
| `useStore()` | State and actions inside `Store.Provider` |
| `useStoreListing()` | One listing and its gate, inside `Store.Listing` |
| `useStoreListings()` | Listings, outside the provider |
| `useStoreTags()` | Tags, for filter chips |
| `useStoreCarousel()` | Featured carousel slides |
| `useSpendableResources()` | The fan's balances, one per currency |
| `useResourceTypes()` | Currency names, public, for pricing signed-out fans |
| `usePurchaseListing()` | Buys a listing, outside the compound |
| `usePurchases()` | The fan's store purchase history |
| `usePurchase(purchaseId, { refetchInterval })` | One purchase, pollable, for a Shopify order in progress |
## Leaderboard [#leaderboard]
[Leaderboard](/docs/leaderboard/model)
| Hook | For |
| ------------------------------------------- | ------------------------------------------------- |
| `useLeaderboard()` | State and actions inside `Leaderboard.Provider` |
| `useLeaderboardList({ kind, page, limit })` | One page of a board, outside the provider |
| `useLeaderboardViewerRank({ kind })` | The signed-in fan's own row, outside the provider |
## Newsfeed [#newsfeed]
[Newsfeed](/docs/newsfeed/model). There is no provider: these are the whole surface.
| Hook | For |
| -------------------------------------------------- | --------------------------------------- |
| `useNewsfeedFeed(filters)` | The feed, as an infinite query |
| `useNewsfeedPost({ newsId })` | One post |
| `useNewsfeedPublishers()` | Publishers, for filter chips |
| `useNewsfeedReactionTypes()` | The community's reaction emoji |
| `useReactToPost()` | Reacts to a post. Optimistic. |
| `useNewsfeedComments({ newsId, sort })` | A post's comments, as an infinite query |
| `useNewsfeedCommentReplies({ newsId, commentId })` | More replies under one comment |
| `usePostComment()` | Posts a comment or a reply. Optimistic. |
| `useUpdateComment()` | Edits the fan's own comment |
| `useDeleteComment()` | Deletes the fan's own comment |
| `useCommentVote()` | Votes on a comment. Optimistic. |
| `useReactToComment()` | Reacts to a comment. Optimistic. |
## Prizes and inventory [#prizes-and-inventory]
[Prizes and inventory](/docs/inventory/prizes)
| Hook | For |
| -------------------------------------------- | ------------------------------------------------------------ |
| `usePrizes({ ownedOnly })` | Prizes in the community, or the ones this fan owns |
| `usePrize(prizeId)` | One prize, with the details it asks for |
| `useLootboxes({ lootboxIds })` | A loot box's possible items, for the reveal |
| `useClaimLootbox()` | Sends a won prize's details. Refuses unless it is claimable. |
| `useInventoryItem({ communityKey, itemId })` | One inventory item the fan holds |
| `usePersonalizations({ ownedOnly, kind })` | Cosmetics, filtered by kind |
| `useEquippedPersonalization()` | What the fan is wearing now |
| `useBatchEquipPersonalizations()` | Equips a whole draft at once |
| `useEquipPersonalization()` | Equips one |
| `useUnequipPersonalization()` | Takes one off |
## Linking accounts [#linking-accounts]
[Linking accounts](/docs/linking)
| Hook | For |
| -------------------- | ------------------------------------------------------------------ |
| `useBind()` | Redeems a link token on your callback page |
| `useLinkedSocials()` | The fan's linked accounts, with expiry dates. Feeds `authProfile`. |
## Community and membership [#community-and-membership]
[Membership](/docs/membership)
| Hook | For |
| -------------------------- | ---------------------------------------------------------------------- |
| `useCommunity()` | The community, resolved from your slug |
| `useResolvedCommunityId()` | Just its id, for writes that need one |
| `useMembership()` | The fan's membership. Errors for a non-member: treat that as rank 0. |
| `useMembershipTiers()` | The community's tiers, lowest rank first |
| `useCommunityXP()` | The fan's XP and level. Always XP, whichever leaderboard is on screen. |
## Outside the hooks [#outside-the-hooks]
Every read also has a `prepare…Options` factory and every write a `prepare…Mutation`, for a server-side prefetch or a query client you manage yourself. Each feature exports its query keys, like `FANBASE_STORE_KEYS`, and an `invalidateFanbase…Queries` function. You rarely need them: every write already refreshes what it touched.
# FanbaseProvider (/docs/reference/provider)
Configuration, session and API client for everything below it. Mount near the root.
## Props [#props]
| Prop | Required | What it is |
| ------------- | -------- | -------------------------------------------------- |
| `tenant` | yes | Tenant host. Sent as `xb-tenant` on every request. |
| `slug` | yes | Community slug. |
| `appId` | yes | Identifier for this app or environment. |
| `httpOptions` | yes | `{ gamerBaseUrl, locale }`. |
| `session` | yes | Adapter with `get`, `set`, `clear`. |
| `queryClient` | yes | Your `QueryClient`. You own it. |
| `children` | yes | Your tree. |
### httpOptions [#httpoptions]
| Key | Notes |
| -------------- | -------------------------------------------------- |
| `gamerBaseUrl` | API base URL. Differs between beta and production. |
| `locale` | Language for API-side content. Defaults to `en`. |
### session [#session]
```ts
interface SessionAdapter {
get(): Session | null
set(session: Session): void
clear(): void
}
```
`localStorage` is fine for a browser SPA. Swap for cookies or a server-backed store without touching anything else.
## Query client [#query-client]
The provider mounts its own `QueryClientProvider` around your children, using the client you passed. Your `useQuery` calls need to be inside it, which they are if the provider is near the root.
## Example [#example]
```tsx
```
## Mounting [#mounting]
One provider per app. Nesting is not supported and multiple providers do not give you multiple communities in one tree.
Wait for `state.ready` from `useFanbase()` before acting on session state anywhere below.
# Browsing the store (/docs/store/browse)
The storefront. Mostly your design, with the SDK doing the data and the arithmetic.
## The shape [#the-shape]
```tsx
import { Store, useStore } from '@xborglabs/fanbase-react'
export function StorePage() {
return (
)
}
function Grid() {
const { state } = useStore()
if (state.isLoading) return
if (state.error) return
if (!state.listings.length) return
return (
{state.listings.map((listing) => (
))}
)
}
```
`Store.Provider` reads the listings, the fan's balances, the membership tiers and the currency names in one go. `Store.Listing` wraps one card and works out whether that listing can be bought.
Do not pass a `containerId` or `communityId`. The provider resolves them from the `slug` on [`FanbaseProvider`](/docs/reference/provider).
Keep `enrichRequirements` on. It fills in details the fan has already saved, like their shipping address, so a listing that needs one does not wrongly report it as missing. Turning it on for a separate `useStoreListings` call beside the provider does not help: it has to be on the provider, because that is the read that fills the grid.
The store works signed out. Listings, prices and currency names are public. Balances and membership only load once a fan signs in.
## Filters [#filters]
Four of them, and the SDK turns them into the request for you. Pass them to the provider:
```tsx
import { STORE_SORT } from '@xborglabs/fanbase-react'
```
| Sort | Order |
| --------------------------- | --------------------------------- |
| `STORE_SORT.ALL` | The order your community team set |
| `STORE_SORT.CHEAPEST` | Price, low to high |
| `STORE_SORT.MOST_EXPENSIVE` | Price, high to low |
| `STORE_SORT.NEWEST` | Newest first |
Filtering happens on the server, so paging stays correct. `limit` defaults to 20.
The SDK holds no filter state and does not read the URL. Keep the filters in your router's query string, so a filtered view survives a refresh and can be shared as a link.
## Tags [#tags]
Your community team tags listings in the admin panel. Read the tags for your filter chips with a hook beside the provider:
```tsx
import { useStoreTags } from '@xborglabs/fanbase-react'
const { data } = useStoreTags()
data?.results.map((tag) => (
))
```
Tag labels arrive already translated. Put the `tagId`s you select into `filters.tagIds`.
## The featured carousel [#the-featured-carousel]
Optional, and configured in the Hub. Each slide links to a listing.
```tsx
import { useStoreCarousel } from '@xborglabs/fanbase-react'
const { data: slides = [] } = useStoreCarousel()
```
This one returns the slides directly, not inside `results`. A slide's `title`, `description` and buttons can all be empty if your team did not fill them in, so treat each as optional. The slide's own `description` is plain text. The listing it points to, at `slide.item`, has the same shape as a card.
## A card [#a-card]
Every listing arrives with a `unified` field: a name, an image and a description, whichever of the four listing types it is. Build cards from that and you never branch on type to find a title.
```tsx
import { Store, useStoreListing } from '@xborglabs/fanbase-react'
function ListingCard() {
const { state } = useStoreListing()
const { name, mediaUrl } = state.listing.unified
return (
{mediaUrl ? : }
{name || 'Untitled'}
)
}
```
Check for `mediaUrl` before rendering an image. An item with no art has no `mediaUrl` at all, rather than an empty string, so there is no broken image to guard against.
The item a listing points at can be missing even when its id is there. Read anything beyond `unified` with optional chaining, `listing.prize?.name`, so one incomplete listing does not take down the grid.
## Descriptions [#descriptions]
A listing description is structured content, the same format as a quest description. It is not a string and not markdown.
```tsx
// on a card: plain text, one line of it
// on a product page: the full render
```
Printed directly it comes out as `[object Object]`. [Quest descriptions](/docs/quests/descriptions) covers the format and how to style it.
## Prices [#prices]
A price is a number and a currency. `resolveStorePriceChrome` puts them together:
```tsx
import { getSpendableBalance, resolveStorePriceChrome, useStore, useStoreListing } from '@xborglabs/fanbase-react'
function Price() {
const { state: store } = useStore()
const { state } = useStoreListing()
const option = state.pricingOption
const chrome = resolveStorePriceChrome(option, store.balances, store.resourceTypes)
const balance = option ? getSpendableBalance(store.balances, option.resourceTypeId) : undefined
return (
{chrome?.label}
{store.isAuthenticated && You have {balance}}
)
}
```
`chrome.label` is `12 Credits`, or whatever your currency is called. It works for fans who are not signed in, because currency names are public.
Read the balance for the listing's own currency, as above. Never `balances[0]`. In a store with two currencies, the first balance is often the wrong one, and a fan with plenty of Coins gets told they cannot afford something priced in Coins.
## Sales [#sales]
A listing on sale has two prices: the sale one, with `isSale: true`, and the normal one. The SDK does not pick the sale price for you. Unless you say otherwise, the gate and the checkout use the first price in the list.
Pick it yourself:
```tsx
const selected = listing.listings.find((option) => option.isSale) ?? listing.listings[0]
```
Then pass `selected` to the checkout, as [Buying](/docs/store/buy#the-shape) shows. The strikethrough and the percentage off are yours to draw from the two prices.
## Level requirements [#level-requirements]
Some listings need a minimum level. That badge is yours to render, from the listing's requirements. It is not part of the purchase gate, so a fan below the level will still see the buy button enabled, and the purchase will be refused with the same error as a bad email. If level-locked listings matter to your store, check the fan's level on the product page before you enable the button.
## Checklist [#checklist]
* The grid renders with no `containerId` or `communityId`
* `enrichRequirements` is on the provider
* Every card has a name, and art only where there is art
* Descriptions go through `Store.Description`, plain on cards
* Prices read `12 Credits`, signed in or not
* A store with two currencies shows the balance of the right one
* A sale listing sells at the sale price
* Filters live in the URL
# Buying (/docs/store/buy)
The checkout. Less code than it looks, and two traps that each cost a fan real currency if you miss them.
## The shape [#the-shape]
```tsx
import { Store } from '@xborglabs/fanbase-react'
function Checkout({ listing, requirementData }) {
const selected = listing.listings.find((option) => option.isSale) ?? listing.listings[0]
return (
)
}
```
`Store.Checkout` holds the price the fan picked and any details they filled in. `Store.Purchase` is the button that spends them, and it disables itself while the gate is locked or a purchase is in flight.
Pass the price you mean to charge. Without `pricingOption`, the checkout uses the first price on the listing, which for a sale item is the full price. See [Sales](/docs/store/browse#sales).
## The gate [#the-gate]
Worked out before anything is sent, from data the page already has. Read it from the listing scope:
```tsx
import { useStoreListing, resolveStorePriceChrome, useStore } from '@xborglabs/fanbase-react'
function GateMessage() {
const { state } = useStoreListing()
const { state: store } = useStore()
const reason = state.gate.reason
if (!reason) return null
switch (reason.reason) {
case 'MEMBERSHIP_REQUIRED':
return
}
}
}
```
| Reason | Show | Clears when |
| ---------------------- | ------------------------------------------------------ | -------------------------------------- |
| `MEMBERSHIP_REQUIRED` | The tier by name, and a way to upgrade | The fan's membership reaches that tier |
| `OUT_OF_STOCK` | Sold out | The item is restocked |
| `REQUIREMENTS_MISSING` | The details form | The fan fills it in |
| `INSUFFICIENT_BALANCE` | Which currency they are short of, and where to earn it | Their balance rises |
Only the first failing reason is reported, in that order.
A fan who is not signed in never gets `INSUFFICIENT_BALANCE`, because the SDK does not know their balance. Handle sign-in before checkout yourself. A buy button that sends a signed-out fan to sign-in is better than one that fails.
Name the tier from the reason. "For Premium members" tells a fan exactly what to do, and reading the name rather than hardcoding it keeps the copy right if the community renames the tier.
## Details a purchase needs [#details-a-purchase-needs]
Some listings need something from the fan: an email, a shipping address, a wallet address. Where those requirements live depends on the listing type, and the SDK reads the right place for you:
```tsx
import {
getPurchaseRequirementFields,
getPurchaseRequirements,
toPurchaseRequirementData,
} from '@xborglabs/fanbase-react'
const fields = getPurchaseRequirements(listing).flatMap(getPurchaseRequirementFields)
// render a form from `fields`, then on submit:
const requirementData = toPurchaseRequirementData(values)
```
Pass `requirementData` to `Store.Checkout` and `REQUIREMENTS_MISSING` clears.
Do not read `listing.prize?.requirements` yourself. A prize keeps its requirements on the prize. Every other type keeps them on the listing. `getPurchaseRequirements` knows which, and returns only the fields a fan fills in, in the order a form should ask for them.
An address comes back as its parts in checkout order: country, recipient name, three address lines, city, state, postal code. Details a fan enters are saved to their profile by default, so they do not type their address twice. That is also why `enrichRequirements` on the provider matters: it is what reads those saved details back in.
## Never retry with a new nonce [#never-retry-with-a-new-nonce]
Worth reading twice.
Every purchase is sent with a `nonce`, a one-time key that stops the same purchase going through twice. The SDK generates one for you.
If a purchase fails with `DuplicateNonceError`, the first attempt almost certainly went through. The platform is refusing a repeat of a purchase it already accepted. It does not replay the original result, it just refuses.
So the fix is not to retry. It is to check:
```tsx
import { DuplicateNonceError, usePurchases, useStoreListing } from '@xborglabs/fanbase-react'
const { actions } = useStoreListing()
const { refetch } = usePurchases()
try {
await actions.purchase()
} catch (error) {
if (error instanceof DuplicateNonceError) {
await refetch() // the purchase is almost certainly in here
return showPurchased()
}
throw error
}
```
Retrying with a fresh nonce is the one thing not to do. It is a new key, the platform accepts it, and the fan is charged twice for one item. The SDK never retries a purchase on its own for exactly this reason.
## Errors [#errors]
Every refusal comes back as a typed error. Switch on the class, never on the message.
| Error | Means | Show |
| --------------------------------- | ---------------------------------------- | ----------------------------------------------------- |
| `DuplicateNonceError` | This purchase already went through | See above. Do not retry. |
| `ListingUnavailableError` | The listing was removed | No longer available |
| `InsufficientBalanceError` | Not enough currency | Should not happen past the gate. Refetch the balance. |
| `PrizeRequirementValidationError` | A detail was rejected | Field-level errors on the form |
| `SupplyDepletedError` | Sold out, even though the card had stock | Sold out. See [Stock](/docs/store/model#stock). |
| `PurchaseTransferError` | The purchase could not complete | A generic failure. Do not retry automatically. |
`PrizeRequirementValidationError` also covers a fan below the membership tier and a fan below the level. The platform does not tell those apart from a bad email, which is the whole reason the gate is worked out up front.
## After a purchase [#after-a-purchase]
A purchase settles into one of four outcomes, one per listing type. Branch on it rather than going back to the listing:
```tsx
const { state } = useStore()
const outcome = state.settlement?.outcome
switch (outcome?.kind) {
case 'item':
return
case 'prize':
return outcome.awaitingFulfilment ? :
case 'lootbox':
return
case 'personalization':
return
}
```
| `kind` | Bought | Show |
| ----------------- | ----------------- | --------------------------------------------- |
| `item` | An inventory item | It, straight away |
| `prize` | A prize | Granted, or processing if it is being shipped |
| `lootbox` | A loot box | The reveal |
| `personalization` | A cosmetic | An offer to equip it now |
The inventory item outcome is `item`, not `inventoryItem`. It matches what a loot box can contain, not the listing type.
For a loot box, the reveal is yours to animate, over `outcome.opening`. For a personalisation, `useEquipPersonalization` equips it in one step. [Rewards and claims](/docs/quests/rewards#loot-boxes) covers both.
After any purchase, the fan's balance, the listings, their purchase history and their inventory all refresh on their own.
## Shopify orders [#shopify-orders]
A prize fulfilled through Shopify comes back with `awaitingFulfilment: true` and a status of `ALLOCATED`. The Shopify order is created just after the purchase, not during it.
| Status | Means | Show |
| -------------- | ----------------------------- | ---------- |
| `ALLOCATED` | Bought, order not created yet | Processing |
| `DISTRIBUTING` | The order is being fulfilled | Processing |
| `DISTRIBUTED` | The fan has it | Delivered |
`ALLOCATED` is not an error. Do not show one.
The SDK does not poll for you. If you want the status to update live on the page, poll the one purchase:
```tsx
import { usePurchase } from '@xborglabs/fanbase-react'
const { data } = usePurchase(purchaseId, { refetchInterval: 5000 })
```
## Purchase history [#purchase-history]
```tsx
import { usePurchases } from '@xborglabs/fanbase-react'
const { data } = usePurchases()
data?.results.map((purchase) => )
```
The list is in `results`, with the count in `total`, so you can page it. Each row carries its delivery status. It covers store purchases only. Rewards from quests are not in here.
## Components [#components]
| Component | Use |
| ------------------- | --------------------------------------------------------------------- |
| `Store.Provider` | Reads listings, balances, tiers and currency names for the storefront |
| `Store.Listing` | One listing, with its gate worked out |
| `Store.Description` | Renders a listing's description, full or plain |
| `Store.Checkout` | Holds the chosen price and the fan's details |
| `Store.Purchase` | The buy button |
`Store.Purchase` takes `asChild` and renders your element. Full props in [Components](/docs/reference/components).
## Checklist [#checklist]
* The buy button is disabled while the gate is locked and while a purchase is in flight
* A member-only listing names the tier it needs
* A listing that needs an address shows the form, and buys once it is filled in
* A `DuplicateNonceError` checks purchase history and never retries with a new nonce
* A card that showed stock still handles `SupplyDepletedError`
* Each of the four outcomes shows its own screen
* A Shopify prize shows processing, not an error
* The balance updates after a purchase without a refresh
# The store model (/docs/store/model)
What the store is made of, and the vocabulary the other two pages use.
## A store [#a-store]
Somewhere fans spend what they earn. Your community team lists items in the admin panel, and you render the storefront in your product, in your design.
If your community runs a spendable currency, give it somewhere to go. Fans notice within about a week whether their balance buys anything.
Listings, prices, stock and the Shopify connection are set up in the Hub. [Store in the Hub docs](https://fanbase-hub-docs.vercel.app/docs/store) covers that side.
## Listings [#listings]
A listing is one thing on sale. Two ids matter, and they are not interchangeable:
| Id | What it identifies | Use it for |
| ------------- | -------------------------- | ---------------------------------- |
| `storeItemId` | The product | React keys, links, "similar items" |
| `listingId` | One price for that product | Buying |
A product can be on sale for more than one price, so it has one `storeItemId` and a `listingId` per price. You always buy a `listingId`.
Prices never change in place. When your community team changes a price, the platform creates a new `listingId`. So never cache a price against a `storeItemId`: the product is the same, the price is not.
## What a fan can buy [#what-a-fan-can-buy]
Every listing is one of four types. The SDK works out which from the listing and gives it to you as `listing.type`.
| `type` | What the fan gets |
| ----------------- | --------------------------------------------------------- |
| `prize` | A physical or digital prize, often shipped |
| `inventoryItem` | An item that lands straight in their inventory |
| `lootbox` | A loot box, with a reveal |
| `personalization` | A cosmetic, like a border or a badge, that they can equip |
The type decides what happens after the purchase, which is why [Buying](/docs/store/buy#after-a-purchase) branches on it.
## Prices and currencies [#prices-and-currencies]
A listing is priced in a spendable resource, and a community can have more than one: Credits, Coins, whatever your team called them. A single product can even be priced in two.
So a price is a number and a unit, never a number alone. Show `12 Credits`, not `12`. The SDK builds that label for you, including for fans who are not signed in, and [Browsing](/docs/store/browse#prices) shows how.
For the same reason, a fan's balance is a list, not a number. Always read the balance of the currency the listing is priced in.
## The purchase gate [#the-purchase-gate]
Before a fan can buy something, four things have to be true. The SDK checks them in this order, before any request, and reports the first one that fails:
| Reason | Means |
| ---------------------- | ---------------------------------------------------------------------------- |
| `MEMBERSHIP_REQUIRED` | The listing is for a membership tier above the fan's |
| `OUT_OF_STOCK` | None left |
| `REQUIREMENTS_MISSING` | The listing needs details the fan has not given yet, like a shipping address |
| `INSUFFICIENT_BALANCE` | They cannot afford it |
You render the reason. You do not work it out. [Buying](/docs/store/buy#the-gate) covers each one.
The gate exists because the platform is unhelpful when a purchase is refused. A fan below the right membership tier gets the same generic error as a fan who typed their email wrong. A reason you can show is always cheaper than a failure you have to decode.
## Premium items are visible to everyone [#premium-items-are-visible-to-everyone]
Listings are public and unfiltered. Every fan sees every item, including the ones only members can buy, and the platform only refuses at the moment of purchase.
That is deliberate. A locked item stays visible so fans can see what membership gets them. The gate tells you which tier unlocks it, by name, so you can say "for Premium members" in the community's own words rather than a vague "locked". [Membership](/docs/membership) covers how the same gate works across the battlepass and the newsfeed.
## Stock [#stock]
Stock is checked twice, and you can only see one of the checks.
The first is `currentSupply` on the listing, which the gate reads. `-1` means unlimited, `0` means sold out.
The second is a community-wide limit, checked at the moment of purchase, for prizes and inventory items. It is not on the listing. So a listing that shows stock can still fail with `SupplyDepletedError`, and your checkout has to handle it even when the card said there were some left.
## Shopify [#shopify]
When your community connects Shopify in the Hub, some prizes are fulfilled as real Shopify orders. The order is created a moment after the purchase succeeds, not during it, so the purchase comes back as `ALLOCATED`.
`ALLOCATED` is expected, not an error. The fan has bought it and the order is on its way. Show "processing". [Buying](/docs/store/buy#shopify-orders) covers how to follow it.