React SDK
First-class React/Next.js integration. Install the SDK package, wrap your app with a provider, and render engagements with full TypeScript support, eligibility checks, and event callbacks.
Installation
npm install @bricqs/sdk-react @bricqs/sdk-coreOr with yarn / pnpm:
yarn add @bricqs/sdk-react @bricqs/sdk-core
# or
pnpm add @bricqs/sdk-react @bricqs/sdk-coreProvider Setup
Wrap your application (or a section of it) with BricqsProvider. This initializes the SDK client, manages sessions, and provides context to all child components and hooks.
import { BricqsProvider } from '@bricqs/sdk-react';
function App() {
return (
<BricqsProvider
config={{
apiKey: 'bq_live_YOUR_KEY',
}}
>
<YourApp />
</BricqsProvider>
);
}import { BricqsProvider } from '@bricqs/sdk-react';
function App() {
const { user } = useAuth(); // Your auth system
return (
<BricqsProvider
config={{
apiKey: 'bq_live_YOUR_KEY',
userId: user?.id,
userName: user?.displayName,
userEmail: user?.email,
}}
>
<YourApp />
</BricqsProvider>
);
}| Config Option | Type | Description |
|---|---|---|
apiKey | string | Required. Your API key from Settings → API Keys. |
userId | string | Your user ID. Links sessions across devices for identified users. |
userName | string | Display name for leaderboards and social features. |
userEmail | string | User email for reward delivery. |
apiUrl | string | API base URL. Defaults to https://api.bricqs.ai. Override for self-hosted or staging. |
debug | boolean | Enable verbose console logging for development. |
Rendering Engagements
Use the BricqsEngagement component to render a published engagement. It creates a managed iframe with auto-resize and event forwarding.
import { BricqsEngagement } from '@bricqs/sdk-react';
function CampaignPage() {
return (
<BricqsEngagement
id="YOUR_ENGAGEMENT_UUID"
onComplete={(result) => {
console.log('Engagement completed!', result);
}}
onActivityComplete={(data) => {
console.log('Activity done:', data.activityType, data.score);
}}
onPointsAwarded={({ points, newBalance }) => {
console.log(`+${points} points! Balance: ${newBalance}`);
}}
onBadgeUnlocked={({ badgeName, badgeCode }) => {
showToast(`Badge earned: ${badgeName}`);
}}
onRewardClaimed={({ rewardName, codeValue, expiresAt }) => {
showCouponModal(rewardName, codeValue);
}}
onTierChanged={({ tierName, tierLevel }) => {
showCelebration(`Welcome to ${tierName}!`);
}}
style={{ maxWidth: 640, margin: '0 auto' }}
className="my-engagement"
/>
);
}| Prop | Type | Description |
|---|---|---|
id | string | Required. Engagement UUID. |
onComplete | function | Called when the entire engagement is completed. |
onActivityComplete | function | Called when an individual activity (quiz, form, etc.) completes. |
onPointsAwarded | function | Called when points are awarded to the participant. |
onBadgeUnlocked | function | Called when a badge is unlocked. |
onRewardClaimed | function | Called when a reward (coupon, voucher, etc.) is claimed. |
onTierChanged | function | Called when the participant's tier changes. |
onError | function | Called on load or runtime errors. |
style | CSSProperties | Inline styles applied to the container div. |
className | string | CSS class applied to the container div. |
Eligibility & Trigger Rules
The React SDK supports eligibility checks — decide whether to show an engagement based on conditions like URL patterns, user attributes, time windows, and frequency caps.
import { useEligibility } from '@bricqs/sdk-react';
function ConditionalEngagement() {
const { isEligible, isLoading, reason } = useEligibility({
engagementId: 'YOUR_UUID',
context: {
url: window.location.href,
referrer: document.referrer,
userAgent: navigator.userAgent,
},
});
if (isLoading) return <Spinner />;
if (!isEligible) return null; // Don't render
return <BricqsEngagement id="YOUR_UUID" />;
}BricqsSpot combines eligibility checking with rendering in a single component. Place it anywhere in your app and it will only render if the engagement is eligible for the current context.
import { BricqsSpot } from '@bricqs/sdk-react';
function ProductPage() {
return (
<div>
<h1>Product Details</h1>
<ProductInfo />
{/* Only renders if the engagement is eligible */}
<BricqsSpot
engagementId="YOUR_UUID"
trigger={{
url: '/products/*', // URL pattern match
minTimeOnPage: 10, // Wait 10 seconds
scrollDepth: 50, // 50% scroll depth
maxImpressions: 3, // Show max 3 times
maxImpressionsWindow: 'day', // Per day
}}
placement="inline" // 'inline' | 'modal' | 'slide-in'
onDismiss={() => console.log('User dismissed')}
onImpression={() => analytics.track('bricqs_impression')}
/>
</div>
);
}| Trigger Rule | Type | Description |
|---|---|---|
url | string | Glob pattern matched against the current URL path (e.g. /products/*). |
minTimeOnPage | number | Seconds the user must spend on the page before showing. |
scrollDepth | number | Minimum scroll percentage (0-100) before showing. |
maxImpressions | number | Maximum times to show the engagement. |
maxImpressionsWindow | string | Time window for impression limit: session, day, week, month, lifetime. |
userAttribute | object | Match on user attributes: { key, operator, value }. |
schedule | object | Time-based rules: { startDate, endDate, daysOfWeek, timeRange }. |
Available Hooks
The React SDK exports hooks for accessing Bricqs data and state. These are available within a BricqsProvider context.
useBricqsClient()
Access the underlying BricqsClient instance for direct API calls.
useEligibility(options)
Check if an engagement should be shown based on trigger rules, frequency caps, and eligibility conditions.
usePoints(options)
Access points balance, transaction history, and tier info. Auto-refreshes on points:awarded events.
useBricqsEvents()
Subscribe to real-time SDK events (activity completions, points, badges, rewards).
useQuiz, useSpinWheel, useForm, useBadges, useChallenge, and more. See the Headless SDK page.Next.js Integration
The SDK works with both the Pages Router and App Router. Since the provider uses React context and browser APIs, it must run on the client.
'use client';
import { BricqsProvider } from '@bricqs/sdk-react';
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html>
<body>
<BricqsProvider config={{ apiKey: process.env.NEXT_PUBLIC_BRICQS_KEY! }}>
{children}
</BricqsProvider>
</body>
</html>
);
}import { BricqsProvider } from '@bricqs/sdk-react';
import type { AppProps } from 'next/app';
export default function App({ Component, pageProps }: AppProps) {
return (
<BricqsProvider config={{ apiKey: process.env.NEXT_PUBLIC_BRICQS_KEY! }}>
<Component {...pageProps} />
</BricqsProvider>
);
}.env.local as NEXT_PUBLIC_BRICQS_KEY=bq_live_xxx. The NEXT_PUBLIC_ prefix makes it available on the client side.TypeScript Support
The SDK ships with complete TypeScript definitions. All props, events, and return types are fully typed.
import type {
BricqsConfig,
EngagementResult,
ActivityResult,
PointsAwardedEvent,
BadgeUnlockedEvent,
RewardClaimedEvent,
TierChangedEvent,
EligibilityResult,
TriggerConfig,
} from '@bricqs/sdk-react';
// All event callbacks are fully typed
const handlePoints = (event: PointsAwardedEvent) => {
// event.points: number
// event.newBalance: number
// event.reason: string
};
const handleReward = (event: RewardClaimedEvent) => {
// event.rewardName: string
// event.rewardType: 'coupon' | 'voucher' | 'physical' | 'digital'
// event.codeValue: string
// event.expiresAt: string | null
};Full Example
A complete React app with Bricqs integration — engagement rendering, event handling, and points display.
import { BricqsProvider, BricqsEngagement, usePoints } from '@bricqs/sdk-react';
function App() {
return (
<BricqsProvider config={{ apiKey: 'bq_live_YOUR_KEY' }}>
<div className="app">
<Header />
<CampaignPage />
</div>
</BricqsProvider>
);
}
function Header() {
const { balance } = usePoints({ engagementId: 'YOUR_UUID' });
return (
<header>
<h1>My App</h1>
<span>{balance} points</span>
</header>
);
}
function CampaignPage() {
return (
<main>
<h2>Today's Challenge</h2>
<BricqsEngagement
id="YOUR_ENGAGEMENT_UUID"
onPointsAwarded={({ points }) => {
// Points display auto-updates via usePoints hook
showToast(`+${points} points!`);
}}
onRewardClaimed={({ rewardName, codeValue }) => {
showCouponModal(rewardName, codeValue);
}}
onComplete={() => {
router.push('/thank-you');
}}
/>
</main>
);
}