Backend

Client and hooks

Reference of pleate-client: every module of createPleateClient and every React hook with what it returns.

pleate-client has two entry points. pleate-client is framework free: createPleateClient(), errors, list and SSE helpers, and the generated types. pleate-client/react adds a provider and hooks built on TanStack Query, each returning a …Props object to spread on a pleate component.

createPleateClient

ts
import { createPleateClient } from "pleate-client";

const client = createPleateClient({
  baseUrl: "/api",
  locale: () => document.documentElement.lang,
  onUnauthorized: () => location.assign("/login"),
});

const me = await client.auth.me();
const page = await client.files.list({ search: "receipt", ordering: "-created_at" });
for await (const event of client.ai.send(conversationId, { content: "Hello" })) {
  if (event.event === "delta") process.stdout.write(event.data.text);
}

Options

OptionDefaultMeaning
baseUrl"/api"Where pleate-backend is mounted. An absolute URL works too.
fetchglobalThis.fetchCustom fetch: tests, or forwarding cookies on the server.
credentials"include"So the session cookie also travels on cross origin setups.
headersnoneExtra headers, or a function returning them. E.g. { Authorization: "Bearer pl_..." }.
localenoneSent as Accept-Language. A string or a function.
csrf{ cookieName: "csrftoken", headerName: "X-CSRFToken", path: "/csrf" }false for API key clients.
onUnauthorizednoneCalled on every 401.

Modules

ModuleMethods
authcsrf, me, updateMe, signup, login, logout, changePassword, requestPasswordReset, validateResetToken, resetPassword, verifyEmail, resendVerification, changeEmail, confirmEmailChange, uploadAvatar, removeAvatar, exportData, preferences, updatePreferences, deleteAccount
sessionslist, revoke, revokeOthers
mfastatus, setup, confirm, disable, regenerateBackupCodes, verify
oauthproviders, startUrl (a URL to navigate to), accounts, unlink
apiKeyslist, create, rename, revoke
fileslist, get, upload (with onProgress), rename, remove, usage, downloadUrl, presign, complete
notificationslist, unreadCount, markRead, markUnread, markAllRead, remove, clearRead, preferences, updatePreferences, stream (SSE), pushPublicKey, subscribePush, unsubscribePush
aimodels, suggestions, usage, conversations, createConversation, conversation, updateConversation, deleteConversation, messages, send (SSE), stop, regenerate (SSE)
billingplans, subscription, checkout, portal
marketingsubscribe, confirmSubscription, unsubscribe, contact, joinWaitlist, waitlistStatus
activitymine, all, get
webhooksevents, endpoints, createEndpoint, updateEndpoint, deleteEndpoint, rotateSecret, test, deliveries, delivery, redeliver
rbacmyFeatures, roles, createRole, updateRole, deleteRole, permissions, assignRole, removeRole, features
staffusers, user, updateUser, deleteUser, revokeSessions, sendPasswordReset, stats, bans, createBan, deleteBan
usagesummary
search(q, { types, limit, signal })The signed in user's files, conversations and notifications → SearchResult[].
list<T>(path, params)Any list endpoint of your own that follows the conventions → Page<T>.
httpThe underlying Http: get, post, put, patch, delete, raw, stream, upload, url, ensureCsrf.

Every method returns typed data and throws ApiError (status, code, fields, fieldErrors(), retryAfter) on failure. Streams are async generators of {event, data}; pass an AbortSignal to stop them. Types for every schema are available as Schema<"Me">, plus named aliases: Me, Session, ApiKey, FileItem, Notification, Conversation, ChatMessage, Plan, ActivityLog, StaffUser...

Helpers

ExportDoes
isApiError(error, code?)Type guard, optionally for one code.
toOrdering(sort) / fromOrdering(ordering)Between {key, direction} and -price.
toSearchParams(params)Query string without empty values, arrays repeated.
parseSse(body, signal)Parses any text/event-stream body (fetch, POST included).

