@coframe/sdk
v1.1.16
Published
Coframe optimizes your website using generative AI to deliver maximum impact to your audience and allow your site to improve itself as you sleep. Learn more at coframe.com.
Readme
@coframe/sdk
Bring your UX to life with AI-powered optimization and personalization.
Coframe helps you personalize and optimize your site with experiments, targeting, anti-flicker rendering, analytics callbacks, and conversion tracking.
This package exposes three entry points:
@coframe/sdkfor the browser runtime@coframe/sdk/serverfor SSR and edge prefetching@coframe/sdk/reactfor React apps
Install
npm install @coframe/sdkIf you use the React entry point, install React as well:
npm install react@">=17"Quick start
Browser
import { init } from '@coframe/sdk'
await init({
config: {
projectId: 'your-project-id',
},
})init() accepts config and optional projectData, so npm consumers do not need to manually populate window.CFQ first.
URL controls
The npm entry uses the same browser URL controls as the script-tag and Edge installations:
cf_disableskips initialization and reveals any antiflicker state.coframe_variant_idpreviews one or more comma-separated variant IDs.coframe_should_send_events=trueallows events during preview for testing.
Debug tools are allowed by default. Open the Launcher with cf_preview=true and
use Keep across navigation in the Preview Session tool to keep the selected
variants active for the current tab. Set enableDebug: false to prevent URL or
saved session state from loading the Launcher.
For SSR, pass the complete request URL, including its query string, as
currentUrl. This is required for query-sensitive targeting and allows
getProjectData() to short-circuit before any request when cf_disable is
present.
React
import { CoframeProvider } from '@coframe/sdk/react'
import type { CoframeConfig } from '@coframe/sdk'
const projectConfig: CoframeConfig = {
projectId: 'your-project-id',
}
export default function App({ children }) {
return (
<CoframeProvider projectConfig={projectConfig}>
{children}
</CoframeProvider>
)
}Mount the provider once at the root of your app. It initializes the SDK on mount and keeps treatment state available to child components. Keep it mounted across client-side route changes; runtime commands and the SDK's navigation observer handle subsequent page changes without remounting it.
Server prefetch
import { getProjectData } from '@coframe/sdk/server'
const serverData = await getProjectData({
projectId: 'your-project-id',
currentUrl: request.url,
headers: request.headers,
})
const projectData = serverData?.project
? {
project: serverData.project,
personalizationHeaders: serverData.personalizationHeaders,
}
: undefinedPass projectData into <CoframeProvider> to avoid the extra client-side project fetch and personalize on first paint.
Common React usage
Read variants in components
'use client'
import { useCoframeVariant } from '@coframe/sdk/react'
export function CheckoutPage() {
const variant = useCoframeVariant('checkout_flow_v2')
if (variant === undefined) return <CheckoutSkeleton />
if (variant === 'treatment') return <NewCheckout />
return <OldCheckout />
}Other hooks:
useCoframeTreatments()returns all treatments ornullwhile init is in flightuseCoframeTreatment(experimentId)returns one treatment payload
Track conversions
'use client'
import { trackConversion } from '@coframe/sdk'
export function CheckoutButton() {
return (
<button
onClick={() =>
trackConversion({
metricName: 'checkout_complete',
value: 99.95,
})
}
>
Complete checkout
</button>
)
}Analytics and log callbacks
import { CoframeProvider } from '@coframe/sdk/react'
<CoframeProvider
projectConfig={projectConfig}
onTreatmentAppliedBulkV2={(data) => {
for (const treatment of data) {
analytics.track('Experiment Viewed', treatment)
}
}}
onLog={(payload) => {
console.error('[coframe]', payload.monitoring_type, payload)
}}
>
{children}
</CoframeProvider>If your privacy policy permits treatment analytics before cookie consent, use
onTreatmentAppliedBulkV2WithoutConsent instead. It has the same callback
arguments and does not fire again when consent is later granted.
Outside React, you can also register callbacks from the main entry:
import { onLog, onTreatmentApplied } from '@coframe/sdk'Next.js / Remix / SSR notes
getProjectData()is intended for SSR and edge runtimes that can provide a full request URL and request headers.- In Pages Router or Remix, per-request server loaders are the most straightforward place to call it.
- In App Router, keep the provider mounted in a persistent shell, but be careful about request URL handling in
layout.tsxif you need query-sensitive SSR targeting. - The npm runtime reveals antiflicker styles but cannot insert them early enough to protect the initial paint. Render
antiflickerCSSfromgetProjectData()in the server document head, or place equivalent static CSS and a timeout fallback there before application content.
Package layout
The published tarball contains only dist/pkg/:
dist/pkg/
├── cf.esm.mjs cf.cjs.js types/index.d.ts ← @coframe/sdk
├── server.esm.mjs server.cjs.js types/server.d.ts ← @coframe/sdk/server
└── react.esm.mjs react.cjs.js types/react.d.ts ← @coframe/sdk/reactTypeScript compatibility
The package publishes typed subpath exports for:
@coframe/sdk@coframe/sdk/server@coframe/sdk/react
If your app uses an older TypeScript module resolution mode, prefer moving to one of:
moduleResolution: "bundler"moduleResolution: "node16"moduleResolution: "nodenext"
Modern resolution modes handle package subpath exports more reliably.
API overview
@coframe/sdk
init(options)trackConversion(payload)setConsent(enabled)setUserToken(token)setFeatureFlag(enabled)setPageHydrated()onTreatmentApplied(...)onLog(...)
@coframe/sdk/server
getProjectData(options)
Returns a payload that may include:
projectpersonalizationHeadersantiflickerCSS
@coframe/sdk/react
CoframeProvideruseCoframeTreatments()useCoframeTreatment(experimentId)useCoframeVariant(experimentId)
