@swirepay-developer/reports-builder-sdk
v1.1.5
Published
React SDK for embedding Swirepay Reports Builder dashboards (filters, search, Cognito auth)
Maintainers
Readme
Swirepay Reports Builder React SDK
Embed dashboards and reports with server-side filters, search, and Cognito-aware authentication.
Full auth + ECS guide: docs/AUTH_AND_SDK.md
Install
npm (host applications):
npm install @swirepay-developer/reports-builder-sdk@^1.1.0
npm install react react-dom axios @heroicons/react recharts
npm install aws-amplify # Cognito mode onlyRequires npm access to the @swirepay-developer scope. See PUBLISHING.md for release steps.
Monorepo link (SDK development):
npm install file:../sdkPeer dependencies: react, react-dom, axios, @heroicons/react, recharts, aws-amplify (optional — Cognito only).
Check version: import { SDK_VERSION } from '@swirepay-developer/reports-builder-sdk'
Quick start
import {
configureReportsBuilderSdk,
configureCognitoAuth,
useAuthSDK,
EmbedDashboard,
} from '@swirepay-developer/reports-builder-sdk';
// Host app picks API environment (like Superset domain config)
configureReportsBuilderSdk({
environment: 'staging',
environments: {
local: 'http://localhost:3001',
development: 'https://reports-api.dev.example.com',
staging: 'https://reports-api.staging.example.com',
production: 'https://reports-api.example.com',
},
});
configureCognitoAuth();
function HostApp() {
const { exchangeSdkToken, isAuthenticated } = useAuthSDK();
// Call exchangeSdkToken after Cognito signIn (see Authentication below)
return isAuthenticated ? <EmbedDashboard embedId="emb_…" /> : <ConnectForm />;
}API environment
| Export | Purpose |
|--------|---------|
| configureReportsBuilderSdk({ environment, environments, apiUrl }) | Set API base URL at startup |
| setReportsBuilderApiUrl(url) | Change URL at runtime (env switcher) |
| getReportsBuilderSdkConfig() | Current { environment, apiUrl, environments } |
| sdkApi.setBaseURL(url) | Legacy — still supported, syncs config |
Runtime injection: window.__REPORTS_BUILDER_CONFIG__ = { environment, apiUrl, environments }.
Env vars: REACT_APP_REPORTS_BUILDER_ENV, REACT_APP_API_URL, REACT_APP_API_URL_STAGING, etc.
Authentication
Cognito (recommended)
Same model as Superset Middleware:
- Host app signs in with AWS Amplify (Cognito user pool).
- SDK calls
POST /api/sdk/tokenwithAuthorization: Bearer <Cognito JWT>. - Backend validates via JWKS and returns scoped app JWTs for embed/dashboard API calls.
import { configureCognitoAuth, useAuthSDK } from '@swirepay-developer/reports-builder-sdk';
import { signIn } from 'aws-amplify/auth';
configureCognitoAuth(); // reads REACT_APP_COGNITO_* or window.__RUNTIME_CONFIG__
await signIn({ username: email, password });
const { exchangeSdkToken } = useAuthSDK();
const result = await exchangeSdkToken({
scope: { embedKeys: ['emb_abc123'] },
});
// result.accessToken → used automatically by sdkApiEnvironment (host app or ECS frontend task → runtime-config.js):
| Variable | Description |
|----------|-------------|
| REACT_APP_COGNITO_USER_POOL_ID | Cognito user pool |
| REACT_APP_COGNITO_CLIENT_ID | App client ID |
| REACT_APP_COGNITO_REGION | e.g. ap-south-1 |
Runtime config keys (no REACT_APP_ prefix): COGNITO_USER_POOL_ID, COGNITO_CLIENT_ID, COGNITO_REGION.
Custom token provider (host already has Cognito tokens):
import { setCognitoTokenProvider } from '@swirepay-developer/reports-builder-sdk';
setCognitoTokenProvider(async () => existingAuth.getAccessToken());Legacy static exchange key
When Cognito is not configured:
await exchangeSdkToken({
scope: { embedKeys: ['emb_…'] },
exchangeKey: process.env.REACT_APP_SDK_EXCHANGE_KEY,
});
// or sdkApi.setSdkExchangeKey('…') before exchangeBackend must have matching SDK_TOKEN_EXCHANGE_KEY.
CORS (host app on another origin)
Call exchangeSdkToken before loading embeds, or use EmbedDashboard / useEmbedSDK (auto-exchange on load when needed). Embed data requests use the exchanged app JWT, not the Cognito token.
If the browser reports a CORS error, check the failed OPTIONS request in DevTools. Host apps with Sentry need the API to allow sentry-trace / baggage (included in current API). For non-localhost host apps in production, set backend CORS_ALLOWED_ORIGINS to your host origin(s). See docs/AUTH_AND_SDK.md.
Bootstrap with parent-supplied JWT
Skip exchange when the parent app already has an app JWT:
const { bootstrapSession } = useAuthSDK();
await bootstrapSession({
accessToken: jwtFromParent,
refreshToken: optionalRefresh,
scope: { embedKeys: ['emb_…'] },
});useAuthSDK reference
const {
user,
token,
loading,
error,
isAuthenticated,
exchangeSdkToken,
bootstrapSession,
refreshToken,
logout,
getStoredAuth,
getCurrentUser,
setAuthErrorHandler,
clearAuthData,
} = useAuthSDK();| Export | Description |
|--------|-------------|
| configureCognitoAuth({ getToken }) | Init Amplify or custom provider |
| isCognitoEnabled() | True when pool + client configured |
| getCognitoAccessToken({ forceRefresh }) | Current Cognito JWT |
| setCognitoTokenProvider(fn) | Inject token source |
Dynamic filters and search
Filters are sent as a JSON string query param:
GET /api/dashboards/:id/data?filters=[{"field":"created_at","op":"gte","value":"2025-01-01"}]&search=smith&searchVariable=customer_nameSQL templates use {{ from_date }}, {{ to_date }}, {{ search }} — see docs/FILTERS_AND_SEARCH_SAMPLES.md.
Built-in sidebar (EmbedDashboard)
Uses dashboard metadata.filters and buildServerFilters on Apply.
Full-height layout
EmbedDashboard defaults to fillHeight (measures parent/viewport height via ResizeObserver). In host apps with a header/toolbar, use a flex column layout:
<div style={{ display: 'flex', flexDirection: 'column', height: '100vh' }}>
<HostHeader />
<EmbedDashboard embedId="emb_…" className="flex-1 min-h-0" />
</div>Set fillHeight={false} and pass style={{ height: 600 }} for a fixed-height embed. Fullscreen expands the embed root only (not the entire host page).
Host-owned filters
import { useEmbedSDK, buildServerFilters } from '@swirepay-developer/reports-builder-sdk';
const { filterDefs, applyServerFilters, searchData } = useEmbedSDK({ embedId: 'emb_…' });
const filterValues = {
'filter-date': { from: '2025-01-01', to: '2025-12-31' },
'filter-region': ['US', 'UK'],
};
await applyServerFilters(buildServerFilters(filterDefs, filterValues));
await searchData('alice', 'customer_name'); // keeps active filtersDirect API
await sdkApi.getDashboardData(dashboardId, {
filters: [
{ field: 'region', op: 'in', value: ['US'] },
{ field: 'created_at', op: 'gte', value: '2025-01-01' },
],
search: 'smith',
searchVariable: 'customer_name',
});Components and hooks
| Export | Purpose |
|--------|---------|
| EmbedDashboard | Full embed UI with optional filter sidebar |
| DashboardEmbedder | Dashboard by ID |
| useEmbedSDK | Embed data, filters, search |
| useDashboardSDK | Dashboard by ID + data |
| useSearchSDK | Search state helper |
| FilterSidebar, buildServerFilters | Filter UI + server filter builder |
| sdkApi | Low-level HTTP client |
AWS ECS (host apps)
Configure Cognito on the frontend ECS task (same pool as backend). The SDK reads window.__RUNTIME_CONFIG__ generated at container start.
See deploy/README.md and docs/AUTH_AND_SDK.md.
Sample app
../sample-app/ demonstrates Cognito sign-in, token exchange, embed demo, host filters, and SDK sidebar modes.
cd sample-app && cp .env.example .env.local && npm install && npm start