React

tsx
<PleateProvider options={{ baseUrl: "/api" }}>          {/* or client={client} queryClient={queryClient} */}
  <App />
</PleateProvider>

The provider creates the client and a QueryClient (30 second stale time, no retries on 401) unless you pass yours. usePleateClient() returns the client for calls without a hook; keys holds the query keys, so you can invalidate them (queryClient.invalidateQueries({ queryKey: keys.apiKeys })).

Hooks

HookReturnsFor
useMe()user, isSignedIn, hasRole, hasPermission, hasFeature, query stateAny component
useUpdateMe()mutation, updates the cached userProfile forms
useLogin({ onSuccess })loginFormProps, twoFactorFormProps, mfaRequired, reset, login, verifyLoginForm, TwoFactorForm
useSignup({ onSuccess })signupFormProps, verificationRequired, signupSignupForm
useLogout({ onSuccess })mutation, clears the cacheAny button
useForgotPassword()forgotPasswordFormPropsForgotPasswordForm
useResetPassword(token, { onSuccess })resetPasswordFormProps, tokenValid, checkingTokenResetPasswordForm
useVerifyEmail(token)query of the verified userVerification page
useTwoFactorSetup({ onDone })twoFactorSetupProps (after start), start, starting, status, enabled, disableTwoFactorSetup
useOAuth({ next, mode, remember })oauthButtonsProps, providers queryOAuthButtons
useSocialAccounts()accounts query, unlinkLinked accounts list
useSessions()sessionListPropsSessionList
useApiKeys()apiKeyListPropsApiKeyList
useList(path | fn, options)tableProps, paginationProps, searchProps, sortProps(key), rows, settersDataTable, Table, SearchBar, Pagination
useCursorList(key, fetcher, options)items, fetchNextPage, hasNextPageFeeds, List
useUpload({ purpose, onUploaded })fileUploadProps, uploaded, busy, add, remove, retry, clearFileUpload
useNotifications({ live, pageSize, unreadOnly })notificationCenterProps, unreadCount, markRead, markAllRead, removeNotificationBell, NotificationCenter
usePushSubscription()mutation taking a ServiceWorkerRegistrationPush opt in
useChat(id | null, { model, onConversation })composerProps, messages, streaming, error, send, stop, regenerate, loadOlderChatThread, Message, Composer
useModels(initial?)modelPickerProps, model, setModelModelPicker
useSuggestions(onSelect)promptSuggestionsPropsPromptSuggestions
useConversations({ archived })useList result for conversationsChat sidebar
useAiUsage()query of today's tokensQuota meter
usePreferences()preferences, update (optimistic, rolls back on error)Theme and bottom bar settings
useUsage()plan, items, usageMeterPropsUsageMeter
useSearch(q, { types, limit })results, query state; runs from 2 charactersCommand palette
usePricing({ isSignedIn, signInHref, renderCta })pricingProps, billing, setBilling, checkout, portalPricing
useSubscription()subscription, openPortalBilling settings
useNewsletter({ source })newsletterProps, confirmationRequiredNewsletter
useContactForm()contactFormPropsContactForm
useWaitlist()mutation returning position and referral codeWaitlist form

Every hook also spreads the underlying TanStack Query result (data, isPending, error, refetch...) or exposes its mutations, for anything the props do not cover.

Errors in forms

errorProps(error) turns any failure into the error and fieldErrors props every pleate form takes: field messages go under their inputs, everything else above the form. mapFields renames backend fields to form fields.

tsx
import { errorProps, mapFields } from "pleate-client/react";

const save = useMutation({ mutationFn: client.auth.changePassword });
<PasswordForm
  onSubmit={(v) => save.mutate({ current_password: v.current, new_password: v.next })}
  {...mapFields(errorProps(save.error), { current_password: "current", new_password: "next" })}
/>