@gravity-rail/react
Canonical React components & hooks for embedding Gravity Rail — chat, forms, data, and voice — into any React app. The same components run unchanged in a Gravity Rail source site (sandboxed, zero-config) and in a third-party host (your own Next.js/Vite app) by swapping one transport seam.
import { GravityRailProvider, ChatButton, FormDialog, useDataType } from '@gravity-rail/react';
import '@gravity-rail/react/styles.css'; // optional default theme
- Zero required dependencies beyond React. No data-fetching library, no UI kit — it runs in a bare source-site bundle (React + this package only).
- Pluggable transport. Same-origin by default (works in a sandboxed source site with no token in JS); pass a custom
fetchto route through your own BFF. - Themeable. Every visual is driven by
--gr-*CSS custom properties. Ship the default stylesheet or bring your own. - TypeScript-first, ESM + CJS, tree-shakeable.
Installation
npm install @gravity-rail/react
# peers: react >=18, react-dom >=18. @gravity-rail/sdk is optional.
# The /query subpath also needs @tanstack/react-query >=5.89.
In a Gravity Rail source site the package is already on the build allow-list — just import it.
Subpath imports (tree-shaking)
Everything is available from the root barrel (which is side-effect-free, so modern bundlers tree-shake unused features). For an explicit, minimal surface you can also import from curated subpaths — all of which share the same provider/context instance:
import { GravityRailProvider } from '@gravity-rail/react/context';
import { DataForm, DataWizard, useDataRecords } from '@gravity-rail/react/data';
import { ChatWidget, useChat } from '@gravity-rail/react/chat';
import { VoiceButton } from '@gravity-rail/react/voice';
import { Router, Route, Link } from '@gravity-rail/react/router';
Quick start
A. Source site (same-origin, zero config)
A hosted source Site injects its workspace and theme through window.GRAVITY_RAIL_SITE_CONTEXT. Its same-origin API proxy uses the Site session cookie. A workspace UUID identifies a workspace; it does not authenticate a visitor. Configure Site access and record permissions before adding workspace data.
Use real paths for pages and record details. This complete example expects an existing Form with the slug loads. Replace that slug with your Form slug:
import { useState } from 'react';
import {
GravityRailProvider,
WorkspaceBoundary,
Router,
Route,
Link,
useRoute,
matchPath,
DataForm,
DataRecordList,
DataRecordEditor,
useDataType,
useDataRecord,
FloatingChat,
type DataType,
} from '@gravity-rail/react';
import '@gravity-rail/react/styles.css';
function Loads() {
const { data: form, loading, error } = useDataType('loads');
const [refreshKey, setRefreshKey] = useState(0);
const { navigate } = useRoute();
if (loading) return <p>Loading Form…</p>;
if (error) return <p role="alert">{error.message}</p>;
if (!form) return <p>Form not found.</p>;
return (
<>
<h1>Loads</h1>
<DataForm dataType={form} onSuccess={() => setRefreshKey((value) => value + 1)} />
<DataRecordList
dataType={form}
refreshKey={refreshKey}
emptyState={<p>No loads yet.</p>}
onEdit={(record) => navigate(`/loads/${record.id}`)}
/>
</>
);
}
function LoadRecord({ form, recordId }: { form: DataType; recordId: number }) {
const { data: record, loading, error, reload } = useDataRecord(form.id, recordId);
if (loading) return <p>Loading record…</p>;
if (error) return <p role="alert">{error.message}</p>;
if (!record) return <p>Record not found.</p>;
return (
<>
<h1>Edit load</h1>
<Link to="/loads">All loads</Link>
<DataRecordEditor
key={record.id}
dataType={form}
record={record}
onSuccess={() => reload()}
/>
</>
);
}
function LoadDetail({ id }: { id: string }) {
const { data: form, loading, error } = useDataType('loads');
const recordId = Number(id);
if (!/^[1-9][0-9]*$/.test(id) || !Number.isSafeInteger(recordId)) {
return <p>Record not found.</p>;
}
if (loading) return <p>Loading Form…</p>;
if (error) return <p role="alert">{error.message}</p>;
if (!form) return <p>Form not found.</p>;
return <LoadRecord key={recordId} form={form} recordId={recordId} />;
}
function Shell() {
const { path } = useRoute();
const pages = ['/', '/overview', '/loads', '/loads/:id'];
return (
<>
<nav aria-label="Main">
<Link
to="/overview"
aria-current={path === '/' || path === '/overview' ? 'page' : undefined}
>
Overview
</Link>{' '}
<Link
to="/loads"
aria-current={
matchPath('/loads', path) || matchPath('/loads/:id', path) ? 'page' : undefined
}
>
Loads
</Link>
</nav>
<WorkspaceBoundary>
<main>
<Route path="/">
<h1>Overview</h1>
</Route>
<Route path="/overview">
<h1>Overview</h1>
</Route>
<Route path="/loads">
<Loads />
</Route>
<Route path="/loads/:id">{({ id }) => <LoadDetail id={id} />}</Route>
{!pages.some((page) => matchPath(page, path)) && <h1>Page not found</h1>}
</main>
<FloatingChat />
</WorkspaceBoundary>
</>
);
}
export function App() {
return (
<GravityRailProvider>
<Router>
<Shell />
</Router>
</GravityRailProvider>
);
}
WorkspaceBoundary shows one No workspace provided message and prevents
workspace children from mounting. Pass fallback to customize it. Keep public
content outside this boundary. The provider also supports explicitly configured
public components such as AnonymousForm.
FloatingChat stays mounted outside the changing pages so navigation preserves
the open Chat. Opening it shows the welcome without creating a Chat. Sending a
message, choosing a suggestion, or selecting Start voice creates the Chat.
B. Third-party host (your own app + BFF)
Off-platform, serve your own same-origin BFF routes (use @gravity-rail/sdk server-side with an OAuth token) and either mirror the /api/v2/... shape or pass a custom fetch. The browser still only ever talks same-origin:
<GravityRailProvider
config={{
workspaceUuid: 'YOUR-WORKSPACE-UUID',
// Attach auth / rewrite to your BFF. The browser never holds a long-lived token.
// This example assumes your BFF mirrors /api/v2/... paths.
fetch: (input, init) => fetch(input, init),
// For voice (cross-origin WebSocket): mint a short-lived token from your BFF.
apiUrl: 'https://api.gravityrail.com',
getAccessToken: async () => {
const response = await fetch('/api/gr-token');
if (!response.ok) throw new Error('Unable to start voice');
return response.text();
},
}}
>
<App />
</GravityRailProvider>
Building blocks
Forms & data
The API calls a Form a DataType. useDataType(slugOrId) reads an existing schema; it does not create a Form. Create the Form in the Workspace first. DataForm creates records, DataRecordList lists them, and DataRecordEditor updates an existing record.
Core hooks return data, loading, error, and reload(). After a write, call reload() on affected reads or change DataRecordList.refreshKey. A write may return a value-free receipt when read permission is absent; reload a permitted read instead of replacing displayed values with the receipt. DataForm and DataRecordEditor already show submission errors, so avoid a second alert for the same failure.
For a smaller create-only component:
function ContactForm() {
const { data: dataType, loading, error } = useDataType('contact');
if (loading) return <p>Loading Form…</p>;
if (error) return <p role="alert">{error.message}</p>;
if (!dataType) return <p>Form not found.</p>;
return <DataForm dataType={dataType} />;
}
| Export | Kind | Purpose |
|---|---|---|
DataForm | component | Render a DataType schema as inputs; create a record on submit |
DataRecordList | component | List of records for a DataType — variant="table" (default) or variant="cards" |
FormDialog | component | Button → modal containing a DataForm |
useDataType / useDataRecords / useCreateDataRecord | hooks | Core data access with loading/error state |
fetchDataType / listDataRecords / createDataRecord | functions | Promise-based, hook-free |
StepUpRequiredError / SignInVerificationChallenge | error/type | Safe assurance challenge with permitted-method hints |
verifySignIn / SignInVerification | function/component | Explicit verification on the pinned app origin and return to the Site |
These verification exports are also available from @gravity-rail/react/data.
Source Sites inject siteContext.verificationOrigin from the deployment's WebAuthn
origin. Third-party hosts must supply config.verificationOrigin themselves. The
navigation action checks that exact origin and accepts HTTP only for local
loopback or .test development hosts. The response cannot choose a different host.
An existing source release must be rebuilt to receive this new runtime metadata.
Public anonymous Forms
AnonymousForm reads only the public schema of a Form that has anonymous
submissions enabled. It does not read or list submitted records. In a Gravity
Rail source-site, the component gets a token through a narrow first-party
reCAPTCHA bridge, so the site's compiled JavaScript never loads Google's script.
For another host, supply a token callback; the API checks the token, so a Form
UUID by itself is not enough there. Use the public site key and the
anonymous_form_submit action expected by the server. Never put a reCAPTCHA
secret in browser code.
On a source-site, use the injected workspace context and the trusted app-hosted token bridge:
import { AnonymousForm } from '@gravity-rail/react';
<AnonymousForm workspaceUuid="YOUR-WORKSPACE-UUID" formUuid="PUBLIC-FORM-UUID" />;
For a third-party host, the host owns provider setup and the public site key:
import { AnonymousForm } from '@gravity-rail/react';
import { ReCaptchaProvider, useReCaptcha } from 'next-recaptcha-v3';
function PublicRequestForm() {
const { executeRecaptcha } = useReCaptcha();
return (
<AnonymousForm
workspaceUuid="YOUR-WORKSPACE-UUID"
formUuid="PUBLIC-FORM-UUID"
getRecaptchaToken={async () => {
if (!executeRecaptcha) throw new Error('reCAPTCHA is not ready');
return executeRecaptcha('anonymous_form_submit');
}}
/>
);
}
export function App() {
return (
<ReCaptchaProvider reCaptchaKey={process.env.NEXT_PUBLIC_RECAPTCHA_SITE_KEY} useEnterprise>
<PublicRequestForm />
</ReCaptchaProvider>
);
}
The component sends the schema and submission requests without browser cookies
or API credentials. For a third-party host, allow the canonical
/api/v2/w/{workspaceUuid}/anonymous-forms/... paths through the host's
same-origin proxy.
The easy path (@gravity-rail/react/query)
The core above is dependency-free. The /query subpath layers in
React Query (an optional peer —
@tanstack/react-query) for caching + global invalidation, plus
batteries-included components that fetch their own data. Wrap your app in a
QueryClientProvider alongside GravityRailProvider:
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { GravityRailProvider } from '@gravity-rail/react';
import { useMe, AccountMenu } from '@gravity-rail/react/query';
<QueryClientProvider client={new QueryClient()}>
<GravityRailProvider>
<AccountMenu /> {/* renders the signed-in chip, or nothing when anonymous */}
</GravityRailProvider>
</QueryClientProvider>;
| Export | Kind | Purpose |
|---|---|---|
useDataType / useDataRecords / useDataRecord + create/update/delete | hooks | React Query versions with caching + invalidation |
useMe | hook | The current signed-in member (GET /me), cached |
fetchMe (+ Member type) | function | Promise-based, hook-free current-member fetch |
AccountMenu | component | Signed-in account chip (initials avatar + name + Log out); renders null when anonymous |
useRecordQuery / runRecordQuery | hook/fn | Server-side filter, sort, count and aggregate over a Form's records (see below) |
gravityKeys (+ GravityQueryScope type) | object | Scoped cache keys for manual invalidateQueries / prefetchQuery (see below) |
The mutation hooks keep cached lists correct. After useUpdateDataRecord succeeds,
the saved record has replaced the copy in every cached list that holds it and in its
useDataRecord entry when mutateAsync resolves; useDeleteDataRecord has removed
the record from the lists that hold it and lowered the total of unfiltered lists. Both then refetch the lists in the background. A new record's
place in a paged or filtered list is unknown, so useCreateDataRecord stays pending
until the lists have refetched. The saved fieldValues merge into the cached ones, so a
value-free write receipt never blanks a list.
Record queries (useRecordQuery) cannot be patched in place, so they refetch. A mutation knows only the Form's numeric id, so it refetches the queries that name that id and every query that names its Form by slug, whichever Form that slug is: useCreateDataRecord awaits the list and record-query refetch before it settles, so no query still shows old data then; useUpdateDataRecord and useDeleteDataRecord patch the lists immediately and refetch record queries in the background.
All of this happens only in the workspace the mutation started in: a mutation keeps the
provider, workspace and Form it started with, even if the provider changes workspace or
the hook's Form id changes before it settles (including a mutation paused offline).
Cache keys are scoped to the API base and workspace
Form, record and Member ids are only unique inside one workspace, so every cache key
starts with the resolved API base and workspace: ['gravity-rail', apiBase, workspaceUuid | null, kind, …]. Two GravityRailProviders under one QueryClient, or
one provider that changes workspace, never read each other's records or /me. Every
gravityKeys builder takes that scope first. Pass useGravityRail() (it carries the
resolved apiBase and workspaceUuid), or outside React the same two values the
transport uses ('' is the same-origin API base):
import { useQueryClient } from '@tanstack/react-query';
import { useGravityRail } from '@gravity-rail/react';
import { gravityKeys, listDataRecords } from '@gravity-rail/react/query';
function useRefreshCheckins(dataTypeId: number) {
const client = useGravityRail();
const queryClient = useQueryClient();
return {
// Prefetch: the key is the same one useDataRecords(dataTypeId) reads.
prefetch: () =>
queryClient.prefetchQuery({
queryKey: gravityKeys.recordsList(client, dataTypeId, {}),
queryFn: () => listDataRecords(client, dataTypeId, {}),
}),
// One Form's lists, in this provider's workspace only.
refreshForm: () =>
queryClient.invalidateQueries({ queryKey: gravityKeys.records(client, dataTypeId) }),
// Everything this provider has cached (its API base + workspace).
refreshScope: () => queryClient.invalidateQueries({ queryKey: gravityKeys.scope(client) }),
};
}
// Outside React, name the scope yourself (queryClient is your QueryClient):
const scope = { apiBase: '', workspaceUuid: 'YOUR-WORKSPACE-UUID' };
queryClient.invalidateQueries({ queryKey: gravityKeys.me(scope) });
// Deliberately global — every workspace and API base this QueryClient holds:
queryClient.removeQueries({ queryKey: gravityKeys.all });
- Unresolved workspace. Until a workspace is known the query hooks hold (send
nothing), and their keys carry an explicit
nullworkspace, so they can never read another workspace's data. A mutation without a workspace fails withNo workspace providedbefore any request or cache write. - Signing out or changing actor. Keys separate workspaces and API bases, not the
people behind one transport. When the signed-in person changes within the same
workspace — sign-out, account switch, a different token in a custom
fetch— clear or replace theQueryClient. Never put tokens or a fetch function's identity in a key. - Persisted caches. Entries stored by an earlier version have unscoped keys and are
never read. If you persist or dehydrate the
QueryClient, discard those entries (or bump your persister's version); do not relabel them with the workspace selected now.
Filtered, sorted and aggregated queries
useDataRecords pages through records and cannot filter by field. To filter, sort,
count or roll up a Form's records on the server, use the Query Engine client:
useRecordQuery in @gravity-rail/react/query, or runRecordQuery (also in the root
and /data entries) without React Query. The session needs records:read. On a
source site that is a Site admin opt-in: the Site's Reading Records control must be
on, and the signed-in Member's role must also grant records:read (the session's
scopes are the intersection of the two). Without it the query fails with an access
error. dataType is the Form's slug or numeric id; field paths
are record.<slug> or a system field (record.createdAt, record.updatedAt,
record.externalId, record.memberId, record.isTest).
A filtered, sorted page of records:
import { useRecordQuery } from '@gravity-rail/react/query';
function OpenCheckins() {
const { data, error, isLoading } = useRecordQuery({
entity: 'data_record',
dataType: 'checkins',
where: {
kind: 'and',
children: [
{ kind: 'compare', field: 'record.status', op: 'eq', value: 'open' },
{
kind: 'compare',
field: 'record.createdAt',
op: 'gte',
value: { type: 'daysAgo', days: 30 },
},
],
},
sort: [{ field: 'record.createdAt', dir: 'desc' }],
limit: 20,
});
if (isLoading) return <p>Loading…</p>;
if (error) return <p role="alert">{error.message}</p>;
// data.items[n].fieldValues.status; data.nextCursor is the next page's `cursor`.
return <p>{data?.items.length} open check-ins</p>;
}
A weekly average:
import { aggregateNumber, useRecordQuery } from '@gravity-rail/react/query';
const { data } = useRecordQuery({
entity: 'data_record',
dataType: 'checkins',
timezone: 'UTC',
aggregate: {
groupBy: [{ field: 'record.createdAt', bucket: 'week', alias: 'week' }],
metrics: [
{ fn: 'avg', of: 'record.score', as: 'avg_score' },
{ fn: 'count', as: 'n' },
],
},
});
// data.rows: [{ week: '2026-01-05T00:00:00+00:00', avg_score: '47.63', n: 3 }, …]
const points = data?.rows.map((r) => ({ week: r.week, avg: aggregateNumber(r.avg_score) }));
-
Modes. A query without
aggregatereturns rows; pass{ mode: 'count' }to get{ count }instead. A query withaggregatereturns{ rows }. Every result haswarningsandcost({ score, budget }, ornull). -
Buckets. A
timestamptzgroup value is truncated in the session'sTimeZoneunless the query setstimezone: 'UTC'; aDATE/naive value is pinned first because it carries no instant. A UTC-truncatedtimestamptzlabel comes back as a naive UTC string (YYYY-MM-DDTHH:MM:SS), so parse it as UTC rather than in the browser's zone. Settingtimezone: 'UTC'also reads offset-less record dates andonDaybounds in UTC. The Record Metric series always does this. -
Paging. Rows results carry
nextCursor; pass it ascursorin the same query for the next page. It isnullon the last page. -
Numbers.
countandcountDistinctare JSON numbers.sum,avg,minandmaxare exact decimals that arrive as strings ("47.63"), and the client leaves them as sent.aggregateNumber(value)converts one to a number (nullstaysnull). A decimal string becomes the nearest double, so digits beyond about 15 to 17 significant digits are rounded; the only guard is on the integer part, which throws aRangeErrorabove 15 digits because a double cannot hold every such integer. Keep the string for those. Bucketed dates are ISO-8601 strings. -
Errors.
runRecordQueryrejects withRecordQueryError:kindisvalidation(400, or a 422Validation failedwith the per-fielderrors),access(403, withrequiredScopewhen the server names one),cost_exceeded(a 422query cost N exceeds budget M) orrequest_failed;statusis the HTTP status. Messages are the server's text, which names fields and operators and never record values. A request for extra sign-in verification rejects withStepUpRequiredError. The hook'serroris typedError(a network failure is a plainError); narrow withisRecordQueryError(error)before readingkind. -
Without React Query.
runRecordQuery(client, query, mode?)takes the value ofuseGravityRail():const client = useGravityRail();
const { count } = await runRecordQuery(client, openQuery, 'count'); -
Holding a query.
useRecordQuery(null)and{ enabled: false }send nothing, for example while a filter input is incomplete. -
Freshness. Cache keys come from
gravityKeys.recordQuery(client, mode, query). Create, update and delete through the/querymutation hooks refetch the queries on that Form (create waits for them; update and delete refetch in the background). A mutation knows the Form's numeric id, so a query that names the Form by slug refreshes after any record change.
Chat
Text replies use same-origin AG-UI SSE. Voice uses the realtime WebSocket described below:
const { messages, suggestions, start, sendMessage, isStreaming, isLoading, queuedMessageCount, stop, isStopping, reset } = useChat({
greeting: 'Hi! How can I help?',
});
The floating bubble opens a Workflow menu. Choose a Workflow to see its local greeting and suggestions; Back returns to the menu. Contextual requests open the selected Workflow directly. These navigation actions create no Chat. Send, a suggestion click, or explicit Start voice creates once. start() explicitly creates and loads the server greeting; use it only when creation is intentional. reset() discards the local session without creating another Chat. sendMessage(text) retains its PromisesendDraft(text, files) returns whether the send completed so a composer can retain failed drafts. A completed send with failed history refresh still returns true and reports the read error.
While a response is running, the composer accepts follow-up messages and shows queuedMessageCount. stop() requests cancellation of the current response; isStopping reports the pending request, and error reports a failure. A queued message may still need a later response after Stop. File attachments stay with their submitted message.
While the Agent calls tools, useChat returns toolCalls: the latest turn's calls in order, each { id, name, label, status }. label is the name in plain words (list_all_records is List All Records) and status is running, done or failed. A call with no result when the stream ends is done; one cut off by a stream error is failed. ChatWidget shows the tool running now and a count (for example "Using List All Records… · 3 tools so far", then "Used 3 tools"), with the list collapsed behind a disclosure. The activity sits after the latest user message and before its replies, during streaming and after history refresh. Each turn starts collapsed; the detail list is mounted only when opened, so the host site's list styles cannot reveal it. Calls hold names and statuses only; tool arguments and results can carry record data and are never kept or shown. A turn that only calls tools adds no assistant message, so messages never holds an empty one. toolCalls clears when the next text message is sent or a voice interaction begins, on reset() and resume(), and when a workspace, Site, transport or Workflow change replaces the Chat.
| Export | Purpose |
|---|---|
useChat | Streaming messages, toolCalls, suggestions, queuedMessageCount, stop(), isStopping, chatId, ensureChat(mode?), resume(id) and refresh() |
ChatWidget | Native composer; lazy by default. autoStart={true} explicitly restores eager creation. |
ChatButton | Button that opens a lazy widget in a modal |
FloatingChat | Persistent floating session, Workflow menu, paginated own-Chat history and New chat |
InlineChat | Lazy embedded widget |
ChatWorkflowOption / ChatContextRequest | Types for configured Workflows and keyed contextual drafts |
ChatToolCall / ChatToolCallStatus | Types for useChat().toolCalls entries |
<FloatingChat
workflowId={1}
workflows={[
{
id: 1,
label: 'Operations',
greeting: 'How can I help?',
suggestions: ['Prepare a briefing'],
},
]}
open={open}
onOpenChange={setOpen}
contextRequest={{ key: requestKey, workflowId: 1, draft: 'Investigate this shipment' }}
enableVoice
enableFileUpload
/>
Configure authorized Workflow IDs. A new context opens an editable draft in a new local session; it does not run a Workflow or append to a different Chat. History uses existing own-Chat pagination and resumes the same Chat. Closing preserves the draft/session and releases voice capture. Neither drafts nor file bytes use browser storage.
The composer supports Enter to send, Shift+Enter, file picker/drop drafts, removal and wrapping suggestions. Raster images use message ingress. PDF, Markdown, CSV and XLSX use existing private file creation in the exact Chat folder only on Send. This needs the backend own-file/participating-Chat-folder self-access change; it is not enabled by adding general file scopes. Limits are 4 MiB per document and 4 MiB total images. Failed send/upload keeps drafts and files; an interrupted stream may have saved a turn, so inspect history before manually sending again.
Voice
Keep a custom provider fetch function stable, for example with useCallback. Changing transport identity closes Chat/voice sessions because it can change the acting Member. A fresh config object with unchanged transport and session inputs preserves the session.
Browser voice uses the existing origin-bound realtime WebSocket and Workflow configuration. enableVoice opts the widget in. useVoice({ getChatId: chat.ensureChat }) joins the same text Chat and passes realtime when voice initiates its creation. Text-first Chats keep their opening mode; the server creates a realtime interaction session when voice connects. Close, switch, stop and socket errors release audio resources.
<VoiceButton label="Talk to an agent" />;
const { status, isActive, start, stop, error } = useVoice();
Router & presentational helpers
Router follows browser history. Route matches an exact path, ignoring trailing
slashes, and supports required named segments such as /loads/:id. A render
function receives decoded parameters. Malformed URL encoding does not match.
Write static pattern segments as decoded text: /100%off matches /100%25off.
matchPath(pattern, pathname) returns the parameter object or null; use it with
useRoute().path for active navigation or a page-not-found fallback.
Link renders a real anchor and keeps modifier clicks, downloads, external links,
named targets, and fragment scrolling native. Its onClick may cancel navigation
with preventDefault(). useRoute() also exposes search, hash, and
navigate(to, { replace: true }) for same-origin app paths. Invalid or cross-origin
destinations throw an error. Relative URLs resolve against the current URL.
Query-only navigation updates subscribers. Supply any query parameters your app
needs on the destination; the router does not carry them automatically.
Hosted source Sites serve the same application bundle on direct deep links. On another host, configure an SPA fallback for application paths so refreshes and shared URLs reach your app. If your app already has a router, keep using it.
SiteHeader, DataList, ProgressSteps, and ConsentCheckbox provide optional
presentational building blocks.
Server-side flow (with @gravity-rail/sdk)
The React components cover the in-page surface (forms, chat, voice). The steps a host does on the server — register a member, populate a form, enroll into a journey, verify inbound webhooks — live in @gravity-rail/sdk and its @gravity-rail/sdk/helpers entry, so a BFF host uses the same package everywhere:
import { GravityRailClient } from '@gravity-rail/sdk';
import {
upsertDataRecordForMember,
enrollMemberInJourney,
verifyWebhookSignature,
WEBHOOK_SIGNATURE_HEADER,
} from '@gravity-rail/sdk/helpers';
const client = new GravityRailClient(oauthToken, apiUrl);
// 1. Register the member
const member = await client.createWorkspaceMember(wid, { name, phone, externalId, memberRoleId });
// 2. Populate a form (idempotent, keyed by member)
await upsertDataRecordForMember(client, wid, dataTypeId, member.id, { mrn, provider });
// 3. Enroll into a journey (resolve by memberId | phone | externalId; find-or-create labels)
await enrollMemberInJourney(client, wid, { memberId: member.id, journeyId, labels: ['pilot'] });
// 4. Verify an inbound webhook (in your POST handler, over the RAW body)
const result = await verifyWebhookSignature(
rawBody,
req.headers.get(WEBHOOK_SIGNATURE_HEADER),
secret
);
if (!result.ok) return new Response(result.reason, { status: 401 });
The same BFF that serves these routes can expose the same-origin /api/v2/... proxy the provider (transport seam below) talks to, so the browser never holds a token.
Theming
Import the optional stylesheet and override any --gr-* token at the root (or any ancestor):
:root {
--gr-color-primary: #0ea5e9;
--gr-radius-md: 4px;
--gr-font: 'Inter', system-ui, sans-serif;
}
Source sites populate these tokens from the site's theme settings automatically. Skip the stylesheet entirely and target the gr-* class names with your own CSS if you prefer.
The transport seam
Both hosting models put a same-origin request in front of the browser; only what sits behind the origin differs:
| Source site | Third-party host | |
|---|---|---|
baseUrl | "" (proxy forwards) | "" (your BFF) |
| Auth | httpOnly gr_sess_ cookie | your BFF attaches an OAuth token |
| Workspace | from injected site context | config.workspaceUuid |
| Voice token | same-origin /realtime/ws-token | config.getAccessToken |
SSR
All components are client components (useState/window). The provider degrades gracefully when window is absent (it returns an empty site context), so importing the package in a Server Component is safe — render the interactive pieces on the client.
Links
- Docs & API reference: https://docs.gravityrail.com/developer/libraries/react
- TypeScript SDK:
@gravity-rail/sdk
Assistant message Markdown
Markdown renders headings, lists, code, links, and GitHub-flavored tables using the same parser libraries as the main app. Tables scroll within the message on narrow screens. Raw HTML is omitted rather than rendered or shown as literal markup. Remote images are displayed as alt text without loading their URLs; links allow only HTTP, HTTPS, and mailto URLs.
License
MIT