# 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 &&

{failed.length} could not be claimed. Try again.

} {needsAttention.length > 0 && } ) } ``` `Battlepass.ClaimAll` is the same thing as a ready-made button, disabled when claims are closed or when there is nothing it can claim on its own. Tiers claim one after another. If one fails, the rest still go through, and the failure lands in `results` with its error. The pass refreshes once at the end rather than after every tier. ## What claim-all will not claim [#what-claim-all-will-not-claim] Some rewards need the fan in the room, so claim-all leaves them alone and hands them back in `needsAttention`. | `kind` | Why it waits | What the fan has to do | | --------- | -------------------------------------------------------- | ---------------------------------------------------------- | | `prize` | The prize asks for details, a shipping address or a size | Fill in the form, then claim | | `lootbox` | A loot box has a reveal | Watch the reveal, then claim if the item won needs details | Everything else settles on its own: currencies, digital assets, Discord roles, personalisation items, and prizes that ask for nothing. That is a feature. A batch that silently claimed a loot box would skip the reveal, which is the part fans open loot boxes for, and a physical prize claimed with no address cannot ship. Step the fan through each one yourself. [Rewards and claims](/docs/quests/rewards#claims-that-need-details) covers the form, and [Loot boxes](/docs/quests/rewards#loot-boxes) covers the reveal. Both work the same way here as they do for a quest. ## Errors [#errors] Two are specific to the battlepass. Everything else is the ordinary quest claim error and reads the same way it does there. | Error | Means | | ----------------------------------- | ----------------------------------------------------------------- | | `BattlepassSeasonInvalidTierError` | The quest is not a tier of this season | | `BattlepassTierCompleteFailedError` | The completion failed for a reason the platform did not break out | A premium tier completed by a free fan is not on this list, because it does not raise one. See [the silent failure](#the-silent-failure). ## After a claim [#after-a-claim] The pass, your quest list and the fan's inventory all refresh on their own. A tier's rewards are quest rewards, and a tier can grant an item, so the SDK invalidates all three together. You do not need a manual refetch anywhere. ## Checklist [#checklist] * A tier with two rewards ends with both claimed * A premium tier cannot be claimed by a free fan, and the button says why * No button is bound to `isEnabled` * Claim-all survives one failing tier and reports it * A season mixing currency, prize and loot box tiers claims only the currency tiers, and hands the other two back * A loot box tier from `needsAttention` shows its reveal before anything is claimed # The battlepass model (/docs/battlepass/model) What a battlepass is made of, and the vocabulary the other two pages use. ## A battlepass [#a-battlepass] A ladder of rewards that unlocks as a fan levels up. Your community team builds it in the admin panel, and you render it in your product. Quests pay per action. A battlepass pays for the total, so the thirtieth quest is still worth doing when the reward on it is small. That is the whole reason to ship one. Seasons, tiers and the premium track are configured in the Hub. [Battlepass in the Hub docs](https://fanbase-hub-docs.vercel.app/docs/battlepass) covers that side. This page is about rendering what they built. ## Seasons [#seasons] A season is one run of the ladder. It has a title, a description, optional dates and a status. | Status | Means | Claims | | -------- | ------------------ | ------ | | `DRAFT` | Not published yet | Closed | | `ACTIVE` | The current season | Open | | `CLOSED` | Ended by an admin | Closed | There is at most one `ACTIVE` season at a time. Publishing a new one closes the old one. ## Tiers [#tiers] A tier is one rung on the ladder: a level, and what a fan gets for reaching it. Under the hood, every tier is a quest. Its template is `basic.check-level`, and the level lives on `template.args.level`. You will not see these quests in [your quest list](/docs/quests/list), because they are filtered out, but they claim through the same reward allocations every other quest does. That is why most of what you already know from [Rewards and claims](/docs/quests/rewards) carries straight over. ## Levels [#levels] A fan's level on the ladder is their **community XP** level, the same number their profile shows. It is not their membership rank. The two are easy to confuse because a battlepass uses both: XP decides how far up the ladder a fan is, and membership decides which side of it they can claim. ## Lanes [#lanes] A season can have more than one track. There is always a free lane, and there is one paid lane for each membership tier that gates a reward. The SDK turns the tiers into lanes for you: the premium lane on top and the free lane below it. Every lane has one slot per level, so level 5 is always the fifth slot, even in a lane that has nothing at level 5. [Rendering a season](/docs/battlepass/season#lanes-and-tiers) shows why that matters for your layout. ## Membership [#membership] The premium lane is what fans pay for. Whether a given fan can claim a premium tier depends on their membership rank against the rank the tier asks for. The SDK fetches the fan's membership and the community's membership tiers for you, inside the provider. You never fetch them yourself. See [Membership](/docs/membership) for how the same gate works across the store and the newsfeed. ## Four things that do not work the way they look [#four-things-that-do-not-work-the-way-they-look] Worth reading before you build anything. Each of them looks like a bug in your code when you hit it. **A tier is just a quest.** There is no separate battlepass state machine and no battlepass claim endpoint. Completing a tier is the ordinary quest completion with a different URL, and claiming it is the ordinary reward allocation claim. **A premium tier completed by a free fan fails silently.** The platform quietly undoes it and returns success. There is no error to catch. The SDK's gate check is the only signal you get, so you run it before you show a claim button, not after. [Completing and claiming](/docs/battlepass/claims#the-silent-failure) covers it. **`isEnabled` does not mean unlocked.** A tier a fan cannot claim still arrives with `isEnabled: true`. Lock state comes from the membership gate and nowhere else. **Season dates are for display.** Nothing enforces them. A season whose end date has passed stays `ACTIVE`, and keeps paying out, until an admin closes it. Read the status. Never compute "ended" from the dates, and do not render a countdown that implies the season stops on its own. ## No season at all [#no-season-at-all] A community can run a battlepass with no active season. The platform calls this orphan mode: the progress read returns `season: null` and serves the tiers from the container instead. That is a supported state, not an error. Render the ladder as normal, and treat claims as open. # Rendering a season (/docs/battlepass/season) The main build. Every piece of the pass renders inside one provider. ## The shape [#the-shape] ```tsx import { Battlepass } from '@xborglabs/fanbase-react' export function BattlepassPage() { return ( ) } ``` `Battlepass.Provider` reads four things at once so you wire one: the fan's progress through the season, their membership, the community's membership tiers, and their XP level. It derives the lanes from all four and publishes the result to everything inside it. Do not pass a `communityId`. The provider resolves it from the `slug` you already gave [`FanbaseProvider`](/docs/reference/provider). And do not fetch membership tiers yourself anywhere on this page. The provider has them. The pass renders signed out. A fan who is not signed in sees every tier with no personal progress on it, which is a good reason to put the pass somewhere they can find it before they have an account. ## The season header [#the-season-header] Title, level and whether claims are open. `Battlepass.Season` hands you all of it. ```tsx import { Battlepass, Parser } from '@xborglabs/fanbase-react' function SeasonHeader() { return ( {({ season, claimsEnabled, currentLevel, maxLevel }) => (

{season?.title ?? 'Rewards'}

Level {currentLevel} of {maxLevel}

{season?.description ? : null} {!claimsEnabled &&

Claims are closed for this season.

}
)}
) } ``` Three things to get right here: **`season` can be `null`.** That is [orphan mode](/docs/battlepass/model#no-season-at-all), not a missing season. Render the ladder anyway. `claimsEnabled` is `true` in that state. **`currentLevel` is community XP**, not membership rank. For a progress bar, `useBattlepass().state.xp` carries the balance and the next target: ```tsx const { state } = useBattlepass() const progress = state.xp ? state.xp.balance / state.xp.next.target : 0 ``` **The description is structured content**, the same format as a quest description. Render it through `Parser`. Printed as a string it comes out as JSON. [Quest descriptions](/docs/quests/descriptions) explains the format. Do not show a countdown. The dates are not enforced, so a countdown to a season that keeps paying out after zero is a promise the platform does not keep. Show `claimsEnabled` instead. ## Lanes and tiers [#lanes-and-tiers] The part that decides whether the pass looks right. ```tsx function LaneStack() { return ( {({ lane }) => (

{lane.kind === 'free' ? 'Free' : lane.name}

{({ slot, level, gate, canClaim }) => (
{!slot ? null : (

{slot.tier.title}

{slot.state === 'PREMIUM_LOCKED' && (

Needs {gate?.reason?.requiredTierName}

)} {canClaim && ( )}
)}
)}
)}
) } ``` `Battlepass.Lane` renders every lane in order: the premium lane on top, the free lane below it. Pass `laneId` to render just one, for example as tabs on a phone. `Battlepass.Tier` walks the lane one level at a time. **It includes the gaps.** A lane with nothing at level 4 still gets a cell at level 4, with `slot` set to `null`. That is deliberate: `slots[i]` is always level `i + 1`, in every lane, so a CSS grid keyed on level keeps the free lane and the premium lane lined up. Render the empty cell. If you skip it, every tier after the gap slides one column left and the lanes stop matching. Both parts accept a render function or plain children. If you would rather build a card as its own component than thread props into it, read the same values from `useBattlepassLane()` and `useBattlepassTier()` inside it. ## Tier states [#tier-states] Each slot carries a `state`. Render it, do not recompute it. | `state` | Means | What to render | | ---------------- | ----------------------------------------------------- | -------------------------------------------------------------------------------- | | `PREMIUM_LOCKED` | The fan's membership is below what this tier asks for | Lock badge, the tier name from `gate.reason.requiredTierName`, an upgrade prompt | | `CLAIMED` | Already taken | A taken state, no button | | `CLAIMABLE` | Level reached and not claimed | The claim button | | `FUTURE` | Level not reached yet | A dimmed card, nothing to press | A tier the fan has reached but cannot claim for a reason the SDK does not recognise also reads as `FUTURE`. Inert is the safe way to render "we are not sure you can have this". The premium upsell is yours. The gate tells you which membership tier unlocks the reward, by name and rank. What the upgrade costs and where it goes is your product's call. Milestone tiers, the ones your community team flagged as featured, carry `slot.isMilestone`. Use it for a taller card or a different treatment. ## Switching seasons [#switching-seasons] Optional. Past seasons are worth showing when a community runs them back to back. ```tsx import { Battlepass, useBattlepassProgress, useBattlepassSeasons } from '@xborglabs/fanbase-react' function SeasonSwitcher() { const [selectedId, setSelectedId] = useState() const { data: progress } = useBattlepassProgress() const { data: seasons = [] } = useBattlepassSeasons() const liveId = progress?.season?.seasonId const switchable = seasons.filter((season) => season.status !== 'CLOSED') return ( ) } ``` Leave `CLOSED` seasons out of the control. For the live season, pass `undefined`, not its id. That keeps the provider on the live progress read, which is the only one that works in orphan mode. Passing the live season's own id sends it down the single-season read instead, and a community with no active season then renders nothing. ## Components [#components] | Component | Use | | --------------------- | ------------------------------------------------------ | | `Battlepass.Provider` | Reads the season, membership and XP, derives the lanes | | `Battlepass.Season` | Season header: title, level, whether claims are open | | `Battlepass.Lane` | Every lane in order, or one by `laneId` | | `Battlepass.Tier` | One cell per level in a lane, gaps included | | `Battlepass.Claim` | Claim button for one tier | | `Battlepass.ClaimAll` | Claim button for everything that can settle on its own | `Claim` and `ClaimAll` take `asChild` and render your element. Full props in [Components](/docs/reference/components). ## Checklist [#checklist] * The pass renders with no `communityId` and no membership fetch of your own * `season: null` renders the ladder, not an empty state * The season description goes through `Parser` * No code compares the end date to today, and there is no countdown * The premium lane renders above the free lane * A lane with a gap renders an empty cell there, and the lanes stay aligned * A premium tier shows as locked for a free fan, with the required tier's name # Environment (/docs/getting-started/environment) Eight values. Your FanBase contact provides all of them for your community. The examples below use Vite's `VITE_` prefix; rename for Next.js (`NEXT_PUBLIC_`) or your own framework. ## The values [#the-values] | Variable | What it is | | --------------------------------- | ---------------------------------------------------------------------------------------- | | `VITE_FANBASE_TENANT` | Your tenant host. Sent as the `xb-tenant` header on every API request. | | `VITE_FANBASE_COMMUNITY_SLUG` | Your community's slug. Community identifier only, never an auth path or a provider name. | | `VITE_FANBASE_APP_ID` | Identifies this specific app or environment within your community. | | `VITE_FANBASE_GAMER_BASE_URL` | API base URL. Beta and production differ. | | `VITE_FANBASE_LOCALE` | Display language. Defaults to `en`. | | `VITE_FANBASE_OAUTH_PROXY_URL` | The OAuth proxy that handles the provider handshake. | | `VITE_FANBASE_OAUTH_PROXY_SECRET` | Routing key for your community on the proxy. See the note below. | | `VITE_FANBASE_OAUTH_REDIRECT_URL` | Absolute URL of your callback page. Has to be registered with the proxy. | ## Beta defaults [#beta-defaults] Working values against beta, for a local Vite app on port 5173: ```dotenv VITE_FANBASE_TENANT=xbg-beta.apps.gamerbase.gg VITE_FANBASE_COMMUNITY_SLUG=xbg VITE_FANBASE_APP_ID=local_5173_beta VITE_FANBASE_GAMER_BASE_URL=https://api-beta.gamerbase.gg VITE_FANBASE_LOCALE=en # OAuth proxy VITE_FANBASE_OAUTH_PROXY_URL=https://oauth-beta.gamerbase.gg/ VITE_FANBASE_OAUTH_PROXY_SECRET=local_5173_beta VITE_FANBASE_OAUTH_REDIRECT_URL=http://localhost:5173/auth/callback ``` Paste that and the app runs. Swap in your own values when you move off the shared beta community. ## The tenant header [#the-tenant-header] `VITE_FANBASE_TENANT` becomes the `xb-tenant` header, and it goes out on every request the SDK makes. It scopes the data you get back. Your tenant's quests, your tenant's rewards. Getting it right matters more than it looks: | Header value | What happens | | -------------------------------------- | -------------------------------------------- | | Your correct tenant | Your community's data | | A wrong value, including a placeholder | `400 generic_client_error` on every endpoint | | Header absent entirely | `200` with a different, unscoped dataset | Header absent returns a 200 with someone else's data. Nothing errors and the app renders, so if your quest list looks plausible but does not match your admin panel, check this first. That last row is the one to watch. Nothing errors, the app renders, and the content belongs to someone else. If your quest list looks plausible but does not match your admin panel, check this header first. ## The trailing slash on the proxy URL [#the-trailing-slash-on-the-proxy-url] `VITE_FANBASE_OAUTH_PROXY_URL` is resolved as a URL base, so a trailing slash changes the result when the proxy is mounted on a path: | Value | Resolves to | | ------------------------------------ | ------------------------------------------ | | `https://oauth.example.com/` | `https://oauth.example.com/SECRET` | | `https://oauth.example.com/fanbase/` | `https://oauth.example.com/fanbase/SECRET` | | `https://oauth.example.com/fanbase` | `https://oauth.example.com/SECRET` | Include the trailing slash. If you are on a root-mounted proxy it makes no difference, and if you are ever moved to a path-mounted one it saves an afternoon. ## About the proxy secret [#about-the-proxy-secret] Despite the name, this is a routing key, not a credential. It is the path segment that tells the proxy which configuration a sign-in belongs to: which providers are enabled, and which callback URL is allowed. It compiles into your public bundle and shows up in the sign-in URL. That is expected. A production build of your app contains it. Your security reviewer will stop here, so what it cannot do: * It does not authorise a request, carry an identity, or read anything. It selects a configuration. * The callback URL lives on our side. The proxy only returns a fan to a URL registered against that configuration, so the key on its own cannot send a sign-in anywhere else. * Rotating it is a support request, not an incident. Authority sits in the token instead. The proxy returns an encrypted token, your app exchanges it for a session, and after that it is a JWT in your session adapter sent as a Bearer header. None of that goes in a URL. One scoping caveat. This key is configured per proxy entry, not per community, and one entry can cover several surfaces in the same organisation. If you run several communities that need isolating at sign-in, check the arrangement with your FanBase contact. ## Registering your redirect [#registering-your-redirect] `VITE_FANBASE_OAUTH_REDIRECT_URL` has to be registered with the proxy before sign-in works. Send us every URL you need, including local development ports and preview deployments. An unregistered redirect fails at the provider handshake. # Installation (/docs/getting-started/installation) ## Before you start [#before-you-start] Two things have to be in place, and only one of them is on your side. **From us:** a community provisioned on the FanBase platform, and the environment values for it. Your contact at FanBase sends these. They are listed in [Environment](/docs/getting-started/environment). **From you:** a GitHub Personal Access Token with the `read:packages` scope on the `@xborglabs` organisation. The packages are published to GitHub Packages, not the public npm registry, so a plain `npm install` cannot see them until this is configured. ## Requirements [#requirements] | | | | ----------------------- | --------------------------- | | React | 19 | | react-dom | matching your React version | | `@tanstack/react-query` | ^5 | | Package manager | npm, pnpm, yarn or bun | React 19 is a hard requirement. The React bindings use the `use()` hook, which does not exist in React 18, and an app on 18 fails at module load rather than at runtime. `@tanstack/react-query` is a peer dependency and you own the `QueryClient`. The SDK does not install its own. ## Point npm at GitHub Packages [#point-npm-at-github-packages] Add to `.npmrc` in your project root: ``` @xborglabs:registry=https://npm.pkg.github.com //npm.pkg.github.com/:_authToken=${GITHUB_TOKEN} ``` Then export the token in your shell or CI environment: ```bash export GITHUB_TOKEN=ghp_your_token_here ``` Keep the token out of the file itself. The `${GITHUB_TOKEN}` reference above is expanded by npm at install time. ## Install [#install] Ask for the `alpha` tag by name: ```bash npm install @xborglabs/fanbase-core@alpha @xborglabs/fanbase-react@alpha ``` Both packages are released together and the tag moves to the current release of each, so this resolves them as a matching pair. ## Which tag [#which-tag] Three tags exist, and they do not carry the same features. | Tag | Has every feature in these docs | | -------- | ---------------------------------------------------------------------------------------------------- | | `alpha` | Yes | | `beta` | Yes | | `latest` | No. It trails the other two, and at the time of writing is missing the leaderboard and the newsfeed. | A bare `npm install`, with no tag, installs `latest`. That works, but it is the oldest of the three: the leaderboard and newsfeed hooks are not in it, and an agent following these docs will reach for them and not find them. So name the tag. `alpha` and `beta` carry the same features and ship on the same day. Ask your FanBase contact which one your community is provisioned against. If `npm install` fails with `ETARGET`, your token is fine. It means the tag you asked for does not exist, usually a typo in it. ## Verify [#verify] ```bash node -e "console.log(require('@xborglabs/fanbase-react/package.json').version)" ``` If that prints a version, the registry and token are working. If it fails to resolve, the `.npmrc` scope line is the usual cause. ## Typecheck note for Vite apps [#typecheck-note-for-vite-apps] The stock Vite React template ships a root `tsconfig.json` that only contains project references. Running `tsc --noEmit` against it checks nothing and exits 0, which reads as a clean typecheck when it is not one. Point at the app config instead: ```bash npx tsc -p tsconfig.app.json --noEmit ``` Worth putting in your `package.json` scripts so nobody has to remember it. ## Next [#next] [Environment](/docs/getting-started/environment), then [Quickstart](/docs/getting-started/quickstart). # What you get (/docs/getting-started/overview) ## The short version [#the-short-version] You keep your website. We provide the fan account system and the engagement mechanics behind it. A fan signs in on your site, does things you have set up, earns things you have configured. None of it looks like FanBase unless you want it to. ## The pieces [#the-pieces] **Fan accounts.** Sign-in with Discord, Google, X or Twitch. The fan gets one identity across everything you build. You do not store passwords and you do not build an auth system. **Quests.** A quest is any action you want to reward. Follow an account, answer a question, predict a scoreline, submit a photo, visit a page, spend on your store. You create and edit these in the FanBase admin panel, no deploy needed, and they appear in your app through the SDK. **Rewards.** Points, prizes, personalisation items, loot boxes. The claim flow, including the loot box reveal, runs through the SDK. **Your design.** The components take your markup and add behaviour. There is no FanBase stylesheet to override and no iframe. ## What running it looks like [#what-running-it-looks-like] Setup is a developer job once, then a marketing job forever. Someone technical spends an afternoon wiring it in. After that your community team creates quests in the admin panel and they go live without engineering. ## What it is not [#what-it-is-not] Not a hosted community site. If you want a full fan app rather than features inside your own site, that is the FanBase Fan Hub, a different product. Not a loyalty plugin with a fixed UI. There is more work up front than installing a Shopify app, and correspondingly no ceiling on how it looks. Not everything yet. Quests and sign-in are live. Battlepass, predictions, store, newsfeed and leaderboard are not in the package. See [feature status](/docs/status). ## Typical first build [#typical-first-build] A quest page on an existing marketing site. Sign-in, a list of live quests, a detail view, claim. Roughly a day of developer time, or under an hour with a coding agent doing the wiring. # Quickstart (/docs/getting-started/quickstart) Assumes [installation](/docs/getting-started/installation) is done and you have your [environment values](/docs/getting-started/environment). Doing this with a coding agent instead? [Agent setup](/docs/agents) has the prompts. This page is the same path by hand. ## 1. Wrap your app [#1-wrap-your-app] `FanbaseProvider` holds configuration, the session, and the API client. It goes above anything that touches FanBase. ```tsx import { FanbaseProvider } from '@xborglabs/fanbase-react' import { QueryClient } from '@tanstack/react-query' const queryClient = new QueryClient() const session = { get: () => JSON.parse(localStorage.getItem('fanbase.session') ?? 'null'), set: (s) => localStorage.setItem('fanbase.session', JSON.stringify(s)), clear: () => localStorage.removeItem('fanbase.session'), } export function App() { return ( ) } ``` Two things worth knowing before you go further. The session adapter is any object with `get`, `set` and `clear`. `localStorage` is fine to start. Swap in cookies or your own store later without touching anything else. `FanbaseProvider` mounts its own `QueryClientProvider` around your children, using the client you passed. Your own `useQuery` calls need to sit inside it, which they will if `FanbaseProvider` is near the root. ## 2. Sign in [#2-sign-in] Two helpers build the URL, then you navigate to it. ```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, }) function signIn(provider) { sessionStorage.setItem('fanbase.provider', provider) const redirectUrl = new URL(import.meta.env.VITE_FANBASE_OAUTH_REDIRECT_URL) redirectUrl.searchParams.set('provider', provider) window.location.href = buildLoginUrl({ oauthProxyUrl: proxyUrl, provider, redirectUrl: redirectUrl.toString(), }) } ``` `provider` is one of `google`, `discord`, `twitter`, `twitch`. It is the identity provider and nothing else. Passing a tenant or a community slug here is the most common first mistake. The proxy returns to your callback with `?token=` and nothing else, so stash the provider before you leave. Both the query param and `sessionStorage` above do that, either alone is enough. ## 3. Handle the callback [#3-handle-the-callback] This page has to live at exactly the URL registered as your redirect. ```tsx import { useEffect } from 'react' import { useFanbase, parseOAuthCallbackToken } from '@xborglabs/fanbase-react' export function AuthCallback() { const { state, actions } = useFanbase() useEffect(() => { if (!state.ready) return const token = parseOAuthCallbackToken(window.location.href) if (!token) return const provider = new URLSearchParams(window.location.search).get('provider') ?? sessionStorage.getItem('fanbase.provider') actions.loginWithToken({ provider, token }) }, [state.ready]) return

