@farthershore/farthershore-js
v0.51.0
Published
Farther Shore Frontend SDK — the browser integration layer between static frontends and the Farther Shore platform (Core + Gateway).
Maintainers
Readme
@farthershore/farthershore-js
The Farther Shore Frontend SDK — the browser + React integration layer for your product's subscriber portal.
Status:
0.51.0(pre-1.0). Pin the version you build against and readCHANGELOG.mdbefore upgrading.
pnpm add @farthershore/farthershore-js # React is an optional peer (for /react)What this is
When you build a software business on Farther Shore, your subscribers get a portal where they sign in, pick a plan, manage API keys, watch their usage, and handle billing — and where you can surface your own product features. This SDK is how a frontend talks to that portal.
Your frontend code never deals with Core URLs, Gateway URLs, auth endpoints, or
routing rules. It expresses intent — "list my API keys", "subscribe to this
plan", "call my weather feature" — and the SDK decides where each request
goes (Core for platform concerns like auth, plans, usage, and billing; the
Gateway for your product's own features), how it's authenticated, and which
host/environment scoping headers to attach.
This guide walks through the on-ramps for integrating the SDK into a real app: the zero-config happy path, sign-in (always the platform's on a portal it serves), bringing your own design system, bringing your own data layer, and writing org-scoped custom hooks.
1. Zero-config happy path
On a portal served by the Farther Shore edge, the client needs no
arguments at all. It reads window.__FS_CONFIG__ (injected by the edge)
lazily — the first time a request actually needs it — and discovers the
businessId from the portal host.
import { createFartherShoreClient } from "@farthershore/farthershore-js";
const fs = createFartherShoreClient();Wrap your tree in the provider:
import { FartherShoreProvider } from "@farthershore/farthershore-js/react";
function App() {
return (
<FartherShoreProvider client={fs}>
<Portal />
</FartherShoreProvider>
);
}Then read platform state through the hooks. Every read hook returns the same
ecosystem shape — { data, error, isLoading, isError, isSuccess, refetch,
queryKey } — plus its mutations:
import { toPublicMessage } from "@farthershore/farthershore-js";
import { useApiKeys } from "@farthershore/farthershore-js/react";
function ApiKeys() {
const { data, isLoading, isError, error, refetch } = useApiKeys();
if (isLoading) return <p>Loading…</p>;
if (isError)
return <p>{toPublicMessage(error, "We couldn't load your keys.")}</p>;
return (
<ul>
{data?.map((k) => (
<li key={k.id}>{k.label}</li>
))}
</ul>
);
}Want a whole portal with almost no code? <FartherShoreRoot> is one wrapper —
provider + bootstrap gate + the plain .fs-app wrapper + managed auth context +
customer readiness —
and the managed component kit is self-fed under it. The root mounts the auth
provider and context but does not implicitly render a sign-in surface, so a
custom portal must compose one explicitly.
Signed-in customers can browse the portal without a plan. The root no longer
renders a plan picker. On first entry, Farther Shore starts the customer on the
declared free plan when one is available. Hosts mount FsOnboardingPlanRail on
their own billing or plan route and pass that route's href to
FsChoosePlanPrompt (href) and the key surfaces (ApiKeysPanel's
choosePlanHref, or ApiKeys.Root's noPlan). Permission gates still apply, and
subscription-scoped actions require an active plan. Loading, retries, checkout
reconciliation, and active-plan access confirmation remain managed by the root.
For example:
import {
FartherShoreRoot,
FsSignIn,
PlansTable,
SignedIn,
SignedOut,
UsageCard,
BillingSummary,
ApiKeysPanel,
} from "@farthershore/farthershore-js/components";
// The SDK is HEADLESS — it ships zero CSS. Provide the component styles
// yourself. A platform-provisioned repo already includes them as plain,
// editable CSS:
import "./styles/components.css";
function Application() {
return (
<>
<PlansTable />
<UsageCard />
<BillingSummary />
<ApiKeysPanel />
</>
);
}
<FartherShoreRoot client={fs}>
<SignedOut>
<FsSignIn />
</SignedOut>
<SignedIn>
<Application />
</SignedIn>
</FartherShoreRoot>;The public createFartherShoreClient(config) accepts only builder-facing
options (getToken, organizationId, apiKey, fetch, retry, the error
hooks, mock):
const fs = createFartherShoreClient({
retry: { maxAttempts: 2 },
});The platform-infrastructure knobs (coreUrl, portalHost, businessId,
environmentId, gatewayUrl) are not accepted here — the edge injects them
via window.__FS_CONFIG__, and the public factory strips them at runtime, so a
builder cannot point the client at the wrong place. A platform harness that must
target a non-prod environment (local dev without edge injection, self-hosting,
tests) uses the internal factory instead:
import { createFartherShoreClientWithPlatformConfig } from "@farthershore/farthershore-js/internal";
const fs = createFartherShoreClientWithPlatformConfig({
coreUrl: "http://localhost:4000", // dev/self-host only; injected on-platform
portalHost: "croncloud.example.com", // defaults to window.location.host
businessId: "biz_123", // usually omitted — bootstrap() discovers it
});Explicit config always wins over the injected channel. A request attempted
with no resolvable coreUrl throws an actionable FartherShoreConfigError.
Test-persona browser sessions
In preview environments, run farthershore personas login <business>
<persona-id> --env <environment>. The CLI opens the platform-owned sign-in
bridge, which establishes a host-only HttpOnly cookie before returning to the
exact application route. The SDK then reads session identity and RBAC from
/me and mints short-lived Gateway context tokens with that same-origin
cookie. Application code never parses a handoff URL, receives a persona bearer,
or stores one in web storage.
2. Sign-in
Sign-in is the platform's, not the app's. On a portal the platform serves,
<FartherShoreRoot> always mounts the managed sign-in layer, and visitors sign
in with the platform's login: the hosted sign-in page in production, a test
persona session in preview environments. There is no bring-your-own auth on a
platform-served portal:
skipAuthis ignored — the sign-in layer mounts anyway;- a
clerksign-in key override is ignored — only the platform's injected connection is used; - mock mode (
mock: true, or an injectedmock) is ignored — visitors never see placeholder data or a fake signed-in owner; - the auth strategy comes from the environment, never from a prop.
Only sessions the platform issued are accepted: a token your own code supplies
(getToken, fs.setTokenProvider(), fs.setSessionToken()) cannot sign
anyone in on a served portal.
Render a sign-in surface for signed-out visitors (<FsSignIn /> or
<FsSignInButton /> under <SignedOut>, or your own button calling
useFsSignIn()), and read the session through useFsAuth(): strategy is
"hosted" or "test-personas".
import { useFsSignIn } from "@farthershore/farthershore-js/components";
const { signIn, signUp } = useFsSignIn();
<button onClick={signIn}>Log in</button>;Publishing requires it. A portal is published only when its built output
ships this managed sign-in layer AND at least one sign-in control
(<FsSignIn />, <FsSignInButton />, or a button using useFsSignIn()) from
@farthershore/farthershore-js at or above the platform's minimum version. A
button wired straight to useFsAuth().signIn() works but does not count. The
check confirms both are in your build; mounting <FartherShoreRoot> and
rendering the control for signed-out visitors is what makes them appear. Otherwise the build is refused with a
typed reason (FRONTEND_SIGN_IN_MISSING or FRONTEND_SDK_TOO_OLD) shown by
farthershore frontend status, and the portal keeps serving what it served.
Local development and tests are not platform-served, so the knobs still
work there: farthershore frontend dev / preview render with placeholder
data (mock mode) by default, a local vite dev can pass a clerk connection
to <FartherShoreRoot>, and tests can pass skipAuth, mock, or their own
token source (getToken in the config, or fs.setTokenProvider() /
fs.setSessionToken()) for a standalone client. The signed-in persona preview
(farthershore frontend dev --live --persona …) behaves like a served portal.
3. BYO design system
This package is headless: every component renders semantic markup with
stable .fs-* class names and ships no CSS at all. You own 100% of the
styling — write it against the .fs-* class hooks (and the --fs-* CSS
variable tokens the components read for theming). A platform-provisioned repo
comes with a full default stylesheet as plain, editable CSS
(src/styles/components.css); import it, edit it, or replace it wholesale.
The managed components work standalone under a bare <FartherShoreProvider>
— you don't need <FartherShoreRoot> to use them:
import { FartherShoreProvider } from "@farthershore/farthershore-js/react";
import {
PlansTable,
ApiKeysPanel,
UsageCard,
BillingSummary,
TeamPanel,
AuditLogTable,
RateLimitDisplay,
BillPreviewCard,
BalanceCard,
ResourceLimitUsageCard,
UpgradePrompt,
DocsLegal,
ResourcesPanel,
RoutePanel,
Plans,
Usage,
} from "@farthershore/farthershore-js/components";
import "./styles/components.css"; // your own styles for the .fs-* class hooks
<FartherShoreProvider client={fs}>
<PlansTable />
<ApiKeysPanel />
</FartherShoreProvider>;Recompose without forking. Every managed surface is also a set of parts
(the default component is one arrangement of them), so a custom plan card is
<Plans.Root> with a function child on Plans.Grid. The parts keep the real
actions, permissions and required notices:
<Plans.Root>
<Plans.Grid>
{(offer) => (
<Plans.Card planId={offer.id}>
<Plans.Name />
<Plans.Price />
<Plans.Features />
<Plans.PurchaseNotice />
<Plans.CheckoutButton />
</Plans.Card>
)}
</Plans.Grid>
</Plans.Root>The usage card is also a set of Usage parts (<UsageCard> is their default
arrangement); give Usage.Rows a function for a custom row per metered
dimension:
<Usage.Root>
<Usage.Head />
<Usage.Body>
<Usage.Rows>
{(row, index) => <MyUsageRow key={row.key} row={row} index={index} />}
</Usage.Rows>
</Usage.Body>
<Usage.Empty />
</Usage.Root>A custom billing summary composes the Billing parts (Billing.Root,
Billing.Plan, Billing.ManageButton, Billing.TopUpButtons, …) the same
way. See the public guide "Defaults, parts and flow hooks" for every surface.
Every component also accepts a plain className on its root for CSS-based
restyling.
To render your own wrapper instead of the plain .fs-app element
<FartherShoreRoot> adds, pass skipAppShell:
<FartherShoreRoot client={fs} skipAppShell>
<MyThemeProvider>
<Portal />
</MyThemeProvider>
</FartherShoreRoot>4. BYO data layer
Already run TanStack Query or SWR? The /react subpath ships a structural
adapter — no runtime dependency on either library, so it costs nothing unless
you import it.
TanStack Query:
import { useQuery } from "@tanstack/react-query";
import { fsQueryOptions } from "@farthershore/farthershore-js/react";
const q = fsQueryOptions(fs);
const { data } = useQuery(q.keys.list());
const { data: usage } = useQuery(q.usage.snapshot());SWR:
import useSWR from "swr";
import { createFsFetcher } from "@farthershore/farthershore-js/react";
const fetcher = createFsFetcher(fs);
// The key is [integration, path]: one of your backend integrations by name.
const { data } = useSWR(["billing-history", "/v1/charges"], ([id, path]) =>
fetcher(id, path).then((res) => res.json()),
);fsQueryOptions covers the common reads (keys, usage, billing, plans,
me, business). For a product-declared resource beyond those, use the
generic escape hatch — both return a ready-to-use { queryKey, queryFn }
object:
const { data: widgets } = useQuery(q.resource("widgets"));
const { data: widget } = useQuery(q.resourceItem("widgets", widgetId));5. Org-scope custom hooks
Writing your own hook that reads org-scoped data (a product-declared resource,
say)? Use useReadScope() instead of useFartherShore() alone — it composes
the client with the reactive active-org id, so folding it into your query
key/dep array makes an org switch auto-refetch:
import { useReadScope } from "@farthershore/farthershore-js/react";
import { useAsync } from "@farthershore/farthershore-js/react";
function useMyResource() {
const { fs, businessId, organizationId } = useReadScope();
return useAsync(
(signal) => fs.resources("widgets").list({ signal }),
[fs, businessId, organizationId],
["widgets", businessId, organizationId],
);
}fs alone is a stable reference and never reacts to an org switch on its
own — businessId/organizationId are what make the dep array and query key
scope-correct.
Errors
Reads and mutations throw typed errors you can catch and branch on. The root
package keeps the five most-caught classes:
import {
FartherShoreError,
FartherShoreApiError,
LimitExceededError,
FartherShoreRateLimitedError,
FartherShoreConfigError,
} from "@farthershore/farthershore-js";
try {
await fs.keys.list();
} catch (err) {
if (err instanceof LimitExceededError) showUpgrade(err);
else if (err instanceof FartherShoreApiError && err.status === 401) {
// session expired — prompt re-auth
} else throw err;
}The full taxonomy — throttle subclasses (ConcurrencyLimitError,
AdaptiveThrottleError), deny-envelope parsers, makeApiError, secure-fetch
codes, and more — lives at the @farthershore/farthershore-js/errors subpath.
To show an error to a visitor, render toPublicMessage(err, fallback) rather
than err.message. A 4xx that carried a message (a validation refusal, a
missing permission) reads as itself and a 401 asks the visitor to sign in
again; a network failure, any 5xx or an unrecognized error becomes neutral
copy, so platform and provider detail never reaches the page. The managed
components all render failures this way.
Display helpers
Pure catalog display helpers (declared plan kind, recurring price, quotas,
dates, status chips) are grouped under the format namespace, so every
frontend renders them identically:
import { format } from "@farthershore/farthershore-js";
format.formatCents(1234); // "$12.34"
format.formatNanos("12450000000"); // "$12.45" — bill-preview nanos, bigintA plan describes its billing components: floor, canCharge, fundable,
billsUsage, trialDays, the published rate card per pricing family
(plan.pricingDisplay — null when the builder withholds rates) and its
funding (plan.funding: included value and top-up packs). Render them with
format.describePlanBilling, format.catalogPricingLines and
format.formatTopUpOffer. Amounts are exact decimal strings and integer cents;
nothing is rounded. Per-period usage money comes only from the bill preview — fs.billing.getBillPreview(),
useBillPreview(), or the <BillPreviewCard> component — computed by the
same engine that invoices, and honoring the plan's disclosure (transparent
shows windows / totals / balances; opaque shows allowances only).
What the account has left to spend, per usage unit, comes from
fs.billing.getBalances(), useBalances() or the <BalanceCard> component:
exact amounts in each unit (format.formatUnitBalance renders money in its
currency and credits by their key), or only the share used and left on an
opaque plan (format.formatBalanceShare). A balance with source: "estimate"
may not count the most recent calls yet; the card labels it "Updating". A spent
balance on a plan that sells top-ups links to BillingSummary's top-up buttons.
Testing
@farthershore/farthershore-js/test-utils gives you a fully-typed mock client,
a provider wrapper, and typed-error builders — no network, no server:
import {
createMockFartherShoreClient,
FartherShoreTestProvider,
mockLimitExceeded,
} from "@farthershore/farthershore-js/test-utils";
const client = createMockFartherShoreClient({
keys: {
list: async () => [
{
id: "key_1",
keyPrefix: "fsk_test_ab12",
label: "Test key",
status: "active",
createdAt: "2026-01-01T00:00:00Z",
lastUsedAt: null,
revokedAt: null,
kind: "PERSONAL",
memberId: null,
serviceAccountId: null,
serviceAccountName: null,
createdBy: null,
},
],
},
});
render(
<FartherShoreTestProvider client={client}>
<ApiKeys />
</FartherShoreTestProvider>,
);mockLimitExceeded, mockRateLimited, and mockApiError build the typed
errors above for asserting your error-handling paths without a real deny from
Core or the Gateway.
Learn more
See the platform docs for the full guide to building, publishing, and operating a
product on Farther Shore. Breaking changes within 0.x are recorded in
CHANGELOG.md — read it before bumping.
Team roles use one write surface: fs.team.roles.assign(membershipId, teamRole)
assigns owner, admin, member or a custom key. Invite with
fs.team.invites.create({ email, teamRole }); omit teamRole to invite a
Member. The legacy { role } invite input and team.updateRole were removed
in 0.35.0. role on returned rows is the stored tier, while teamRole is
the member's actual role. Assignment returns TeamMemberRoleUpdated; refetch
team.list() for the full roster row.