Signing you in…

} ``` Wait for `state.ready`. The provider restores any existing session on mount, and exchanging a token before that finishes puts you in an inconsistent state. The provider you pass to `loginWithToken` has to match the one you passed to `buildLoginUrl`. A mismatch fails the exchange. You are signed in when `state.session` has both `accessToken` and `refreshToken`. From there the SDK sends the access token as a Bearer header on every request. No cookies involved. `actions.logout()` clears the adapter and the in-memory session. ## 4. List quests [#4-list-quests] ```tsx import { useQuestsList } from '@xborglabs/fanbase-react' export function QuestList() { const { data: quests, isLoading } = useQuestsList() if (isLoading) return return (
    {quests.map((quest) => (
  • open(quest)} />
  • ))}
) } ``` One call, one request. Do not fetch per-quest detail or reward allocations for cards. Everything a card needs is on the row you already have, and fanning out turns one request into dozens. Quests appear here as soon as someone publishes them in the admin panel. No deploy. Two things on rendering: quest status comes back as a raw enum like `INACTIVE`, which does not mean what it looks like, and quest descriptions are structured content rather than plain strings. [Display strings](/docs/design/display-strings) and [Quest descriptions](/docs/quests/descriptions) cover both. They are quick reads and skipping them is the usual cause of a first build looking rough. ## 5. Quest detail and claim [#5-quest-detail-and-claim] That is the substantial part, and it has its own pages: [Quest detail](/docs/quests/detail) and [Rewards and claims](/docs/quests/rewards). ## Check it worked [#check-it-worked] * Quest list renders and matches your admin panel * Sign-in returns to your callback and `state.session` has both tokens * `actions.logout()` clears it * Refresh keeps you signed in * Network tab shows one `GET /v1/quests` on the list page, not one per card # How it fits together (/docs/how-it-works/architecture) The model, before any code. Fifteen minutes here saves a lot of guessing later. ## Three layers [#three-layers] **The FanBase platform.** Our API and admin panel. Holds your community, your quests, your fans and their progress. Your community team works here. **`@xborglabs/fanbase-core`.** A framework-free client. Talks to the platform, holds the quest state machine, the template registry, reward resolution and the display string catalog. No React, no DOM. **`@xborglabs/fanbase-react`.** React bindings on top of core. A provider, hooks, and slot-based components that render your markup rather than theirs. Your app sits above all three and owns every pixel. ## Why the split [#why-the-split] Core is where the rules live. Whether a fan can submit a quest right now, what the button should say, which reward image to show. Those rules are identical whatever framework you use, so they sit in a package with no framework in it. That is also why a Vue or Svelte binding is possible later without rewriting the logic. Only React exists today. ## The state machine [#the-state-machine] The single most useful thing to understand. Whether a quest can be acted on depends on a pile of conditions: is the fan signed in, have they linked the right social account, have they already completed it, is it inside its date window, did they open the link. Getting that wrong means fans hitting buttons that fail. You do not evaluate any of it. Core runs a state machine over the quest and everything you have told it about the fan, and gives you back a decision: | Field | What it is | | --------------------------- | -------------------------------------------- | | `state.canSubmit` | Whether the fan can act right now | | `state.canClaim` | Whether there is a reward waiting | | `state.buttonLabel` | The right label for the current state | | `state.disabledReasonLabel` | Why the fan cannot act, in readable language | Change the fan's condition and watch what the machine reports: Render those four fields. Do not reimplement the logic, and do not bypass the machine with your own enabled check. When new quest types ship, apps that trusted the machine keep working. The machine is only as good as what you feed it. If you do not pass the fan's linked socials, it has to assume nothing is linked, and quests that need a linked account stay disabled. [Quest detail](/docs/quests/detail) covers what to pass. ## Unstyled by design [#unstyled-by-design] The components use a slot pattern. You pass your own element, the component attaches behaviour to it. ```tsx ``` Your class names come through untouched. Nothing is added. There is no FanBase stylesheet in your bundle and no iframe. The one place we do give you content is descriptions, which are structured rather than plain text, and there you pass a theme object mapping node types to your classes. See [Quest descriptions](/docs/quests/descriptions). ## Requests [#requests] Every request carries two things: the `xb-tenant` header, which scopes data to your community, and once signed in, a Bearer access token. No cookies, so no third-party cookie problem and no CORS credential dance. The SDK is built around few requests. The quest list is one call for the whole list. Detail is one call per quest, when a fan opens it. If you find yourself fetching per card, something is wired wrong. ## Where content comes from [#where-content-comes-from] Quests are created and edited in the FanBase admin panel by whoever runs your community. They appear in your app through the API, so a new quest is a publish, not a deploy. This shapes how you build. You are not writing a component per quest. You write one detail view that handles every quest type, driven by the quest's template. [Quest templates](/docs/quests/templates) is the map of what can arrive. # Tenant, community and app (/docs/how-it-works/tenancy) ## Tenant [#tenant] Your organisation on the FanBase platform. Set as `tenant` on the provider, sent as the `xb-tenant` header on every request, and what scopes all data to you. Wrong value, everything 400s. Missing entirely, you get a different dataset with a 200. [Environment](/docs/getting-started/environment#the-tenant-header) has the detail. ## Community [#community] A space inside your tenant, identified by a slug. Quests, fans and rewards belong to a community. Most partners have one and can treat it as fixed. A tenant running several, say a club with separate spaces per team, has one slug per space. The slug is an identifier. It is not a URL path, not a provider name, and not part of the sign-in flow. Passing a community slug where a provider is expected is a common early error. ## App [#app] An identifier for a specific surface or environment within a community, set as `appId`. Your local development app, your staging deploy and your production site are usually three different `appId` values against the same community. ## Fans [#fans] A fan is one identity across everything in your community. Sign in with Discord on your main site and with Google on a campaign microsite, same fan, one progress record, if both are the same community. ## Which one goes where [#which-one-goes-where] | Setting | Value | | --------------------- | ----------------------------------------------- | | `tenant` prop | Your tenant host | | `slug` prop | Your community slug | | `appId` prop | This app or environment | | `provider` in sign-in | `google`, `discord`, `twitter` or `twitch` only | The last row is the one that trips people up. `provider` is the identity provider. Nothing about your organisation goes in it. # Display strings (/docs/design/display-strings) Short page, and skipping it is the most common reason a first integration looks unfinished. Two minutes. Skipping this is the most common reason a first integration looks unfinished. ## The problem [#the-problem] The API returns enums. `INACTIVE`, `ACTIVE`, `RESOLVING`, `ALLOCATED`. Render one of those in a badge and a fan reads `INACTIVE` as “this quest is switched off”, when what it means is "you have not started this yet". Raw enums are not just untranslated. Some of them are actively misleading. ## The catalog [#the-catalog] The SDK ships 597 English display strings: 584 for every quest enum the API can return, and 13 for the leaderboard. ```tsx import { resolveMessage } from '@xborglabs/fanbase-react' const label = resolveMessage(`Quests.status.${quest.status}`) ``` ## Signature [#signature] ```ts resolveMessage( key: string, i18n?: { t: (key: string, values?: object) => string }, values?: object ): string ``` The second argument is an i18n adapter, not a fallback catalog. The English catalog is already the automatic fallback, so passing it explicitly is both unnecessary and wrong. Values for interpolation go in the third argument. ## Key namespaces [#key-namespaces] | Namespace | Covers | | ----------------------- | -------------------------------------------------------------------------------------------------------- | | `Quests.status.*` | Fan-facing quest progress | | `Quests.prizeStatus.*` | Prize and claim states | | `Quests.gamingStatus.*` | Game-linked quest states | | `Leaderboard.*` | Column headings, the pager, the empty and unranked states. [Rendering a board](/docs/leaderboard/board). | The battlepass, the store and the newsfeed ship no strings. Their copy is yours: the SDK hands you reason codes and tier names, and you write the sentences. Some real ones: ``` Quests.status.INACTIVE → “Not Started” Quests.status.ACTIVE → "In Progress" Quests.status.RESOLVING → "In Review" Quests.prizeStatus.ALLOCATED → "Processing" ``` `INACTIVE` to "Not Started" is the whole point of this page. ## In practice [#in-practice] ```tsx function QuestStatusBadge({ quest }) { return ( {resolveMessage(`Quests.status.${quest.status}`)} ) } ``` Anywhere you were about to render `{quest.status}`, render this instead. ## Your own wording [#your-own-wording] If your community says something different, wrap it: ```tsx const OVERRIDES = { 'Quests.status.RESOLVING': 'Being checked', } const label = (key) => OVERRIDES[key] ?? resolveMessage(key) ``` ## Other languages [#other-languages] Pass your i18n instance as the adapter and your translations win, with the English catalog behind them for any key you have not covered: ```tsx resolveMessage('Quests.status.ACTIVE', { t: i18n.t }) ``` Set `locale` in `httpOptions` too, so API-side content comes back in the same language. ## Where the SDK already does this for you [#where-the-sdk-already-does-this-for-you] `state.buttonLabel` and `state.disabledReasonLabel` are already resolved. Render them directly. This page is about the raw fields you pull off the quest yourself. # Your design system (/docs/design/theming) The SDK ships no CSS. Nothing to override, nothing to reset, no specificity fight. ## How components render your markup [#how-components-render-your-markup] Every component takes `asChild` and attaches its behaviour to the element you pass: ```tsx ``` Your class names, your element, your props. The component adds the click handler and the disabled state. Nothing else. Works with Tailwind, CSS modules, styled-components, vanilla CSS, or your own component library: ```tsx } /> ``` Here is that pattern doing its job. One quest, one machine, three partner design systems, no FanBase CSS anywhere in them: ## What you own [#what-you-own] All of it. Layout, cards, spacing, typography, the loading and empty states, the loot box animation. ## What you should take from the SDK [#what-you-should-take-from-the-sdk] Two things, because getting them wrong is worse than writing them yourself. **Labels and reasons.** `state.buttonLabel` and `state.disabledReasonLabel` are already correct for the current state and already localised. Writing your own means maintaining a state matrix that the SDK already maintains. **Status text.** Through the catalog. [Display strings](/docs/design/display-strings). ## Descriptions [#descriptions] The one place with structured content coming in, and you map node types to your classes with a theme object. [Quest descriptions](/docs/quests/descriptions). ## Dark mode [#dark-mode] Nothing to configure. Your classes, your CSS variables, your media queries. ## Reward images [#reward-images] `resolveQuestRewardChrome` returns a presentation object with an image. Style the container, size the image, do what you like around it. ## A note on the disabled prop [#a-note-on-the-disabled-prop] Set disabled on your own element rather than on the slot component, and drive it from `state.canSubmit`: ```tsx ``` ## Practical suggestions [#practical-suggestions] Give quest cards a fixed height. Titles and descriptions vary a lot, and a grid that reflows per row looks broken. Build a real empty state. Communities run campaigns in bursts, so there are periods with no live quests and fans will see it. Skeletons over spinners for the list. You know the card shape ahead of time. Show the reward before the action. It is the reason a fan starts. # Personalisation (/docs/inventory/personalization) The cosmetics a fan collects, and the picker where they show them off. ## Personalisations [#personalisations] A personalisation is a cosmetic a fan can equip. Three kinds exist, and a fan wears one of each at a time: | `kind` | What it is | | ------------ | ------------------------- | | `pfp` | Profile picture | | `border` | A frame around the avatar | | `background` | A profile backdrop | Fans get them as quest rewards, from loot boxes, from the battlepass and from the store. Owning one does not equip it. That is the fan's choice, in your picker. ## Per community [#per-community] Equipping is per community. A fan's animated border in one community is not their border in another, and choosing one here never changes what they wear there. Every read and write on this page is scoped to your community. ## What a fan owns [#what-a-fan-owns] ```tsx import { useEquippedPersonalization, usePersonalizations } from '@xborglabs/fanbase-react' const { data: owned } = usePersonalizations({ ownedOnly: true, kind: 'pfp' }) const { data: equipped } = useEquippedPersonalization() ``` `usePersonalizations` lists them, filtered by kind. Each row carries `isOwned`, `isEquipped` and its art in `mediaPath`. Leave `ownedOnly` off to show the locked ones as well, which is a good way to show fans what is left to earn. `useEquippedPersonalization` is what the fan is wearing now: `equipped.pfp`, `equipped.border` and `equipped.background`, each with a `mediaUrl`. Use it anywhere you draw their avatar. Both resolve your community from the `slug` on [`FanbaseProvider`](/docs/reference/provider). ## The picker [#the-picker] Let the fan try things on, then save once. Hold their choices in your own state as a draft, and send the whole draft together: ```tsx import { useBatchEquipPersonalizations, useResolvedCommunityId } from '@xborglabs/fanbase-react' function SaveButton({ draft }) { const containerId = useResolvedCommunityId() const { batchEquip, isPending } = useBatchEquipPersonalizations() return ( ) } ``` The batch is all or nothing, so a fan never ends up half changed. The equipped set refreshes on its own afterwards. Writes need the community id, which `useResolvedCommunityId` gives you. Keep the button disabled until it is there. ## Taking one off [#taking-one-off] A `personalizationId` of `null` takes that kind off: ```tsx batchEquip({ containerId, items: [{ kind: 'border', personalizationId: null }] }) ``` There is no "remove everything" call. To clear all three, send all three as `null`. For a single change with no draft, like an "Equip" button on a reward the fan just won, `useEquipPersonalization` and `useUnequipPersonalization` do one kind at a time. ## After a purchase or a reward [#after-a-purchase-or-a-reward] A personalisation bought in the store comes back as its own outcome, with the item's id, which is the moment to offer "Equip now". [After a purchase](/docs/store/buy#after-a-purchase). The same goes for a personalisation won from a quest. It is in their inventory the moment the claim goes through. ## Checklist [#checklist] * The picker lists what the fan owns, by kind * Locked personalisations show what is left to earn, if you want that * Saving sends one batch, not one call per kind * Setting a kind to `null` takes it off * The avatar everywhere reads from `useEquippedPersonalization` * Choices in one community never show up in another # Prizes and details (/docs/inventory/prizes) What a fan owns, and the form that stands between them and a physical prize. Quests, the battlepass, loot boxes and the store all hand out prizes, and they all use what is on this page. ## Prizes [#prizes] A prize is anything your community team gives away: a signed shirt, a code, a meet and greet. Read the prizes in the community: ```tsx import { usePrizes } from '@xborglabs/fanbase-react' const { data } = usePrizes({ ownedOnly: true, page: 1, limit: 24 }) data?.results.map((prize) => (

{prize.name}

)) ``` `ownedOnly: true` narrows it to what this fan has. Leave it off for a showcase of everything on offer. Only published prizes ever come back. One prize, with the details it asks for, is `usePrize(prizeId)`. Two things that are not there: an owned prize has no expiry, and there is no "prize history" read in the SDK. Store purchases have their own history. [Purchase history](/docs/store/buy#purchase-history). ## The details form [#the-details-form] Some prizes cannot be sent without something from the fan: an email for a code, an address for merchandise, a wallet address for an on-chain item. Those are the prize's requirements, and the SDK turns them into form fields: ```tsx import { getRequirementFields, isSubmissionRequired } from '@xborglabs/fanbase-react' const fields = prize.requirements ?.filter(isSubmissionRequired) .flatMap(getRequirementFields) .filter((field) => !field.hidden) fields?.map((field) => ( )) ``` A prize can carry five kinds of requirement, and only three ask the fan for anything: | Requirement | Fields | | ----------------- | ----------------------------------------------------------------------------------------- | | `email` | One email field | | `address` | Seven: three address lines, city, state, country, postal code. Make `country` a dropdown. | | `wallet_address` | One field, named `walletAddress` | | `membership_tier` | None. Checked by the platform. See [Membership](/docs/membership). | | `level_check` | None. Checked by the platform. | `isSubmissionRequired` drops the last two, so your form never renders an empty step for them. Each field carries its own `label`, `required` and `hidden`, from how your community team set the prize up. Build validation from `required`. Never render a `hidden` field. The form is yours. One screen or one step per requirement are both fine. The SDK ships the fields, not a wizard. ## Sending the details [#sending-the-details] Worth reading twice. The same three answers go to three different endpoints, in three different shapes, depending on how the fan got the prize. Collect them once, then use the builder for the call you are making: ```tsx import { toAllocationClaimPayload, toPurchaseRequirementData, toSubmissionData } from '@xborglabs/fanbase-react' const values = { email: { requirementId: emailRequirement.requirementId, data: 'fan@example.com' }, } toAllocationClaimPayload(values) // a prize from a quest toSubmissionData(values) // a prize won in a loot box toPurchaseRequirementData(values) // a prize bought in the store ``` | The fan got it from | Builder | Where it goes | | ------------------- | --------------------------- | -------------------------------------------------------------------------------------------------------------- | | A quest reward | `toAllocationClaimPayload` | `claimPayload` on `Quest.Provider`. [Claims that need details](/docs/quests/rewards#claims-that-need-details). | | A loot box | `toSubmissionData` | `claimLootbox`. [When the item needs details](/docs/quests/rewards#when-the-item-needs-details). | | The store | `toPurchaseRequirementData` | `requirementData` on `Store.Checkout`. [Details a purchase needs](/docs/store/buy#details-a-purchase-needs). | Never build one by hand. They differ in ways that are easy to miss and hard to debug: the wallet requirement is called `wallet_address`, but its field is `walletAddress`, and the recipient name inside an address is kept by the store builder and dropped by the other two. Details are saved to the fan's profile by default, so they do not type their address twice. That is what `shouldSave` controls, and it defaults to `true`. It does not mean "save this form". It means "remember this for every future prize that asks". ## Claim states [#claim-states] A prize won in a loot box sometimes needs a second claim, to send those details. Only sometimes. Work out which before you offer it: ```tsx import { resolvePrizeClaimState } from '@xborglabs/fanbase-react' const { state } = resolvePrizeClaimState({ opening, prize }) ``` | State | Means | Show | | ----------------------- | --------------------------------------------- | ----------------------------------- | | `REQUIREMENTS_REQUIRED` | The prize needs details before it can be sent | The form and a claim button | | `AWAITING_FULFILMENT` | Details sent, a person is fulfilling it | "Being processed". No retry button. | | `ALREADY_DISTRIBUTED` | The fan has it | Delivered | | `NOT_OWNED` | The fan does not own this | Locked | Only `REQUIREMENTS_REQUIRED` allows a claim. `claimLootbox` checks the state itself and refuses, without sending anything, in every other one. `AWAITING_FULFILMENT` waits on a person. Nothing on the platform moves it to delivered on its own, which is exactly why there should be no retry button. A retry cannot speed up someone packing a box. ## Errors [#errors] The platform is not much help here. Asking to claim something already claimed, or something that does not exist, or something the fan does not own, all come back as the same generic server error. You cannot tell them apart. So do not try. Keep the failure message generic, and rely on `resolvePrizeClaimState` to keep the claim from being sent in those cases at all. | Error | Means | | --------------------------------- | ------------------------------------------------------------------------------------------------ | | `PrizeRequirementValidationError` | A detail was rejected. The one error that says which field. | | `PrizeClaimNotAllowedError` | Your code tried to claim outside `REQUIREMENTS_REQUIRED`. The SDK stopped it before it was sent. | | `LootboxBatchTooLargeError` | More than 100 loot boxes asked for in one read | One case worth special-casing: API code `10010` means the email is already used by another account. ## Checklist [#checklist] * The prize list shows art from `mediaPath` * The form is built from `getRequirementFields`, with no step for membership or level * Hidden fields are never shown * Each call uses the builder named for it, and nothing is built by hand * A loot box prize offers a claim only in `REQUIREMENTS_REQUIRED` * A prize awaiting fulfilment says so, with no retry * Failures show a generic message rather than guessing at a cause # Rendering a board (/docs/leaderboard/board) One provider, one table and one row you pin. Short, because the board is read-only. ## The shape [#the-shape] ```tsx import { LEADERBOARD_KIND, Leaderboard } from '@xborglabs/fanbase-react' export function LeaderboardPage() { return ( ) } ``` `Leaderboard.Provider` reads one page of the board and, for a signed-in fan, their own position, and publishes both through `useLeaderboard()`. Do not pass a `communityId`. The provider resolves it from the `slug` on [`FanbaseProvider`](/docs/reference/provider). The board is public. It works for a fan who is not signed in, which makes it a good page to link from somewhere they can find it before they have an account. ## The table [#the-table] ```tsx import { isLeaderboardViewerRow, resolveMessage, useLeaderboard } from '@xborglabs/fanbase-react' function Board() { const { state } = useLeaderboard() if (state.isLoading) return if (state.listReason === 'SLUG_UNRESOLVED') return

This board is not available.

if (state.listReason === 'EMPTY') return

{resolveMessage('Leaderboard.empty')}

return ( {state.users.map((row) => ( ))}
{resolveMessage('Leaderboard.rank')} {resolveMessage('Leaderboard.username')} {state.resourceType?.name ?? resolveMessage('Leaderboard.score')}
{row.rank ?? '·'} {row.equippedPersonalization?.pfp ? ( ) : null} {row.user.displayName ?? row.user.handle} {row.balance}
) } ``` 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

{resolveMessage('Leaderboard.unranked')}

} const { leaderboardRank, balance, current } = state.viewerRank return (

{resolveMessage('Leaderboard.myRank')}

#{leaderboardRank} · {balance} {current?.level != null && ` · ${resolveMessage('Leaderboard.Level')} ${current.level}`}

) } ``` | `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 (
{post.reactions.map((reaction) => ( ))} {unused.length > 0 && }
) } ``` 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 (
{node.children.map((child) => ( ))} {node.comment.hasMoreReplies && }
) } ``` 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 (
{ e.preventDefault(); submit() }}>