diff --git a/.generated/sdk-docs/browser-sdk/v1.json b/.generated/sdk-docs/browser-sdk/v1.json new file mode 100644 index 0000000..609649d --- /dev/null +++ b/.generated/sdk-docs/browser-sdk/v1.json @@ -0,0 +1,11 @@ +{ + "sourceRepository": "https://github.com/reflagcom/javascript", + "sourceCommit": "b4fe5b3d9386b87c6546175c323862d9878e1430", + "package": "@reflag/browser-sdk", + "version": "1.7.4", + "files": { + "legacy/v1/browser-sdk/README.md": "f532502e44f9d999d2c19c238538df3d8e7985c47b62eee058a89291562e7126", + "legacy/v1/browser-sdk/globals.md": "bc8ad724e3dea10a0ed618bdc91a1fa26617e0505675dd0edbd93c84516aa3b2", + "legacy/v1/browser-sdk/feedback.md": "968e3d393e91c5a1e98d8dfad2ed225e4b3a477ad33aabce23d971a786896cfb" + } +} diff --git a/.generated/sdk-docs/browser-sdk/v2.json b/.generated/sdk-docs/browser-sdk/v2.json new file mode 100644 index 0000000..bd51971 --- /dev/null +++ b/.generated/sdk-docs/browser-sdk/v2.json @@ -0,0 +1,14 @@ +{ + "sourceRepository": "https://github.com/reflagcom/javascript", + "sourceCommit": "ed0e7725719756855c20e939265713914e956b8b", + "package": "@reflag/browser-sdk", + "version": "2.0.0-next.0", + "files": { + "supported-languages/browser-sdk/README.md": "74c3b73ac4a3cfbdef57a1eadff0da041b7f6d39db3697b480e6e8b69afae74b", + "sdk/@reflag/browser-sdk/README.md": "f29ed94303254887c39f995588e85481c851873f78ef6d62e8ce24ecd109f133", + "supported-languages/browser-sdk/globals.md": "4a3be858a621eb3839408d759329a60ab2ea406d0e21174b44b0639c678a1ffc", + "sdk/@reflag/browser-sdk/globals.md": "a60d58526686dcc14ea5cdcecfa1d17388aff78f198f97f41bd667d35c7c39aa", + "supported-languages/browser-sdk/feedback.md": "2a2a3aa124d872970a7b2303b3318b21d675faf1c414525b2e62b31d3f2eb90d", + "sdk/documents/browser-sdk/FEEDBACK.md": "552bee6f6059a5c27a7be36a60e5fc071bd6e95af66bbd6ba45f98aaf29a8478" + } +} diff --git a/.generated/sdk-docs/node-sdk/v1.json b/.generated/sdk-docs/node-sdk/v1.json new file mode 100644 index 0000000..5b20144 --- /dev/null +++ b/.generated/sdk-docs/node-sdk/v1.json @@ -0,0 +1,12 @@ +{ + "sourceRepository": "https://github.com/reflagcom/javascript", + "sourceCommit": "b4fe5b3d9386b87c6546175c323862d9878e1430", + "package": "@reflag/node-sdk", + "version": "1.8.3", + "files": { + "legacy/v1/_media/type-check-failed.png": "f04547c0bf0425bcf554aa1a1dddec56096ca9967d120bdca7737562327d4db8", + "legacy/v1/_media/type-check-payload-failed.png": "8b53c24ecd19288111bda14eab7c490f7e26abba569eea11e16504cc7abeb54a", + "legacy/v1/node-sdk/README.md": "603af9b3c555078fa053e66134670b1e4d55150a340457a90d84e7f97376f57a", + "legacy/v1/node-sdk/globals.md": "0ada91a1c29fac51f779c1694e60c1a72cb96241438f17d531b1786ea1ee3ad1" + } +} diff --git a/.generated/sdk-docs/node-sdk/v2.json b/.generated/sdk-docs/node-sdk/v2.json new file mode 100644 index 0000000..072bf64 --- /dev/null +++ b/.generated/sdk-docs/node-sdk/v2.json @@ -0,0 +1,12 @@ +{ + "sourceRepository": "https://github.com/reflagcom/javascript", + "sourceCommit": "81297fbca156feadd3e666188f5141f42e0488dd", + "package": "@reflag/node-sdk", + "version": "2.0.0-next.0", + "files": { + "supported-languages/node-sdk/README.md": "e82d3aecfc0bb3ec11b48c7a16337fd1c585b57d37be35e3cbffe24c4dbd0136", + "sdk/@reflag/node-sdk/README.md": "ee5d3ffa7fb8e845737022fc35265c87fefc9c1d6085d87939d06395d086ff88", + "supported-languages/node-sdk/globals.md": "e1fc21f052e69b74582782ac7133513b077f328294f674523f087e4846338815", + "sdk/@reflag/node-sdk/globals.md": "3fc142c7e452af2515b11c7efafa34d81bfe887f29ad1e2d6c81d31fb6736cc3" + } +} diff --git a/.generated/sdk-docs/react-native-sdk/v0.json b/.generated/sdk-docs/react-native-sdk/v0.json new file mode 100644 index 0000000..6d15756 --- /dev/null +++ b/.generated/sdk-docs/react-native-sdk/v0.json @@ -0,0 +1,13 @@ +{ + "sourceRepository": "https://github.com/reflagcom/javascript", + "sourceCommit": "b4fe5b3d9386b87c6546175c323862d9878e1430", + "package": "@reflag/react-native-sdk", + "version": "0.3.7", + "files": { + "supported-languages/react-native-sdk/README.md": "2ae69a40046d515f59ffd90e3eb8c18c159d582e74aa55bf96defa63228f0424", + "sdk/@reflag/react-native-sdk/README.md": "ecf2a23a9ca454ec7f3bd9dbe5e4664d9a93e0a7a1b4ca35637295ec22084b8b", + "sdk/documents/react-native-sdk/README.md": "ecf2a23a9ca454ec7f3bd9dbe5e4664d9a93e0a7a1b4ca35637295ec22084b8b", + "supported-languages/react-native-sdk/globals.md": "66043acd9330431cec1ebf8b46f856f713890742f13705e0177f151cd00ed12a", + "sdk/@reflag/react-native-sdk/globals.md": "d6bcb900cee614d69e4ef8b5c771a723bbc26ba94dce356708398b4f77015e01" + } +} diff --git a/.generated/sdk-docs/react-sdk/v1.json b/.generated/sdk-docs/react-sdk/v1.json new file mode 100644 index 0000000..7af01dc --- /dev/null +++ b/.generated/sdk-docs/react-sdk/v1.json @@ -0,0 +1,10 @@ +{ + "sourceRepository": "https://github.com/reflagcom/javascript", + "sourceCommit": "b4fe5b3d9386b87c6546175c323862d9878e1430", + "package": "@reflag/react-sdk", + "version": "1.7.4", + "files": { + "legacy/v1/react-sdk/README.md": "843ed048847c9a84a904f3ac2b9a0a10c17bc954f7b55e9271d02bd8804eb70c", + "legacy/v1/react-sdk/globals.md": "821f640a266168ef35f25114b6a99f4abf80af5aaae9461e2188749526a5eb20" + } +} diff --git a/.generated/sdk-docs/react-sdk/v2.json b/.generated/sdk-docs/react-sdk/v2.json new file mode 100644 index 0000000..03df1fa --- /dev/null +++ b/.generated/sdk-docs/react-sdk/v2.json @@ -0,0 +1,13 @@ +{ + "sourceRepository": "https://github.com/reflagcom/javascript", + "sourceCommit": "ed0e7725719756855c20e939265713914e956b8b", + "package": "@reflag/react-sdk", + "version": "2.0.0-next.0", + "files": { + "supported-languages/react-sdk/README.md": "745947496f5c82508124461e0d0e9e29d3182cdfd7155f79a59fa9387e1b060e", + "sdk/@reflag/react-sdk/README.md": "ef70d89d71d5f52d0adea0163fda82658fc8ec5fb0096fcd2c8424e009307478", + "sdk/documents/react-sdk/README.md": "ef70d89d71d5f52d0adea0163fda82658fc8ec5fb0096fcd2c8424e009307478", + "supported-languages/react-sdk/globals.md": "f414859dd7cc94089d06f27613e1c554e3e3d5f049a9a141c2590058af768b1a", + "sdk/@reflag/react-sdk/globals.md": "4cf0d20cca9c19d3998d9c5d0f6670d17d6782c24ee0ccd25e1d34100f42fcc6" + } +} diff --git a/.generated/sdk-docs/vue-sdk/v1.json b/.generated/sdk-docs/vue-sdk/v1.json new file mode 100644 index 0000000..00720c5 --- /dev/null +++ b/.generated/sdk-docs/vue-sdk/v1.json @@ -0,0 +1,10 @@ +{ + "sourceRepository": "https://github.com/reflagcom/javascript", + "sourceCommit": "b4fe5b3d9386b87c6546175c323862d9878e1430", + "package": "@reflag/vue-sdk", + "version": "1.5.7", + "files": { + "legacy/v1/vue-sdk/README.md": "831dc43f40a1d4248d9c17211c9bc00383778877270f8fe2cacb01dc5659f9fc", + "legacy/v1/vue-sdk/globals.md": "9cbe3d8a579e34b6126860052479464e274b0ef3069bfc3752e46ca49d59e8ac" + } +} diff --git a/.generated/sdk-docs/vue-sdk/v2.json b/.generated/sdk-docs/vue-sdk/v2.json new file mode 100644 index 0000000..2f33800 --- /dev/null +++ b/.generated/sdk-docs/vue-sdk/v2.json @@ -0,0 +1,12 @@ +{ + "sourceRepository": "https://github.com/reflagcom/javascript", + "sourceCommit": "ed0e7725719756855c20e939265713914e956b8b", + "package": "@reflag/vue-sdk", + "version": "2.0.0-next.0", + "files": { + "supported-languages/vue-sdk/README.md": "b50eddc96c442532d6734450e068153da3778c47d98d028dcf1ff36f1e67c530", + "sdk/@reflag/vue-sdk/README.md": "8b256ff3e64959521508bc74a4b3d0d36873f65c797ee8bc00764875b819768f", + "supported-languages/vue-sdk/globals.md": "968ec7df896ee2e78d1d23578acfadfc3378bd511b15c55eca79b6558588727f", + "sdk/@reflag/vue-sdk/globals.md": "73ceaa29875b0d33a02dcfbf12cf1e50644b51d871cc496681bdbcbeee56ab2d" + } +} diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..08038a7 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,9 @@ +# Generated SDK copies; authoritative READMEs/comments live in reflagcom/javascript. +sdk/** linguist-generated=true +supported-languages/browser-sdk/** linguist-generated=true +supported-languages/react-sdk/** linguist-generated=true +supported-languages/vue-sdk/** linguist-generated=true +supported-languages/node-sdk/** linguist-generated=true +supported-languages/react-native-sdk/** linguist-generated=true +legacy/v1/*-sdk/** linguist-generated=true +.generated/** linguist-generated=true diff --git a/.github/README.md b/.github/README.md index bf0ec1c..bbaa4b8 100644 --- a/.github/README.md +++ b/.github/README.md @@ -17,6 +17,22 @@ Reflag is built to work at the company/organization level right out of the box, This repository syncs the documentation to [docs.reflag.com](https://docs.reflag.com). For SDK docs, please go to the [javascript repository](https://github.com/reflagcom/javascript) repository. +## SDK documentation ownership + +SDK READMEs and source comments are maintained in `reflagcom/javascript`. Current Browser/React/Vue/Node pages are generated into `supported-languages/`; protocol-v1 pages live in `legacy/v1/`. Do not hand-edit their generated bodies. Source/version and file hashes are recorded in `.generated/sdk-docs/`. Current pages assume a new installation. The importer adds one short SDK v2 scope line after the introduction and a legacy/upgrade link at the end; these site-only notes are reapplied on every source sync. Prerelease availability and major-pinned upgrade commands belong in the migration guide. Keep release-readiness status in PRs and the migration guide, not repeated page banners. + +Generate one SDK from an explicitly selected, clean source checkout after building declarations and running its canonical `docs.sh`: + +```sh +node .github/scripts/sdk-docs.mjs import --source /path/to/built/javascript --package react-sdk +node .github/scripts/check-sdk-docs.mjs +node --test .github/scripts/sdk-docs.test.mjs +``` + +The importer derives the destination from the package major, preserves historical SDK aliases, and never deletes a tree or overwrites navigation, migration guidance or GitBook settings. Release automation uses the `release` subcommand with an exact tagged-source plan; prereleases do not promote stable documentation automatically. The SDK documentation workflow rebuilds the source commits listed in the manifests and checks representative examples against matching declarations. + +This is ordinary page-based navigation. No GitBook variants or additional published spaces are required. + ## Quick links - Ready to get started? [Follow the guide](https://docs.reflag.com/) diff --git a/.github/scripts/check-sdk-docs.mjs b/.github/scripts/check-sdk-docs.mjs new file mode 100644 index 0000000..e932663 --- /dev/null +++ b/.github/scripts/check-sdk-docs.mjs @@ -0,0 +1,255 @@ +import assert from "node:assert/strict"; +import fs from "node:fs"; +import path from "node:path"; +import { fileURLToPath, pathToFileURL } from "node:url"; +import { currentVersionNote, docsPath, hash, webSDKs, documentedPackages } from "./sdk-docs.mjs"; + +export const root = path.resolve(fileURLToPath(new URL("../../", import.meta.url))); +const read = (base, file) => fs.readFileSync(path.join(base, file), "utf8"); +export const prose = (content) => content.replace(/```[^\n]*\n[\s\S]*?```/g, ""); +export const links = (content) => + [ + ...prose(content).matchAll( + /\[[^\]]*\]\(([^\s)]+)(?:\s+"[^"]*")?\)|(?:src|href)=["']([^"']+)["']/g, + ), + ].map((match) => match[1] ?? match[2]); +const slug = (text) => + text + .toLowerCase() + .replace(/<\/?(?:a|code|strong|em|span|br)(?:\s[^>]*)?>/g, "") + .replace(/[^\p{L}\p{N}_ -]/gu, "") + .replace(/ /g, "-"); + +export function anchors(content) { + const ids = new Set(); + for (const match of prose(content).matchAll(/\bid=["']([^"']+)["']/g)) ids.add(match[1]); + const headingIDs = new Set(); + for (const match of prose(content).matchAll(/^#{1,6} (.+)$/gm)) { + const base = slug(match[1]); + let id = base; + for (let suffix = 1; headingIDs.has(id); suffix++) id = `${base}-${suffix}`; + headingIDs.add(id); + ids.add(id); + } + return ids; +} + +function resolveLink(base, file, href) { + const [pathname, fragment] = href.split("#"); + let target = path.resolve( + base, + path.dirname(file), + decodeURIComponent(pathname || path.basename(file)), + ); + assert(target.startsWith(`${base}${path.sep}`), `Link escapes repository: ${file} -> ${href}`); + if (fs.existsSync(target) && fs.statSync(target).isDirectory()) + target = path.join(target, "README.md"); + return { target, fragment }; +} + +export function checkLinks(base, pages) { + const errors = []; + for (const file of pages) { + for (const href of links(read(base, file))) { + if (/^(?:[a-z][a-z\d+.-]*:|\/|\{)/i.test(href)) continue; + try { + const { target, fragment } = resolveLink(base, file, href); + assert(fs.existsSync(target), `Missing file: ${file} -> ${href}`); + if (fragment && target.endsWith(".md")) + assert( + anchors(fs.readFileSync(target, "utf8")).has(decodeURIComponent(fragment)), + `Missing anchor: ${file} -> ${href}`, + ); + } catch (error) { + errors.push(error.message); + } + } + } + assert.equal(errors.length, 0, errors.join("\n")); +} + +export function sourceMatrix(base = root) { + const commits = new Map(); + for (const name of fs.readdirSync(path.join(base, ".generated/sdk-docs"))) { + assert(documentedPackages.includes(name), `Unknown generated owner: ${name}`); + for (const filename of fs.readdirSync(path.join(base, ".generated/sdk-docs", name))) { + const manifest = JSON.parse(read(base, `.generated/sdk-docs/${name}/${filename}`)); + assert(/^[a-f\d]{40}$/.test(manifest.sourceCommit), "Invalid SDK source ref"); + const packages = commits.get(manifest.sourceCommit) ?? new Set(); + packages.add(name); + commits.set(manifest.sourceCommit, packages); + } + } + return { + include: [...commits].map(([ref, packages]) => ({ + ref, + packages: [...packages] + .sort() + .map((name) => `--package ${name}`) + .join(" "), + })), + }; +} + +export function checkCurrentPagePresentation(content, file) { + const notes = [...content.matchAll(/^Using v1\? .+$/gm)]; + assert.equal(notes.length, 1, `Expected one succinct version note: ${file}`); + assert(content.trimEnd().endsWith(notes[0][0]), `Legacy link must be at the end: ${file}`); + const body = prose(content); + assert.equal( + body.split("\n").filter((line) => line === currentVersionNote).length, + 1, + `Expected one SDK v2 scope note: ${file}`, + ); + const title = /^# .+$/m.exec(body); + const firstSection = /^#{2,6} /m.exec(body); + const scope = body.indexOf(currentVersionNote); + assert( + title && scope > title.index + title[0].length && scope < (firstSection?.index ?? body.length), + `SDK v2 scope note must be in the introduction: ${file}`, + ); + assert(!content.includes("**Protocol v2"), `Repeated protocol banner: ${file}`); + assert(!content.includes("Prerelease source documentation"), `Repeated release warning: ${file}`); + assert(!content.includes("Generated from ["), `Provenance belongs in the manifest: ${file}`); + for (const line of content.split("\n")) + if ( + /^\s*(?:npm (?:i|install)|yarn add|pnpm add|bun add|deno add|npx)\b|cdn\.jsdelivr\.net/.test( + line, + ) + ) + assert( + !/@reflag\/(?:node-sdk|browser-sdk|react-sdk|vue-sdk|cli)@2\b/.test(line), + `Major-pinned installs belong in the upgrade guide: ${file}`, + ); +} + +export function checkSDKDocs(base = root) { + const summary = read(base, "SUMMARY.md"); + const supported = /^## Supported languages\n([\s\S]*?)(?=\n## )/m.exec(summary)?.[1]; + assert(supported, "Missing Supported languages section"); + assert.equal( + links(supported).at(-1), + "supported-languages/migrating-from-v1.md", + "Migration guide must be last in Supported languages", + ); + const navigation = links(summary).filter((href) => !/^[a-z][a-z\d+.-]*:/i.test(href)); + assert.equal(new Set(navigation).size, navigation.length, "Duplicate navigation entry"); + const generated = new Set(); + const owners = new Map(); + for (const name of fs.readdirSync(path.join(base, ".generated/sdk-docs"))) { + for (const filename of fs.readdirSync(path.join(base, ".generated/sdk-docs", name))) { + const manifest = JSON.parse(read(base, `.generated/sdk-docs/${name}/${filename}`)); + assert.equal(manifest.package, `@reflag/${name}`); + assert(/^[a-f\d]{40}$/.test(manifest.sourceCommit), "Missing exact source commit"); + for (const [file, expected] of Object.entries(manifest.files)) { + const actual = hash(fs.readFileSync(path.join(base, file))); + assert.equal(actual, expected, `Generated file drift: ${file}`); + assert(!owners.has(file) || owners.get(file) === actual, `Conflicting ownership: ${file}`); + owners.set(file, actual); + if (file.endsWith(".md")) { + assert( + !/^Generated from\b/im.test(read(base, file)), + `Provenance belongs in the manifest: ${file}`, + ); + generated.add(file); + } + } + } + } + for (const major of [1, 2]) + for (const name of webSDKs) { + for (const filename of [ + "README.md", + "globals.md", + ...(name === "browser-sdk" ? ["feedback.md"] : []), + ]) { + const file = docsPath(name, major, filename); + assert(navigation.includes(file), `SDK page missing from navigation: ${file}`); + assert(generated.has(file), `SDK page has no source manifest: ${file}`); + const content = read(base, file); + const counterpart = docsPath(name, major === 1 ? 2 : 1, filename); + assert( + links(content).some((href) => { + if (/^(?:[a-z][a-z\d+.-]*:|\/)/i.test(href)) return false; + return path.relative(base, resolveLink(base, file, href).target) === counterpart; + }), + `Missing equivalent-version link: ${file}`, + ); + if (major === 2) checkCurrentPagePresentation(content, file); + if (major === 1) { + assert(content.includes("Protocol v1 — legacy")); + assert( + !/cdn\.jsdelivr\.net\/npm\/@reflag\/browser-sdk@(?!1\b)/.test(content), + "Legacy CDN must target v1", + ); + for (const line of content.split("\n")) + if (/^\s*(?:npm (?:i|install)|yarn add|pnpm add|bun add|deno add|npx)\b/.test(line)) { + for (const match of line.matchAll( + /@reflag\/(?:node-sdk|browser-sdk|react-sdk|vue-sdk|cli)(?:@([^\s]+))?/g, + )) + assert.equal(match[1], "1", `Unpinned legacy install: ${file}: ${line}`); + } + } + } + } + const shared = navigation.filter( + (file) => + !generated.has(file) && + !file.startsWith("legacy/") && + !file.startsWith("api/") && + !file.endsWith("globals.md") && + !file.includes("react-native-sdk") && + file !== "supported-languages/migrating-from-v1.md", + ); + for (const file of shared) { + const content = read(base, file); + assert( + !/\{\s*(?:isEnabled|config\s*:)[^\n]*\}\s*=\s*(?:useFlag|.*\.getFlag)\(/.test(content), + `Legacy wrapper in shared example: ${file}`, + ); + assert(!content.includes("../sdk/v2/"), `Obsolete SDK preview link: ${file}`); + if (file === "supported-languages/next.js.md") checkCurrentPagePresentation(content, file); + for (const line of content.split("\n")) + if (/^\s*(?:npm (?:i|install)|yarn add|pnpm add|bun add|deno add|npx)\b/.test(line)) + assert( + !/@reflag\/[a-z-]+@2\b/.test(line), + `Major-pinned installs belong in the upgrade guide: ${file}`, + ); + } + // Existing unrelated handbook anchors are not a gate for generated SDK output. + // New SDK links, migration/overview links and all navigation must resolve. + checkLinks(base, [ + "SUMMARY.md", + ...generated, + "legacy/v1/README.md", + "supported-languages/migrating-from-v1.md", + "supported-languages/overview.md", + ...shared.filter((file) => + [ + "README.md", + "supported-languages/next.js.md", + "product-handbook/service-resiliency.md", + "product-handbook/type-safety.md", + "product-handbook/remote-config.md", + "product-handbook/multivariate-flags.md", + ].includes(file), + ), + ]); + return { generatedPages: generated.size, navigationPages: navigation.length }; +} + +if (process.argv[1] && import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href) { + console.log(JSON.stringify(checkSDKDocs(), null, 2)); + if (process.argv.includes("--sources")) { + const outputs = { + matrix: JSON.stringify(sourceMatrix()), + react_v1_ref: JSON.parse(read(root, ".generated/sdk-docs/react-sdk/v1.json")).sourceCommit, + react_v2_ref: JSON.parse(read(root, ".generated/sdk-docs/react-sdk/v2.json")).sourceCommit, + node_v2_ref: JSON.parse(read(root, ".generated/sdk-docs/node-sdk/v2.json")).sourceCommit, + }; + if (process.env.GITHUB_OUTPUT) + for (const [key, value] of Object.entries(outputs)) + fs.appendFileSync(process.env.GITHUB_OUTPUT, `${key}=${value}\n`); + console.log(JSON.stringify(outputs, null, 2)); + } +} diff --git a/.github/scripts/check-sdk-examples.cjs b/.github/scripts/check-sdk-examples.cjs new file mode 100644 index 0000000..69d89b0 --- /dev/null +++ b/.github/scripts/check-sdk-examples.cjs @@ -0,0 +1,131 @@ +const assert = require("node:assert/strict"); +const fs = require("node:fs"); +const os = require("node:os"); +const path = require("node:path"); +const { createRequire } = require("node:module"); + +const [frameworkRoot, nodeRoot, legacyRoot] = process.argv + .slice(2) + .map((root) => path.resolve(root)); +assert( + frameworkRoot && nodeRoot && legacyRoot, + "Pass built framework-v2, node-v2 and v1 source directories", +); +const root = path.resolve(__dirname, "../.."); +const sdkRequire = createRequire(path.join(frameworkRoot, "package.json")); +const ts = sdkRequire("typescript"); +const reactTypes = path.dirname(sdkRequire.resolve("@types/react/package.json")); +const nodeTypes = path.dirname(sdkRequire.resolve("@types/node/package.json")); +const temp = fs.mkdtempSync(path.join(os.tmpdir(), "reflag-sdk-doc-examples-")); +let snippets = 0; +function declaration(base, name) { + const dir = path.join(base, "packages", name); + const pkg = JSON.parse(fs.readFileSync(path.join(dir, "package.json"), "utf8")); + const file = path.join(dir, pkg.types); + assert(fs.existsSync(file), `Build declarations first: ${file}`); + return file; +} +function blocks(file) { + return [ + ...fs + .readFileSync(path.join(root, file), "utf8") + .matchAll(/```(?:tsx|jsx|typescript|ts)\r?\n([\s\S]*?)```/g), + ].map((match) => match[1]); +} +function compile(label, code, legacy = false, extra = {}) { + const dir = path.join(temp, `${snippets++}`); + fs.mkdirSync(dir); + const file = path.join(dir, "example.tsx"); + const globals = path.join(dir, "globals.d.ts"); + fs.writeFileSync(file, code); + fs.writeFileSync( + globals, + `declare module "your-component-library" { export const Spinner: import("react").FC>; }\n`, + ); + const paths = { + "@reflag/react-sdk": [declaration(legacy ? legacyRoot : frameworkRoot, "react-sdk")], + "@reflag/browser-sdk": [declaration(legacy ? legacyRoot : frameworkRoot, "browser-sdk")], + "@reflag/node-sdk": [declaration(legacy ? legacyRoot : nodeRoot, "node-sdk")], + "@reflag/vue-sdk": [declaration(legacy ? legacyRoot : frameworkRoot, "vue-sdk")], + react: [path.join(reactTypes, "index.d.ts")], + "react/jsx-runtime": [path.join(reactTypes, "jsx-runtime.d.ts")], + next: [path.join(path.dirname(sdkRequire.resolve("next/package.json")), "index.d.ts")], + }; + for (const [name, content] of Object.entries(extra)) { + const target = path.join(dir, `${name.replaceAll(/[^\w]/g, "-")}.tsx`); + fs.writeFileSync(target, content); + paths[name] = [target]; + } + const ambient = label.startsWith("Next.js") ? [path.join(reactTypes, "canary.d.ts")] : []; + const program = ts.createProgram( + [file, globals, path.join(nodeTypes, "index.d.ts"), ...ambient], + { + target: ts.ScriptTarget.ES2022, + module: ts.ModuleKind.ESNext, + moduleResolution: ts.ModuleResolutionKind.Bundler, + jsx: ts.JsxEmit.ReactJSX, + strict: true, + noEmit: true, + skipLibCheck: true, + types: [], + baseUrl: frameworkRoot, + paths, + }, + ); + const diagnostics = ts.getPreEmitDiagnostics(program); + if (diagnostics.length) + throw new Error( + `${label}:\n${ts.formatDiagnosticsWithColorAndContext(diagnostics, { getCanonicalFileName: (file) => file, getCurrentDirectory: () => root, getNewLine: () => "\n" })}`, + ); +} +try { + for (const file of [ + "product-handbook/multivariate-flags.md", + "product-handbook/anonymous-users.md", + "product-handbook/feature-clean-up-and-archival-beta/ai-code-clean-up-beta.md", + "product-handbook/type-safety.md", + "product-handbook/launch-monitor/README.md", + "product-handbook/launch-monitor/give-feedback-button.md", + "guides/toggle-toolbar-with-a-flag.md", + "guides/use-reflag-in-your-cli.md", + ]) + blocks(file).forEach((code, index) => compile(`${file} #${index + 1}`, code)); + blocks("product-handbook/feature-entitlements/README.md") + .slice(0, 2) + .forEach((code, index) => compile(`Entitlements #${index + 1}`, code)); + compile("Opt-in loading and membership", blocks("guides/self-opt-in.md")[0]); + const gettingStarted = blocks("README.md"); + compile("Getting started: Boolean", gettingStarted[0]); + compile("Getting started: feedback", gettingStarted[2]); + const next = blocks("supported-languages/next.js.md"); + compile("Next.js singleton", next[0]); + compile("Next.js server action", next[1], false, { + "@/app/reflag": next[0], + "@/app/auth": + 'import type { Context } from "@reflag/node-sdk"; export async function getContext(): Promise { return {}; }', + }); + compile("Next.js Pages router", next[2], false, { + "@/app/reflag": next[0], + "@/app/auth": + 'import type { Context } from "@reflag/node-sdk"; export async function getContext(): Promise { return {}; }', + }); + compile("Next.js client", next[3]); + compile( + "Vue v2 declaration guard", + `import { useFlag } from "@reflag/vue-sdk";\nconst enabled: boolean = useFlag("huddle").value;\nconst count: number = useFlag("settings", { maxItems: 10 }).value.maxItems;\n// @ts-expect-error Vue returns a ref of the direct value, not a flag wrapper.\nuseFlag("huddle").isEnabled;\n// @ts-expect-error Ref contents are not any.\nconst invalid: string = useFlag("settings", { maxItems: 10 }).value.maxItems;\n`, + ); + compile( + "v1 declaration guard", + `import { useFlag } from "@reflag/react-sdk";\nconst enabled: boolean = useFlag("huddle").isEnabled;\n// @ts-expect-error Reject any-shaped declarations.\nconst invalid: number = useFlag("huddle").isEnabled;\n`, + true, + ); + compile( + "v2 declaration guard", + `import { useFlag, useFlagSuspense } from "@reflag/react-sdk";\nimport { ReflagClient } from "@reflag/node-sdk";\nconst enabled: boolean = useFlag("huddle");\nconst count: number = useFlag("settings", { maxItems: 10 }).maxItems;\nconst suspended: boolean = useFlagSuspense("huddle");\n// @ts-expect-error No wrapper API in v2.\nuseFlag("huddle").isEnabled;\n// @ts-expect-error Inferred fields are not any.\nconst invalid: string = useFlag("settings", { maxItems: 10 }).maxItems;\nconst client = new ReflagClient();\nconst serverEnabled: boolean = client.getFlag({}, "huddle");\n// @ts-expect-error Node returns a value, not a wrapper.\nclient.getFlag({}, "huddle").isEnabled;\n`, + ); + console.log( + `${snippets} documentation examples/declaration guards compiled with zero diagnostics.`, + ); +} finally { + fs.rmSync(temp, { recursive: true, force: true }); +} diff --git a/.github/scripts/sdk-docs.mjs b/.github/scripts/sdk-docs.mjs new file mode 100644 index 0000000..8430997 --- /dev/null +++ b/.github/scripts/sdk-docs.mjs @@ -0,0 +1,361 @@ +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import { createHash } from "node:crypto"; +import fs from "node:fs"; +import path from "node:path"; +import { pathToFileURL } from "node:url"; +import { parseArgs } from "node:util"; + +export const webSDKs = ["browser-sdk", "react-sdk", "vue-sdk", "node-sdk"]; +export const currentVersionNote = "This page covers SDK v2."; +const references = [...webSDKs, "react-native-sdk", "management-sdk"]; +export const documentedPackages = [...references, "cli"]; +const repository = "https://github.com/reflagcom/javascript"; +const versionPattern = + /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(-[\da-zA-Z.-]+)?(?:\+[\da-zA-Z.-]+)?$/; +const read = (root, file) => fs.readFileSync(path.join(root, file), "utf8"); +const git = (source, ...args) => + execFileSync("git", ["-C", source, ...args], { encoding: "utf8" }).trim(); +export const hash = (content) => createHash("sha256").update(content).digest("hex"); +const relative = (from, to) => path.posix.relative(path.posix.dirname(from), to); + +export function docsPath(name, major, filename = "README.md") { + assert(documentedPackages.includes(name), `Unknown documentation owner: ${name}`); + if (webSDKs.includes(name)) { + assert([1, 2].includes(major), `Unmapped SDK major: ${major}`); + return `${major === 1 ? "legacy/v1" : "supported-languages"}/${name}/${filename}`; + } + if (name === "management-sdk") return `api/management-sdk/${filename}`; + if (name === "cli") return "api/cli.md"; + return `supported-languages/react-native-sdk/${filename}`; +} + +function metadata(source, name) { + assert(documentedPackages.includes(name), `Unknown documentation owner: ${name}`); + const pkg = JSON.parse(read(source, `packages/${name}/package.json`)); + assert.equal(pkg.name, `@reflag/${name}`); + assert(versionPattern.test(pkg.version), `Invalid version: ${pkg.name}`); + assert(!pkg.private, `Private package: ${pkg.name}`); + return pkg; +} + +function withBanner(content, message) { + const note = `{% hint style="info" %}\n${message}\n{% endhint %}\n\n`; + if (!content.startsWith("---\n")) return note + content; + const end = content.indexOf("\n---\n", 4); + assert(end >= 0, "Unclosed frontmatter"); + return content.slice(0, end + 5) + "\n" + note + content.slice(end + 5).trimStart(); +} + +export const headingSlug = (text) => + text + .toLowerCase() + .replace(/<\/?(?:a|code|strong|em|span|br)(?:\s[^>]*)?>/g, "") + .replace(/[^\p{L}\p{N}_ -]/gu, "") + .replace(/ /g, "-"); + +export function anchorHeadings(content, { introNote } = {}) { + const lines = content.split("\n"); + const headings = []; + const linked = new Set([...content.matchAll(/#([\w-]+)/g)].map((match) => match[1])); + let fence; + for (const [index, line] of lines.entries()) { + const marker = /^\s*(`{3,}|~{3,})/.exec(line)?.[1]; + if (marker) { + if (!fence) fence = marker; + else if (fence[0] === marker[0] && marker.length >= fence.length) fence = undefined; + continue; + } + if (fence) continue; + const match = /^(#{1,6}) (.+)$/.exec(line); + if (match) headings.push({ index, level: match[1].length, text: match[2] }); + } + const ids = new Set(); + // Canonical docs.sh strips property-collision suffixes from type links. + // Reserve public class/interface/type IDs before similarly named members: + // #logger must still identify Logger, not the earlier client.logger field. + const priority = (heading) => (heading.level <= 3 ? 0 : 1); + for (const heading of [...headings].sort((a, b) => priority(a) - priority(b))) { + const base = headingSlug(heading.text); + let id = base; + for (let suffix = 1; ids.has(id); suffix++) id = `${base}-${suffix}`; + heading.id = id; + ids.add(id); + } + for (const { index, level, text, id } of headings) { + // GitBook drops IDs on Markdown levels 4–6. Promote API members and + // linked headings, but keep unlinked Parameters/Returns out of the outline. + if (level > 3 && (level === 5 || linked.has(id))) + lines[index] = lines[index].replace(/^#{4,6}/, "###"); + // Explicit IDs also preserve TypeDoc's and punctuation-based slugs. + if (!/\bid=["']/.test(text)) lines[index] += ` `; + } + if (introNote) { + const firstSection = headings.find((heading) => heading.level > 1)?.index ?? lines.length; + lines.splice(firstSection, 0, introNote, ""); + } + return lines.join("\n"); +} + +export function planPackage({ source, name, commit }) { + assert(/^[a-f\d]{40}$/.test(commit), "A full SDK source commit is required"); + const pkg = metadata(source, name); + const major = Number(pkg.version.split(".")[0]); + const web = webSDKs.includes(name); + const files = new Map(); + const mediaRoot = web + ? major === 1 + ? "legacy/v1/_media" + : "supported-languages/_media" + : "sdk/_media"; + const add = (file, content) => { + const bytes = Buffer.from(content); + assert( + !files.has(file) || files.get(file).equals(bytes), + `Conflicting generated output: ${file}`, + ); + files.set(file, bytes); + }; + const targetMajor = (target) => { + if (!webSDKs.includes(target)) return Number(metadata(source, target).version.split(".")[0]); + if (web) return major; + const range = + pkg.dependencies?.[`@reflag/${target}`] ?? + pkg.peerDependencies?.[`@reflag/${target}`] ?? + (name === "react-native-sdk" ? pkg.dependencies?.["@reflag/react-sdk"] : undefined); + const selected = /^[~^]?(\d+)\./.exec(range ?? "")?.[1]; + assert(selected, `Cannot determine linked SDK major: ${target}`); + return Number(selected); + }; + const route = (url, output) => { + if (url.startsWith("#")) return url; + // Absolute SDK links must not send legacy readers into the current API. + const publicLink = + /^https:\/\/docs\.reflag\.com\/(?:supported-languages|sdk\/@reflag)\/([^/#]+)(?:\/(globals)(?:\.md)?)?\/?(#[^\s]*)?$/.exec( + url, + ); + if (publicLink && webSDKs.includes(publicLink[1])) { + return ( + relative( + output.file, + docsPath( + publicLink[1], + targetMajor(publicLink[1]), + publicLink[2] ? "globals.md" : "README.md", + ), + ) + (publicLink[3] ?? "") + ); + } + if (/^(?:[a-z][a-z\d+.-]*:|\/)/i.test(url)) { + return url + .replace(`${repository}/blob/main/`, `${repository}/blob/${commit}/`) + .replace(`${repository}/tree/main/`, `${repository}/tree/${commit}/`); + } + const [pathname, fragment = ""] = url.split(/(?=#)/, 2); + let raw = path.posix.normalize( + path.posix.join(path.posix.dirname(output.raw), decodeURIComponent(pathname)), + ); + assert(!raw.startsWith("../") && !path.posix.isAbsolute(raw), `Link escapes SDK docs: ${url}`); + // TypeDoc's shared README attachment can contain the wrong package's README. + if (raw === "_media/README.md") { + const original = read(source, `packages/${name}/README.md`); + const linked = /\]\(\.\.\/([^/]+)\/README\.md\)/.exec(original)?.[1]; + assert(linked && documentedPackages.includes(linked), "Unmapped README attachment"); + raw = `@reflag/${linked}/README.md`; + } + const sdk = /^@reflag\/([^/]+)\/(README|globals)\.md$/.exec(raw); + if (sdk) + return ( + relative(output.file, docsPath(sdk[1], targetMajor(sdk[1]), `${sdk[2]}.md`)) + fragment + ); + if (raw === "documents/browser-sdk/FEEDBACK.md") + return ( + relative(output.file, docsPath("browser-sdk", targetMajor("browser-sdk"), "feedback.md")) + + fragment + ); + const document = /^documents\/([^/]+)\/README\.md$/.exec(raw); + if (document && references.includes(document[1])) + return relative(output.file, docsPath(document[1], targetMajor(document[1]))) + fragment; + if (raw.startsWith("_media/")) { + const target = `${mediaRoot}/${raw.slice("_media/".length)}`; + add(target, fs.readFileSync(path.join(source, "dist/docs", raw))); + return relative(output.file, target) + fragment; + } + return `${repository}/blob/${commit}/${raw}${fragment}`; + }; + const render = (raw, file, kind) => { + let content = read(source, `dist/docs/${raw}`); + // Canonical docs.sh normalizes property anchors; normalize all links, too. + content = content.replace(/(globals\.md#[\w-]+?)-\d+(?=[)"\s])/g, "$1"); + content = content.replace(/```[^\n]*\n[\s\S]*?```/g, (block) => block.replace(/[ \t]+$/gm, "")); + content = content.replace( + /(\]\()([^\s)]+)([^)]*\))/g, + (_, open, url, close) => `${open}${route(url, { raw, file })}${close}`, + ); + content = content.replace( + /((?:src|href)=["'])([^"']+)(["'])/g, + (_, open, url, close) => `${open}${route(url, { raw, file })}${close}`, + ); + content = anchorHeadings(content, { + introNote: web && major === 2 ? currentVersionNote : undefined, + }); + if (web) { + if (major === 1) { + // Only legacy installs need a major pin; current docs assume a fresh install. + content = content + .split("\n") + .map((line) => { + if (!/^\s*(?:npm (?:i|install)|yarn add|pnpm add|bun add|deno add|npx)\b/.test(line)) + return line; + return line.replace( + /@reflag\/(?:node-sdk|browser-sdk|react-sdk|vue-sdk|cli)(?:@[\w.^~-]+)?(?![\w/-])/g, + (match) => `${match.replace(/@[^@/]+$/, "")}@1`, + ); + }) + .join("\n"); + content = content.replace( + /(https:\/\/cdn\.jsdelivr\.net\/npm\/@reflag\/browser-sdk)(?:@[^/"'<>\s]+)?/g, + "$1@1", + ); + } + const counterpart = docsPath( + name, + major === 1 ? 2 : 1, + kind === "feedback" ? "feedback.md" : kind === "reference" ? "globals.md" : "README.md", + ); + const migration = relative(file, "supported-languages/migrating-from-v1.md"); + content = + major === 1 + ? withBanner( + content, + `**Protocol v1 — legacy.** [Current v2 documentation](${relative(file, counterpart)}) · [Migration guide](${migration})`, + ) + : `${content.trimEnd()}\n\nUsing v1? [Legacy docs](${relative(file, counterpart)}) · [Upgrade guide](${migration}).\n`; + } else if (name === "react-native-sdk") { + content = withBanner( + content, + `**Independent SDK compatibility.** This React Native release uses React/Browser protocol v${targetMajor("react-sdk")}. Follow the [matching React documentation](${relative(file, docsPath("react-sdk", targetMajor("react-sdk")))}) and use a [matching Node SDK](${relative(file, docsPath("node-sdk", targetMajor("react-sdk")))}) for bootstrap. Do not pass protocol-v2 bootstrap into a v1 consumer.`, + ); + } + add(file, content); + }; + if (references.includes(name)) { + for (const filename of ["README.md", "globals.md"]) { + const raw = `@reflag/${name}/${filename}`; + const kind = filename === "globals.md" ? "reference" : "readme"; + render(raw, docsPath(name, major, filename), kind); + // Keep historical SDK URLs and their reference anchors usable, but only + // the current major owns these aliases. A v1 release cannot replace v2. + if (!web || major === 2) render(raw, `sdk/@reflag/${name}/${filename}`, kind); + if ( + ((name === "react-sdk" && major === 2) || name === "react-native-sdk") && + filename === "README.md" + ) + render(raw, `sdk/documents/${name}/README.md`, kind); + } + } + if (name === "browser-sdk") { + const raw = "documents/browser-sdk/FEEDBACK.md"; + render(raw, docsPath(name, major, "feedback.md"), "feedback"); + if (major === 2) render(raw, "sdk/documents/browser-sdk/FEEDBACK.md", "feedback"); + } + if (name === "cli") { + render("documents/cli/README.md", "api/cli.md", "readme"); + render("documents/cli/README.md", "sdk/documents/cli/README.md", "readme"); + } + const manifest = { + sourceRepository: repository, + sourceCommit: commit, + package: pkg.name, + version: pkg.version, + files: Object.fromEntries([...files].map(([file, content]) => [file, hash(content)])), + }; + add(`.generated/sdk-docs/${name}/v${major}.json`, `${JSON.stringify(manifest, null, 2)}\n`); + return files; +} + +export function applyPlan(files, destination, { check = false } = {}) { + for (const [file, content] of files) { + assert(!path.isAbsolute(file) && !file.split("/").includes(".."), "Unsafe generated path"); + const target = path.join(destination, file); + if (check) + assert(fs.readFileSync(target).equals(content), `Generated documentation differs: ${file}`); + else { + fs.mkdirSync(path.dirname(target), { recursive: true }); + fs.writeFileSync(target, content); + } + } + // Never delete a tree, or take ownership of navigation, guides or GitBook settings. +} + +export function releaseFiles(source, plan) { + assert.equal( + git(source, "status", "--porcelain", "--untracked-files=no"), + "", + "SDK source must be clean", + ); + const commit = git(source, "rev-parse", "HEAD"); + assert.equal(plan.sourceCommit, commit, "Release source changed"); + assert(Array.isArray(plan.releases), "Invalid release plan"); + const files = new Map(); + const seen = new Set(); + for (const release of plan.releases) { + assert(/^@reflag\/[a-z][a-z0-9-]*$/.test(release.name), "Invalid package name"); + const name = release.name.slice("@reflag/".length); + const pkg = metadata(source, name); + assert(!seen.has(name), `Duplicate package: ${name}`); + seen.add(name); + assert.equal(pkg.version, release.version, "Published/source version mismatch"); + assert(!versionPattern.exec(pkg.version)[4], "Prereleases cannot promote stable docs"); + assert.equal( + git(source, "rev-parse", `refs/tags/${pkg.name}@${pkg.version}^{commit}`), + commit, + "Release tag/source mismatch", + ); + for (const [file, content] of planPackage({ source, name, commit })) { + assert(!files.has(file) || files.get(file).equals(content), `Conflicting output: ${file}`); + files.set(file, content); + } + } + return files; +} + +if (process.argv[1] && import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href) { + const { values, positionals } = parseArgs({ + allowPositionals: true, + options: { + source: { type: "string" }, + destination: { type: "string", default: "." }, + package: { type: "string", multiple: true }, + plan: { type: "string" }, + check: { type: "boolean", default: false }, + }, + }); + assert(values.source, "--source is required"); + const source = path.resolve(values.source); + let files; + if (positionals[0] === "release") { + assert(values.plan, "--plan is required"); + files = releaseFiles(source, JSON.parse(fs.readFileSync(values.plan, "utf8"))); + } else { + assert.equal(positionals[0], "import", "Use import or release"); + assert(values.package?.length, "Select --package explicitly"); + assert.equal( + git(source, "status", "--porcelain", "--untracked-files=no"), + "", + "SDK source must be clean", + ); + files = new Map(); + for (const name of values.package) + for (const [file, content] of planPackage({ + source, + name, + commit: git(source, "rev-parse", "HEAD"), + })) { + assert(!files.has(file) || files.get(file).equals(content), `Conflicting output: ${file}`); + files.set(file, content); + } + } + applyPlan(files, path.resolve(values.destination), { check: values.check }); + console.log(`${values.check ? "Verified" : "Generated"} ${files.size} SDK documentation files.`); +} diff --git a/.github/scripts/sdk-docs.test.mjs b/.github/scripts/sdk-docs.test.mjs new file mode 100644 index 0000000..2eb814e --- /dev/null +++ b/.github/scripts/sdk-docs.test.mjs @@ -0,0 +1,401 @@ +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import test from "node:test"; +import { + anchorHeadings, + applyPlan, + currentVersionNote, + docsPath, + planPackage, + releaseFiles, + webSDKs, +} from "./sdk-docs.mjs"; +import { + anchors, + checkCurrentPagePresentation, + checkLinks, + checkSDKDocs, + root, + sourceMatrix, +} from "./check-sdk-docs.mjs"; + +function fixture(t, major = 2) { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "reflag-sdk-docs-test-")); + t.after(() => fs.rmSync(dir, { recursive: true, force: true })); + const source = path.join(dir, "source"), + destination = path.join(dir, "docs"); + const put = (file, content) => { + fs.mkdirSync(path.dirname(file), { recursive: true }); + fs.writeFileSync(file, content); + }; + const names = [...webSDKs, "react-native-sdk", "management-sdk", "cli"]; + for (const name of names) { + put( + path.join(source, `packages/${name}/package.json`), + JSON.stringify({ + name: `@reflag/${name}`, + version: `${major}.0.0`, + dependencies: { "@reflag/react-sdk": "1.7.4" }, + }), + ); + put( + path.join(source, `packages/${name}/README.md`), + "# SDK\n[Browser](../browser-sdk/README.md)\n", + ); + put( + path.join(source, `dist/docs/@reflag/${name}/README.md`), + `---\nlayout: {}\n---\n# SDK\n\nSDK introduction.\n\n## Setup\n[Browser](../../_media/README.md)\n[Feedback](../../documents/browser-sdk/FEEDBACK.md)\n[Toolbar](https://docs.reflag.com/supported-languages/browser-sdk/globals#toolbaroptions)\nnpm install @reflag/${name}\nbun add @reflag/${name}\ndeno add npm:@reflag/${name}\nnpx @reflag/cli new\n\n[Source](https://github.com/reflagcom/javascript/blob/main/packages/${name}/README.md)\n`, + ); + put( + path.join(source, `dist/docs/@reflag/${name}/globals.md`), + '# Reference\n## FlagValueFromDefault\\\n\n', + ); + } + put( + path.join(source, "dist/docs/documents/browser-sdk/FEEDBACK.md"), + "# Feedback\n[Browser](../../@reflag/browser-sdk/README.md)\n", + ); + put(path.join(source, "dist/docs/documents/cli/README.md"), "# CLI\n"); + return { + source, + destination, + put, + options: { source, name: "react-sdk", commit: "a".repeat(40) }, + }; +} + +test("repository navigation, provenance, cross-version links, assets and anchors", () => { + assert(checkSDKDocs().generatedPages >= 28); +}); + +test("handbook keeps Remote config as a short pointer to the full Multivariate flags guide", () => { + const summary = fs.readFileSync(path.join(root, "SUMMARY.md"), "utf8"); + for (const file of ["remote-config.md", "multivariate-flags.md"]) + assert(summary.includes(`(product-handbook/${file})`)); + const remote = fs.readFileSync(path.join(root, "product-handbook/remote-config.md"), "utf8"); + const paragraph = remote + .replace(/^---\n[\s\S]*?\n---\n/, "") + .replace(/^# Remote config\s*/m, "") + .trim(); + assert.equal(paragraph.split(/\n\s*\n/).length, 1); + assert.match(paragraph, /\[Multivariate flag\]\(multivariate-flags\.md\)/); + assert(!paragraph.includes("```")); + const multivariate = fs.readFileSync( + path.join(root, "product-handbook/multivariate-flags.md"), + "utf8", + ); + assert.match(multivariate, /^# Multivariate flags$/m); + assert(multivariate.includes("export function AssistantSettings()")); + assert(multivariate.includes("export function AssistantModel()")); + assert.match( + multivariate, + /^## Migrating from Remote config$[\s\S]*^### Using an AI agent$[\s\S]*^### Manual migration\n\n1\./m, + ); + assert(multivariate.includes("[Reflag MCP](../api/mcp.md)")); + checkLinks(root, ["product-handbook/remote-config.md", "product-handbook/multivariate-flags.md"]); +}); + +test("CI discovers exact source refs from manifests rather than hardcoding the first import", () => { + const matrix = sourceMatrix(); + assert(matrix.include.length > 0); + for (const row of matrix.include) { + assert(/^[a-f\d]{40}$/.test(row.ref)); + assert.match( + row.packages, + /^(?:--package (?:browser-sdk|react-sdk|vue-sdk|node-sdk|react-native-sdk|management-sdk|cli)(?: |$))+$/, + ); + } +}); + +test("v1 import owns only the archive, pins installers/CDN and routes SDK links to v1", (t) => { + const { options } = fixture(t, 1); + const files = planPackage(options); + assert( + [...files.keys()].every( + (file) => file.startsWith("legacy/v1/") || file.startsWith(".generated/"), + ), + ); + const readme = files.get("legacy/v1/react-sdk/README.md").toString(); + assert.match(readme, /npm install @reflag\/react-sdk@1/); + assert.match(readme, /bun add @reflag\/react-sdk@1/); + assert.match(readme, /deno add npm:@reflag\/react-sdk@1/); + assert.match(readme, /npx @reflag\/cli@1 new/); + assert.match(readme, /browser-sdk@1/); + assert.match(readme, /\(\.\.\/browser-sdk\/globals.md#toolbaroptions\)/); + assert.match(readme, /blob\/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\//); + assert(readme.indexOf("---") < readme.indexOf("{% hint"), "Keep frontmatter first"); + for (const [file, content] of files) + if (file.endsWith(".md")) { + assert.doesNotMatch(content.toString(), /generated from/i); + assert(!content.toString().includes(currentVersionNote)); + } + const manifest = JSON.parse(files.get(".generated/sdk-docs/react-sdk/v1.json")); + assert.equal(manifest.sourceCommit, options.commit); + assert.equal(manifest.version, "1.0.0"); +}); + +test("v2 sync cannot modify archived docs, navigation, settings or handwritten guides", (t) => { + const { options, destination, put } = fixture(t); + const preserved = [ + "legacy/v1/react-sdk/README.md", + "SUMMARY.md", + "README.md", + "gitbook-docs.yaml", + "supported-languages/migrating-from-v1.md", + ]; + for (const file of preserved) put(path.join(destination, file), "preserve"); + const files = planPackage(options); + applyPlan(files, destination); + applyPlan(files, destination, { check: true }); + for (const file of preserved) + assert.equal(fs.readFileSync(path.join(destination, file), "utf8"), "preserve"); + assert(files.has("supported-languages/react-sdk/README.md")); + assert(files.has("sdk/@reflag/react-sdk/globals.md"), "Preserve historical reference URLs"); + assert.match( + files.get("sdk/@reflag/react-sdk/README.md").toString(), + /\.\.\/\.\.\/\.\.\/legacy\/v1\/react-sdk\/README.md/, + ); +}); + +test("current docs retain the introduction, add one v2 scope line and keep unpinned installs", (t) => { + const { options, source, put } = fixture(t); + put( + path.join(source, "packages/react-sdk/package.json"), + JSON.stringify({ name: "@reflag/react-sdk", version: "2.0.0-next.0" }), + ); + const files = planPackage(options); + for (const file of [ + "supported-languages/react-sdk/README.md", + "sdk/@reflag/react-sdk/README.md", + "sdk/documents/react-sdk/README.md", + ]) { + const content = files.get(file).toString(); + checkCurrentPagePresentation(content, file); + assert(content.indexOf("SDK introduction.") < content.indexOf(currentVersionNote)); + assert(content.indexOf(currentVersionNote) < content.indexOf("## Setup")); + assert(content.indexOf("## Setup") < content.indexOf("Using v1?")); + assert.match(content, /npm install @reflag\/react-sdk\n/); + assert.match(content, /npx @reflag\/cli new/); + assert.match(content, /browser-sdk"><\/script>/); + assert(!content.includes("{% hint")); + assert( + !content.includes("2.0.0-next.0"), + "Source versions remain in provenance, not page warnings", + ); + } + const manifest = JSON.parse(files.get(".generated/sdk-docs/react-sdk/v2.json")); + assert.equal(manifest.version, "2.0.0-next.0"); +}); + +test("presentation checks reject repeated or leading notices and major-pinned current installs", () => { + const note = "Using v1? [Legacy docs](legacy.md) · [Upgrade guide](migration.md)."; + const page = `# SDK\n\nGet started.\n\n${currentVersionNote}\n\n## Setup\n\nInstall the SDK.\n\n${note}\n`; + checkCurrentPagePresentation(page, "page.md"); + assert.throws( + () => checkCurrentPagePresentation(page.replace(currentVersionNote, ""), "page.md"), + /one SDK v2 scope note/, + ); + assert.throws( + () => checkCurrentPagePresentation(`${currentVersionNote}\n\n${page}`, "page.md"), + /one SDK v2 scope note/, + ); + assert.throws( + () => + checkCurrentPagePresentation( + `${currentVersionNote}\n\n${page.replace(currentVersionNote, "")}`, + "page.md", + ), + /in the introduction/, + ); + assert.throws( + () => + checkCurrentPagePresentation( + page.replace(`${currentVersionNote}\n\n## Setup`, `## Setup\n\n${currentVersionNote}`), + "page.md", + ), + /in the introduction/, + ); + assert.throws(() => checkCurrentPagePresentation(`${note}\n\n# SDK\n`, "page.md"), /at the end/); + assert.throws( + () => checkCurrentPagePresentation(`${note}\n\n${page}`, "page.md"), + /one succinct/, + ); + assert.throws( + () => + checkCurrentPagePresentation( + page.replace("Get started.", "npm install @reflag/react-sdk@2"), + "page.md", + ), + /Major-pinned installs/, + ); + assert.throws( + () => checkCurrentPagePresentation(page.replace("Get started.", "**Protocol v2.**"), "page.md"), + /Repeated protocol banner/, + ); +}); + +test("independent Native references route to its pinned React/Browser major, not workspace v2", (t) => { + const { options } = fixture(t); + const files = planPackage({ ...options, name: "react-native-sdk" }); + const readme = files.get("supported-languages/react-native-sdk/README.md").toString(); + assert.match(readme, /legacy\/v1\/browser-sdk\/README.md/); + assert.match(readme, /legacy\/v1\/react-sdk\/README.md/); + assert(!readme.includes(currentVersionNote)); + assert(!files.has("supported-languages/react-sdk/README.md")); + assert(!files.has("legacy/v1/react-sdk/README.md")); +}); + +test("Management and CLI updates never own coordinated SDK trees", (t) => { + const { options, source, put } = fixture(t); + put(path.join(source, "dist/docs/@reflag/management-sdk/README.md"), "# Management SDK\n"); + for (const name of ["management-sdk", "cli"]) { + const files = planPackage({ ...options, name }); + assert( + ![...files.keys()].some( + (file) => file.startsWith("legacy/") || file.startsWith("supported-languages/"), + ), + ); + } +}); + +test("GitBook heading IDs preserve TypeDoc/generic deep links without changing code fences", () => { + const content = + "# `` component\n## FlagValueFromDefault\\\n## Properties\n## Properties\n```md\n# Leave code alone\n```\n"; + const rendered = anchorHeadings(content); + assert.match(rendered, /id="reflagprovider-component"/); + assert.match(rendered, /id="flagvaluefromdefaultt"/); + assert.match(rendered, /id="properties-1"/); + assert(rendered.includes("```md\n# Leave code alone\n```")); +}); + +test("the current-version line stays in the introduction without entering code fences", () => { + const content = "# SDK\n\nIntroduction.\n\n```md\n## Code example\n```\n\n## Setup\n"; + const rendered = anchorHeadings(content, { introNote: currentVersionNote }); + assert(rendered.includes("```md\n## Code example\n```")); + assert(rendered.indexOf(`\`\`\`\n\n${currentVersionNote}`) > rendered.indexOf("## Code example")); + assert(rendered.indexOf(currentVersionNote) < rendered.indexOf("## Setup")); + assert.equal(rendered.split(currentVersionNote).length - 1, 1); +}); + +test("GitBook keeps deep API-member and linked-section anchors without outlining every parameter label", () => { + const rendered = anchorHeadings( + "### Client\n#### Constructors\n##### getFlag()\n###### Parameters\n[Constructor](globals.md#constructors)\n", + ); + assert.match(rendered, /^### Constructors { + const rendered = anchorHeadings( + "### Client\n##### logger\n##### flagOverrides\n### Logger\n### FlagOverrides\n[Type](globals.md#logger)\n", + ); + assert.match(rendered, /^### logger { + const { source, options, destination } = fixture(t); + fs.unlinkSync(path.join(source, "dist/docs/@reflag/react-sdk/globals.md")); + assert.throws(() => applyPlan(planPackage(options), destination), /ENOENT/); + assert(!fs.existsSync(destination)); +}); + +test("manifest check detects manual generated-content changes", (t) => { + const { options, destination, put } = fixture(t); + const plan = planPackage(options); + applyPlan(plan, destination); + put(path.join(destination, "supported-languages/react-sdk/README.md"), "edited"); + assert.throws( + () => applyPlan(plan, destination, { check: true }), + /Generated documentation differs/, + ); +}); + +test("unknown owners and majors fail closed", (t) => { + const { options } = fixture(t); + assert.throws( + () => planPackage({ ...options, name: "../../escape" }), + /Unknown documentation owner/, + ); + assert.throws(() => docsPath("react-sdk", 3), /Unmapped SDK major/); + assert.throws(() => planPackage({ ...options, commit: "main" }), /full SDK source commit/); +}); + +test("negative link controls catch missing files and anchors; generic headings remain addressable", (t) => { + const { destination, put } = fixture(t); + put(path.join(destination, "page.md"), "[missing](other.md)\n"); + assert.throws(() => checkLinks(destination, ["page.md"]), /Missing file/); + put(path.join(destination, "other.md"), "# FlagValueFromDefault\\\n"); + put(path.join(destination, "page.md"), "[missing](other.md#nope)\n"); + assert.throws(() => checkLinks(destination, ["page.md"]), /Missing anchor/); + assert( + anchors(fs.readFileSync(path.join(destination, "other.md"), "utf8")).has( + "flagvaluefromdefaultt", + ), + ); +}); + +test("release sync requires the exact clean tagged source and rejects prereleases before writes", (t) => { + const { source, options, put } = fixture(t); + const git = (...args) => + execFileSync("git", ["-C", source, ...args], { encoding: "utf8" }).trim(); + git("init", "--quiet"); + git("add", "."); + git( + "-c", + "user.name=Test", + "-c", + "user.email=test@example.invalid", + "commit", + "--quiet", + "-m", + "Fixture", + ); + const sourceCommit = git("rev-parse", "HEAD"); + const plan = { sourceCommit, releases: [{ name: "@reflag/react-sdk", version: "2.0.0" }] }; + git("tag", "@reflag/react-sdk@2.0.0"); + assert(releaseFiles(source, plan).has("supported-languages/react-sdk/README.md")); + assert.throws( + () => releaseFiles(source, { ...plan, sourceCommit: options.commit }), + /source changed/, + ); + assert.throws( + () => releaseFiles(source, { ...plan, releases: [...plan.releases, ...plan.releases] }), + /Duplicate package/, + ); + put( + path.join(source, "packages/react-sdk/package.json"), + JSON.stringify({ name: "@reflag/react-sdk", version: "2.0.1-next.0" }), + ); + assert.throws(() => releaseFiles(source, plan), /must be clean/); + git("add", "."); + git( + "-c", + "user.name=Test", + "-c", + "user.email=test@example.invalid", + "commit", + "--quiet", + "-m", + "Prerelease", + ); + assert.throws( + () => + releaseFiles(source, { + sourceCommit: git("rev-parse", "HEAD"), + releases: [{ name: "@reflag/react-sdk", version: "2.0.1-next.0" }], + }), + /Prereleases cannot promote/, + ); +}); + +test("this change does not introduce a GitBook variant picker or alternate site mapping", () => { + assert(!fs.existsSync(path.join(root, ".gitbook.yaml")), "No new per-space root mapping"); + assert(!fs.readFileSync(path.join(root, "SUMMARY.md"), "utf8").includes("v2-candidate/")); +}); diff --git a/.github/workflows/sdk-docs.yml b/.github/workflows/sdk-docs.yml new file mode 100644 index 0000000..330e46a --- /dev/null +++ b/.github/workflows/sdk-docs.yml @@ -0,0 +1,112 @@ +name: SDK documentation + +on: + pull_request: + paths: + - "**/*.md" + - .generated/** + - .github/scripts/** + - .github/workflows/sdk-docs.yml + - gitbook-docs.yaml + +permissions: + contents: read + +jobs: + check: + name: Navigation and version isolation + runs-on: ubuntu-latest + outputs: + matrix: ${{ steps.sources.outputs.matrix }} + react_v1_ref: ${{ steps.sources.outputs.react_v1_ref }} + react_v2_ref: ${{ steps.sources.outputs.react_v2_ref }} + node_v2_ref: ${{ steps.sources.outputs.node_v2_ref }} + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + - uses: actions/setup-node@v4 + with: + node-version: 24 + - run: node --test .github/scripts/sdk-docs.test.mjs + - id: sources + name: Discover pinned SDK sources from generated manifests + run: node .github/scripts/check-sdk-docs.mjs --sources + + sources: + name: Rebuild SDK sources + needs: check + runs-on: ubuntu-latest + timeout-minutes: 20 + strategy: + fail-fast: false + matrix: ${{ fromJSON(needs.check.outputs.matrix) }} + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + - uses: actions/setup-node@v4 + with: + node-version: 24 + - run: corepack enable + - uses: actions/checkout@v4 + with: + repository: reflagcom/javascript + ref: ${{ matrix.ref }} + path: .sdk-source + persist-credentials: false + - name: Install exact SDK sources + working-directory: .sdk-source + run: yarn install --immutable + - name: Build declarations and canonical TypeDoc output + working-directory: .sdk-source + run: | + if test -d packages/flag-evaluation; then + yarn workspace @reflag/flag-evaluation build + fi + yarn workspace @reflag/node-sdk build + yarn workspace @reflag/browser-sdk build + yarn workspace @reflag/react-sdk build + yarn workspace @reflag/vue-sdk build + # Published v1 docs.sh uses [[ despite its /bin/sh shebang. + yarn exec bash ./docs.sh + - name: Verify generated content against pinned sources + run: node .github/scripts/sdk-docs.mjs import --source .sdk-source ${{ matrix.packages }} --check + + examples: + name: Compile matching SDK examples + needs: check + runs-on: ubuntu-latest + timeout-minutes: 20 + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + - uses: actions/setup-node@v4 + with: + node-version: 24 + - run: corepack enable + - uses: actions/checkout@v4 + with: + repository: reflagcom/javascript + ref: ${{ needs.check.outputs.react_v1_ref }} + path: .sdk-v1 + persist-credentials: false + - uses: actions/checkout@v4 + with: + repository: reflagcom/javascript + ref: ${{ needs.check.outputs.react_v2_ref }} + path: .sdk-v2 + persist-credentials: false + - uses: actions/checkout@v4 + with: + repository: reflagcom/javascript + ref: ${{ needs.check.outputs.node_v2_ref }} + path: .sdk-node-v2 + persist-credentials: false + - name: Build matching declarations + run: | + (cd .sdk-v1 && yarn install --immutable && yarn workspace @reflag/browser-sdk build && yarn workspace @reflag/react-sdk build && yarn workspace @reflag/vue-sdk build && yarn workspace @reflag/node-sdk build) + (cd .sdk-v2 && yarn install --immutable && yarn workspace @reflag/flag-evaluation build && yarn workspace @reflag/node-sdk build && yarn workspace @reflag/browser-sdk build && yarn workspace @reflag/react-sdk build && yarn workspace @reflag/vue-sdk build) + (cd .sdk-node-v2 && yarn install --immutable && yarn workspace @reflag/flag-evaluation build && yarn workspace @reflag/node-sdk build) + - run: node .github/scripts/check-sdk-examples.cjs .sdk-v2 .sdk-node-v2 .sdk-v1 diff --git a/README.md b/README.md index 4b72bc2..44dbb85 100644 --- a/README.md +++ b/README.md @@ -18,7 +18,7 @@ Now let's create your first flag. npx @reflag/cli new ``` -See [CLI docs](api/cli.md). +See the [CLI docs](api/cli.md), and [Type safety](product-handbook/type-safety.md) to generate TypeScript types for your flags. {% endtab %} {% tab title="UI" %} @@ -54,13 +54,13 @@ If you've installed the React SDK and created a flag called `my-new-flag`, getti import { useFlag } from "@reflag/react-sdk"; const MyFlag = () => { - const { isEnabled } = useFlag("my-new-flag"); + const enabled = useFlag("my-new-flag"); - return isEnabled ? "You have access!" : null; + return enabled ? "You have access!" : null; }; ``` -You can now use `isEnabled` to gate access to the flag. +`enabled` is `true` for users who have access to the flag. ## 3. Set access rules @@ -80,10 +80,12 @@ In the React SDK, you enable it with `toolbar:` ```jsx + + ``` ## 5. Monitor your flag launch @@ -109,20 +111,22 @@ To get feedback from your users, you can add a [static "Feedback" button](produc Here's an example with a static feedback button. ```tsx -import { useFlag } from "@reflag/react-sdk"; +import { useFlag, useTrack, useRequestFeedback } from "@reflag/react-sdk"; const MyFlag = () => { - const { isEnabled, track, requestFeedback } = useFlag("my-new-flag"); + const enabled = useFlag("my-new-flag"); + const track = useTrack(); + const requestFeedback = useRequestFeedback(); - if (!isEnabled) { + if (!enabled) { return null; } return ( <> - + @@ -131,6 +135,8 @@ const MyFlag = () => { } ``` +Configure your flag's adoption rules to match the event name you send with `track()`. + ## Get support * Need some help? [Chat with us](mailto:hello@reflag.com) diff --git a/SUMMARY.md b/SUMMARY.md index 3a5477e..01e1707 100644 --- a/SUMMARY.md +++ b/SUMMARY.md @@ -21,6 +21,7 @@ * [Next.js](supported-languages/next.js.md) * [OpenFeature](supported-languages/openfeature.md) * [Ruby SDK](supported-languages/ruby-sdk.md) +* [Migrating from v1](supported-languages/migrating-from-v1.md) ## API @@ -58,6 +59,7 @@ * [End-user opt-in](product-handbook/feature-rollouts/end-user-opt-in.md) * [Flag clean-up and archival](product-handbook/feature-clean-up-and-archival-beta/README.md) * [AI code clean-up](product-handbook/feature-clean-up-and-archival-beta/ai-code-clean-up-beta.md) +* [Multivariate flags](product-handbook/multivariate-flags.md) * [Remote config](product-handbook/remote-config.md) * [Type safety](product-handbook/type-safety.md) * [Team permissions](product-handbook/team-permissions.md) @@ -96,6 +98,19 @@ * [Beta feature opt-in](guides/self-opt-in.md) * [Toggle toolbar with a flag](guides/toggle-toolbar-with-a-flag.md) +## Legacy SDKs + +* [SDK v1](legacy/v1/README.md) + * [Browser SDK (v1)](legacy/v1/browser-sdk/README.md) + * [Reference](legacy/v1/browser-sdk/globals.md) + * [Feedback](legacy/v1/browser-sdk/feedback.md) + * [React SDK (v1)](legacy/v1/react-sdk/README.md) + * [Reference](legacy/v1/react-sdk/globals.md) + * [Vue SDK (v1)](legacy/v1/vue-sdk/README.md) + * [Reference](legacy/v1/vue-sdk/globals.md) + * [Node.js SDK (v1)](legacy/v1/node-sdk/README.md) + * [Reference](legacy/v1/node-sdk/globals.md) + ## Support * [Get support](support/get-support.md) diff --git a/guides/self-opt-in.md b/guides/self-opt-in.md index 037b37f..ce2dd39 100644 --- a/guides/self-opt-in.md +++ b/guides/self-opt-in.md @@ -19,8 +19,6 @@ For an overview of how opt-in affects access and how memberships are managed in Render the available opt-in flags and let the current user set their opt-in status. -If you're using `` without a `` boundary, see the loading section below. - ```tsx import { useState } from "react"; import { @@ -31,7 +29,11 @@ import { import { Spinner } from "your-component-library"; function OptInPage() { - const { flags: optInFlags } = useOptInFlags(); + const { flags: optInFlags, isLoading } = useOptInFlags({ suspense: false }); + + if (isLoading) { + return ; + } if (optInFlags.length === 0) { return

No opt-in flags are available.

; @@ -107,25 +109,11 @@ User and company opt-ins are independent. Setting `optedIn` to `false` removes o Cancelling every opt-in does not necessarily disable the flag: an access rule may independently enable it for the current context. -## Managing loading state with `` and without `` +## Managing opt-in loading state -Only apps using `ReflagBootstrappedProvider` without Suspense need to handle this loading state. Bootstrapped flag data does not include opt-in metadata, so the SDK fetches it when `useOptInFlags()` is first used. - -Check the hook's `isLoading` value before rendering an empty state: - -```tsx -const { flags: optInFlags, isLoading } = useOptInFlags({ suspense: false }); - -if (isLoading) { - return ; -} - -if (optInFlags.length === 0) { - return

No opt-in flags are available.

; -} -``` +The list of opt-in flags can still be loading after the rest of your flags are ready, for example when you bootstrap flags from the server. Check `isLoading` before rendering an empty state, as the quick start does, so users don't briefly see "No opt-in flags are available." -With a regular `ReflagProvider`, opt-in metadata arrives as part of the normal flags request, so `useOptInFlags().isLoading` remains `false`. Use `useIsLoading()`, suspense or the provider's `loadingComponent` for the normal initial loading state. +To use a Suspense boundary instead, call `useOptInFlags({ suspense: true })`. ## Next steps diff --git a/guides/toggle-toolbar-with-a-flag.md b/guides/toggle-toolbar-with-a-flag.md index cf91262..cb6545f 100644 --- a/guides/toggle-toolbar-with-a-flag.md +++ b/guides/toggle-toolbar-with-a-flag.md @@ -1,45 +1,30 @@ --- -description: >- - Learn how you can control who gets the toolbar in production by toggling a - feature flag on/off +description: Show the SDK toolbar toggle to selected users. icon: toolbox --- # Toggle toolbar with a flag -In some cases, you want to limit who has access to the toolbar in production. If you already have an "admin" or "internalUser" boolean on the user model, that is how most people decide whether to show the toolbar. +The Reflag toolbar lets you toggle flags for yourself in the browser. Use a flag to choose who gets it in production, such as your team or beta testers: create a Boolean `toolbar` flag in Reflag, enable it for those users, and don't set the provider's `toolbar` prop. -Beyond those simple cases, using a feature flag that you can enable for certain people is a great way to manage who gets to see the toolbar. - -Here's an example of how it can be done with the React SDK: - -1. Create the flag: - -```bash -$ npx reflag new toolbar -``` - -2. If you've set the `toolbar` prop on the ``, remove it. We'll manage this by calling `client.showToolbar()` when the flag is enabled. -3. Put this tiny component inside the ``: +Put this component inside your React SDK provider: ```tsx -function ToolbarFlagControl() { +import { useEffect } from "react"; +import { useClient, useFlag } from "@reflag/react-sdk"; + +export function ToolbarFlagControl() { const client = useClient(); - const {isEnabled: toolbarEnabled} = useFlag("toolbar"); + const toolbarEnabled = useFlag("toolbar"); + useEffect(() => { - if (toolbarEnabled) { - client?.showToolbarToggle(); - } - }, [toolbarEnabled]); + if (toolbarEnabled) client.showToolbarToggle(); + }, [client, toolbarEnabled]); + + return null; } ``` -Done! You can now enable/disable the toolbar for users by toggling the `toolbar` feature flag for them inside Reflag. - -{% hint style="info" %} -showToolbarToggle() became available in the following SDK versions: +Now you can turn the toolbar on or off for anyone by changing who the `toolbar` flag is enabled for. Turning it off takes effect the next time the page loads, because the toolbar stays open once it's shown. -* @reflag/react-sdk: 1.3.0 -* @reflag/vue-sdk: 1.3.0 -* @reflag/browser-sdk: 1.3.0 -{% endhint %} +The toolbar only overrides flags in the user's own browser, so it isn't a security control. See the [Browser SDK](../supported-languages/browser-sdk/README.md#overrides-and-toolbar) for more toolbar options. diff --git a/guides/use-reflag-in-your-cli.md b/guides/use-reflag-in-your-cli.md index c156dc5..9279dfe 100644 --- a/guides/use-reflag-in-your-cli.md +++ b/guides/use-reflag-in-your-cli.md @@ -1,111 +1,67 @@ --- -description: High-level guide to flagging features in your CLI +description: Gate a workflow in your own CLI with Reflag. icon: rectangle-terminal --- # Use Reflag in your CLI -### If you use API token for auth +This guide is about **your application's CLI**, not the Reflag management CLI. Your CLI asks your backend for flag values; the backend evaluates them with the Node.js SDK. That way, your Reflag keys stay on your servers instead of shipping inside the CLI. -First, create an endpoint in your backend for the CLI to call: +## Evaluate on your backend -``` -POST /get-flags -Authorization: Bearer -``` - -The endpoint will take the API key and use it to look up the associated user. +Create an endpoint such as `POST /get-flags`, authenticated with your existing API-token or OAuth flow. Look up the user and company from the caller's token, rather than trusting identities the CLI sends. -Then, use the [public-api-reference.md](../api/public-api/public-api-reference.md "mention") to get enabled flags for the authenticated user. Return the flags to the CLI: +Then evaluate the flags for that context: -``` -{ - flags: ['flag1', 'flag2'] -} -``` +```typescript +import { ReflagClient, type Context } from "@reflag/node-sdk"; -Finally, check for access with a simple: +const client = new ReflagClient({ secretKey: process.env.REFLAG_SECRET_KEY ?? "" }); +const initialized = client.initialize(); -```tsx -/function isFlagEnabled(flag: string) { - return flags.contains('myflag'); +export async function getCliAccess(context: Context) { + await initialized; + const bound = client.bindClient(context); + return { + exportEnabled: bound.getFlag("export-to-csv"), + settings: bound.getFlag("export-settings", { maxRows: 1000 }), + }; } ``` -### If you use API token for auth AND Node.js - -First, create an endpoint in your backend for the CLI to call: +Return only the values your CLI needs: +```json +{ + "exportEnabled": true, + "settings": { "maxRows": 1000 } +} ``` -POST /get-flags -Authorization: Bearer -``` - -The endpoint will take the API key and use it to look up the associated user. -Use the [node-sdk](../supported-languages/node-sdk/ "mention") get enabled flags for the authenticated user. +## Gate the CLI workflow -```jsx -import { ReflagClient } from "@reflag/node-sdk"; +In the CLI, use the Boolean directly. Users can modify a CLI they run, so if the CLI calls your backend to perform the operation, check the flag there too. -// configure the client -const boundClient = reflagClient.bindClient({ - user: { - id: "c1_u1", - name: "John Doe" - }, - company: { - id: "c1", - name: "Acme, Inc." - }, -}); - -// get flags -const flags = boundClient.getFlags(); -``` - -Finally, check for access with a simple: - -```tsx -if(flags['myflag'].isEnabled) { - //feature access +```typescript +export function canExport(response: { exportEnabled: boolean }) { + return response.exportEnabled; } ``` -### If you use OAuth for auth - -Use [node-sdk](../supported-languages/node-sdk/ "mention") or [public-api-reference.md](../api/public-api/public-api-reference.md "mention") to get flags for the authenticated user. +## Track successful usage separately -In Node, configure the SDK like so: +When the operation succeeds, track it with the same context, and configure the flag's adoption rules to match the event name. -```jsx -import { ReflagClient } from "@reflag/node-sdk"; +```typescript +import { ReflagClient, type Context } from "@reflag/node-sdk"; -// configure the client -const boundClient = reflagClient.bindClient({ - user: { - id: "c1_u1", - name: "John Doe" - }, - company: { - id: "c1", - name: "Acme, Inc." - }, -}); -``` +const client = new ReflagClient({ secretKey: process.env.REFLAG_SECRET_KEY ?? "" }); +const initialized = client.initialize(); -Check access for individual flag: - -```jsx -const { isEnabled } = boundClient.getFlag("myflag"); - -if (isEnabled) { - //feature access -} +export async function recordExport(context: Context) { + await initialized; + await client.bindClient(context).track("Exported CSV"); +} ``` -Or get all flags: - -```jsx -const flags = boundClient.getFlags(); -``` +Initialize the client once per process and flush queued events before your server process exits. See the [Node.js SDK](../supported-languages/node-sdk/README.md) for lifecycle options. diff --git a/integrations/overview.md b/integrations/overview.md index ea048bd..fb87c32 100644 --- a/integrations/overview.md +++ b/integrations/overview.md @@ -14,7 +14,7 @@ These integrations are crafted and maintained by the Reflag team. To build your own integrations with Reflag, you can use: -* [Event listeners](../supported-languages/browser-sdk/#event-listeners) +* [Event listeners](../supported-languages/browser-sdk/README.md#events) * [Runtime API](../api/public-api/) **To request support for more integrations,** [**please fill out this form**](https://share-eu1.hsforms.com/14DktM5t6T229b5Bg8KPDBg2b6w1x) **— Thanks!** diff --git a/legacy/v1/README.md b/legacy/v1/README.md new file mode 100644 index 0000000..15a7afc --- /dev/null +++ b/legacy/v1/README.md @@ -0,0 +1,34 @@ +--- +description: Documentation for v1 of the Browser, React, Vue and Node.js SDKs. +--- + +# Legacy SDKs (v1) + +These pages document **v1** of the Browser, React, Vue and Node.js SDKs. For a new integration, start with the [current SDK documentation](../../supported-languages/overview.md). To upgrade an existing application, read [Migrating from v1](../../supported-languages/migrating-from-v1.md). + +| SDK | Package major | Documentation | API reference | +| --- | --- | --- | --- | +| Browser | `@reflag/browser-sdk@1` | [Browser SDK v1](browser-sdk/README.md) | [Reference](browser-sdk/globals.md) | +| React | `@reflag/react-sdk@1` | [React SDK v1](react-sdk/README.md) | [Reference](react-sdk/globals.md) | +| Vue | `@reflag/vue-sdk@1` | [Vue SDK v1](vue-sdk/README.md) | [Reference](vue-sdk/globals.md) | +| Node.js | `@reflag/node-sdk@1` | [Node.js SDK v1](node-sdk/README.md) | [Reference](node-sdk/globals.md) | + +The archive also includes [Browser feedback documentation](browser-sdk/feedback.md). + +## Installing v1 + +Pin the major when maintaining a v1 application: + +```sh +npm install @reflag/react-sdk@1 +``` + +Use `@reflag/browser-sdk@1`, `@reflag/vue-sdk@1` or `@reflag/node-sdk@1` in the same way, and keep generating types with CLI 1. Without `@1`, npm installs the latest major version. + +## Compatibility + +- If you bootstrap flags from the server, keep the Node.js SDK and your Browser, React or Vue SDK on the same major version. v1 clients can't read v2 bootstrap data. +- React Native and the OpenFeature providers are released separately. Check their own documentation for the versions they support. +- Guides and handbook examples use v2. For v1 APIs such as `.isEnabled` and `.config.payload`, use the SDK pages in this section. + +"Legacy" means v1 is no longer the latest version. It doesn't announce an end-of-support date. See the [migration guide](../../supported-languages/migrating-from-v1.md) for what changes in v2. diff --git a/legacy/v1/_media/type-check-failed.png b/legacy/v1/_media/type-check-failed.png new file mode 100644 index 0000000..4ffbd40 Binary files /dev/null and b/legacy/v1/_media/type-check-failed.png differ diff --git a/legacy/v1/_media/type-check-payload-failed.png b/legacy/v1/_media/type-check-payload-failed.png new file mode 100644 index 0000000..6f7a486 Binary files /dev/null and b/legacy/v1/_media/type-check-payload-failed.png differ diff --git a/legacy/v1/browser-sdk/README.md b/legacy/v1/browser-sdk/README.md new file mode 100644 index 0000000..4d5a45f --- /dev/null +++ b/legacy/v1/browser-sdk/README.md @@ -0,0 +1,613 @@ +--- +layout: + visible: true +title: + visible: true +description: + visible: false +tableOfContents: + visible: true +outline: + visible: true +pagination: + visible: true +--- + +{% hint style="info" %} +**Protocol v1 — legacy.** [Current v2 documentation](../../../supported-languages/browser-sdk/README.md) · [Migration guide](../../../supported-languages/migrating-from-v1.md) +{% endhint %} + +# Reflag Browser SDK + +Basic client for [Reflag.com](https://reflag.com). If you're using React, you'll be better off with the Reflag React SDK. + +Reflag supports flag toggling, tracking flag usage, [collecting feedback](#qualitative-feedback-on-beta-flags) on flags, and [remotely configuring flags](#remote-config). + +## Install + +First find your `publishableKey` under [environment settings](https://app.reflag.com/env-current/settings/app-environments) in Reflag. + +The package can be imported or used directly in a HTML script tag: + +A. Import module: + +```typescript +import { ReflagClient } from "@reflag/browser-sdk"; + +const user = { + id: 42, + role: "manager", +}; + +const company = { + id: 99, + plan: "enterprise", +}; + +const reflagClient = new ReflagClient({ publishableKey, user, company }); + +await reflagClient.initialize(); + +const { + isEnabled, + config: { payload: question }, + track, + requestFeedback, +} = reflagClient.getFlag("huddle"); + +if (isEnabled) { + // Show flag. When retrieving `isEnabled` the client automatically + // sends a "check" event for the "huddle" flag which is shown in the + // Reflag UI. + + // On usage, call `track` to let Reflag know that a user interacted with the flag + track(); + + // The `payload` is a user-supplied JSON in Reflag that is dynamically picked + // out depending on the user/company. + const question = payload?.question ?? "Tell us what you think of Huddles"; + + // Use `requestFeedback` to create "Send feedback" buttons easily for specific + // flags. This is not related to `track` and you can call them individually. + requestFeedback({ title: question }); +} + +// `track` just calls `reflagClient.track()` to send an event using the same flag key +// You can also use `track` on the client directly to send any custom event. +reflagClient.track("huddle"); + +// similarly, `requestFeedback` just calls `reflagClient.requestFeedback({flagKey: })` +// which you can also call directly: +reflagClient.requestFeedback({ flagKey: "huddle" }); +``` + +B. Script tag (client-side directly in html) + +See [example/browser.html](https://github.com/reflagcom/javascript/tree/b4fe5b3d9386b87c6546175c323862d9878e1430/packages/browser-sdk/example/browser.html) for a working example: + +```html + + +Loading... + +``` + +### Init options + +Supply these to the constructor call: + +```typescript +type Configuration = { + logger: console; // by default only logs warn/error, by passing `console` you'll log everything + apiBaseUrl?: "https://front.reflag.com"; + credentials?: "include" | "same-origin" | "omit"; // forwarded to fetch requests; "include" also enables credentials for the default EventSource transport + feedback?: undefined; // See FEEDBACK.md + enableTracking?: true; // set to `false` to stop sending track events and user/company updates to Reflag servers. Useful when you're impersonating a user + enableLiveFlagUpdates?: false; // Set to `true` to keep flags up to date over SSE (browser SDK default: false) + eventSourceFactory?: (url: string) => { + // Advanced: provide a custom EventSource-compatible transport + addEventListener: (type: string, cb: (event: any) => void) => void; + close: () => void; + }; + fallbackFlags?: + | string[] + | Record; // Enable these flags if unable to contact reflag.com. Can be a list of flag keys or a record with configuration values + timeoutMs?: number; // Timeout for fetching flags (default: 5000ms) + staleWhileRevalidate?: boolean; // Revalidate in the background when cached flags turn stale to avoid latency in the UI (default: false) + staleTimeMs?: number; // at initialization time flags are loaded from the cache unless they have gone stale. Defaults to 0 which means the cache is disabled. Increase this in the case of a non-SPA + expireTimeMs?: number; // In case we're unable to fetch flags from Reflag, cached/stale flags will be used instead until they expire after `expireTimeMs`. Default is 30 days + offline?: boolean; // Use the SDK in offline mode. Offline mode is useful during testing and local development +}; +``` + +## Migrating from Bucket SDK + +If you have been using the Bucket SDKs, the following list will help you migrate to Reflag SDK: + +- `Bucket*` classes, and types have been renamed to `Reflag*` (e.g. `BucketClient` is now `ReflagClient`) +- `Feature*` classes, and types have been renamed to `Feature*` (e.g. `Feature` is now `Flag`, `RawFeatures` is now `RawFlags`) +- All methods that contained `feature` in the name have been renamed to use the `flag` terminology (e.g. `getFeature` is `getFlag`) +- The `fallbackFeatures` property in client constructor and configuration files has been renamed to `fallbackFlags` +- `featureKey` has been renamed to `flagKey` in all methods that accepts that argument +- The new cookies that are stored in the client's browser are now `reflag-*` prefixed instead og `bucket-*` +- The `featuresUpdated` hook has been renamed to `flagsUpdated` +- The `checkIsEnabled` and `checkConfig` hooks have been removed, use `check` from now on + +To ease in transition to Reflag SDK, some of the old methods have been preserved as aliases to the new methods: + +- `getFeature` method is an alias for `getFlag` +- `getFeatures` method is an alias for `getFlags` +- `featuresUpdated` hook is an alias for `flagsUpdated` + +If you are running with strict Content Security Policies active on your website, you will need change them as follows: + +- `connect-src https://front.bucket.co` to `connect-src https://front.reflag.com` + +Finally, if you have customized the look & feel of the Feedback component, update `--bucket-feedback-*` CSS classes to `--reflag-feedback-*` + +## Flag toggles + +Reflag determines which flags are active for a given user/company. The user/company is given in the ReflagClient constructor. + +If you supply `user` or `company` objects, they must include at least the `id` property otherwise they will be ignored in their entirety. +In addition to the `id`, you must also supply anything additional that you want to be able to evaluate flag targeting rules against. + +Attributes cannot be nested (multiple levels) and must be either strings, integers or booleans. +Some attributes are special and used in Reflag UI: + +- `name` -- display name for `user`/`company`, +- `email` -- is accepted for `user`s and will be highlighted in the Reflag UI if available, +- `avatar` -- can be provided for both `user` and `company` and should be an URL to an image. + +```ts +const reflagClient = new ReflagClient({ + publishableKey, + user: { + id: "user_123", + name: "John Doe", + email: "john@acme.com" + avatar: "https://example.com/images/udsy6363" + }, + company: { + id: "company_123", + name: "Acme, Inc", + avatar: "https://example.com/images/31232ds" + }, +}); +``` + +To retrieve flags along with their targeting information, use `getFlag(key: string)`: + +```ts +const huddle = reflagClient.getFlag("huddle"); +// { +// isEnabled: true, +// config: { key: "zoom", payload: { ... } }, +// track: () => Promise +// requestFeedback: (options: RequestFeedbackData) => void +// } +``` + +You can use `getFlags()` to retrieve all enabled flags currently. + +```ts +const flags = reflagClient.getFlags(); +// { +// huddle: { +// isEnabled: true, +// targetingVersion: 42, +// config: ... +// } +// } +``` + +`getFlags()` is meant to be more low-level than `getFlag()` and it typically used +by down-stream clients, like the React SDK. + +Note that accessing `isEnabled` on the object returned by `getFlags` does not automatically +generate a `check` event, contrary to the `isEnabled` property on the object returned by `getFlag`. + +## End-user opt-in + +If a flag has end-user opt-in enabled in Reflag, you can list the opt-in options for the current context and set or cancel opt-in for the current user or company. + +```ts +const optInFlags = reflagClient.getOptInFlags(); +// [{ key, name, description, isEnabled, userOptedIn, companyOptedIn, isOptedIn }] + +try { + const response = await reflagClient.setOptIn("huddle", { + optedIn: true, // Use false to cancel this scope's opt-in. + scope: "user", // Use "company" to change the current company's opt-in. + }); + if (!response?.ok) { + console.error("Could not update opt-in"); + } +} catch (error) { + console.error("Could not update opt-in", error); +} +``` + +By default, `setOptIn()` changes the opt-in for the current user, so the current context must include a `user.id`. To manage the current company's opt-in instead, pass `scope: "company"`; the context must then include a `company.id`. + +User and company opt-ins are managed independently. Setting `optedIn` to `false` removes the opt-in only for the selected scope. For example, cancelling a user's opt-in does not change the company's opt-in for the same flag. + +`setOptIn` returns a promise so you can wait for the new membership state to be synchronized. On success, it resolves after the refreshed flag state has been applied locally, the requested membership change has been confirmed, and `flagsUpdated` listeners have been notified when flags change. + +The promise resolves to a `Response`, or `undefined` if skipped due to invalid input, offline mode etc. Check `response?.ok` for success. + +The `description` comes from the dedicated SDK-facing opt-in description configured in Reflag. + +When using bootstrapped flags, the first `getOptInFlags()` or `getIsLoadingOptInFlags()` call requests a flags refresh. The list call returns the currently available list synchronously, and the loading getter returns `true` until that refresh succeeds or fails. Normal initialization also exposes loading through the client's state. + +Listen for `optInFlagsLoadingUpdated` to update UI when this loading state changes. `flagsUpdated` is emitted when a successful refresh updates the list. + +If fetching opt-in metadata fails, loading ends without exposing an error. Call `reflagClient.refresh()` to retry. + +## Remote config + +Remote config is a dynamic and flexible approach to configuring flag behavior outside of your app – without needing to re-deploy it. + +Similar to `isEnabled`, each flag has a `config` property. This configuration is managed from within Reflag. +It is managed similar to the way access to flags is managed, but instead of the binary `isEnabled` you can have +multiple configuration values which are given to different user/companies. + +```ts +const flags = reflagClient.getFlags(); +// { +// huddle: { +// isEnabled: true, +// targetingVersion: 42, +// config: { +// key: "gpt-3.5", +// payload: { maxTokens: 10000, model: "gpt-3.5-beta1" } +// } +// } +// } +``` + +`key` is mandatory for a config, but if a flag has no config or no config value was matched against the context, the `key` will be `undefined`. Make sure to check against this case when trying to use the configuration in your application. `payload` is an optional JSON value for arbitrary configuration needs. + +Just as `isEnabled`, accessing `config` on the object returned by `getFlags` does not automatically +generate a `check` event, contrary to the `config` property on the object returned by `getFlag`. + +## Server-side rendering and bootstrapping + +For server-side rendered applications, you can render immediately with pre-fetched flag data by bootstrapping the client. + +### Init options bootstrapped + +```typescript +type Configuration = { + logger: console; // by default only logs warn/error, by passing `console` you'll log everything + apiBaseUrl?: "https://front.reflag.com"; + credentials?: "include" | "same-origin" | "omit"; // forwarded to fetch requests; "include" also enables credentials for the default EventSource transport + feedback?: undefined; // See FEEDBACK.md + enableTracking?: true; // set to `false` to stop sending track events and user/company updates to Reflag servers. Useful when you're impersonating a user + offline?: boolean; // Use the SDK in offline mode. Offline mode is useful during testing and local development + bootstrappedState?: { + context: ReflagContext; + flags: FetchedFlags; + flagStateVersion?: number; + }; // Pre-fetched evaluated state from server-side (see Server-side rendering section) + bootstrappedFlags?: FetchedFlags; // Deprecated: use `bootstrappedState` instead +}; +``` + +### Using `bootstrappedState` + +Use the Node SDK's `getFlagsForBootstrap()` method to pre-fetch evaluated state server-side, then pass the returned object directly to the browser client: + +```typescript +// Server-side: Get bootstrapped state using Node SDK +import { ReflagClient as ReflagNodeClient } from "@reflag/node-sdk"; + +const serverClient = new ReflagNodeClient({ secretKey: "your-secret-key" }); +await serverClient.initialize(); + +const bootstrappedState = serverClient.getFlagsForBootstrap({ + user: { id: "user123", name: "John Doe", email: "john@acme.com" }, + company: { id: "company456", name: "Acme Inc", plan: "enterprise" }, +}); + +// Pass the bootstrapped state to the client using your framework's preferred method +app.get("/", (req, res) => { + res.set("Content-Type", "text/html"); + res.send( + Buffer.from( + ` +
`, + ), + ); +}); + +// Client-side: Initialize with pre-fetched evaluated state +import { ReflagClient } from "@reflag/browser-sdk"; + +const reflagClient = new ReflagClient({ + publishableKey: "your-publishable-key", + bootstrappedState, // Contains context, flags, and optional flagStateVersion +}); + +await reflagClient.initialize(); +const { isEnabled } = reflagClient.getFlag("huddle"); +``` + +The `bootstrappedState` object contains: + +- `context`: the evaluation context used on the server +- `flags`: the evaluated raw flags +- `flagStateVersion`: an optional version used to avoid redundant live-update refreshes immediately after bootstrapping + +If you want live flag updates to continue working after bootstrapping, use a recent `@reflag/node-sdk` so `getFlagsForBootstrap()` includes `flagStateVersion`. + +If a bootstrapped application requests opt-in flags, the browser SDK performs one flags refresh. Applications that do not request opt-in data do not make this request. + +If you previously used `bootstrappedFlags`, migrate like this: + +```typescript +// Before +const { flags } = serverClient.getFlagsForBootstrap(context); +const client = new ReflagClient({ + publishableKey, + user: context.user, + company: context.company, + other: context.other, + bootstrappedFlags: flags, +}); + +// After +const bootstrappedState = serverClient.getFlagsForBootstrap(context); +const client = new ReflagClient({ + publishableKey, + bootstrappedState, +}); +``` + +{% hint style="info" %} +After bootstrapping, any live flag updates are fetched directly by the browser SDK from Reflag using the browser-visible context. If your bootstrapped snapshot depends on server-only or secret context that is not available in the browser, later live refreshes may differ. In that case, keep `enableLiveFlagUpdates` disabled. + +Requesting opt-in flags also triggers a browser-side refresh, even when `enableLiveFlagUpdates` is disabled. +{% endhint %} + +This eliminates loading states and removes the initial render's dependency on the flags API. + +## Context management + +### Updating user/company/other context + +Attributes given for the user/company/other context in the ReflagClient constructor can be updated for use in flag targeting evaluation with the `updateUser()`, `updateCompany()` and `updateOtherContext()` methods. +They return a promise which resolves once the flags have been re-evaluated follow the update of the attributes. + +{% hint style="info" %} +{% endhint %} + +### setContext() + +The `setContext()` method allows you to replace the entire context (user, company, and other attributes) at once. This method is useful when you need to completely change the context, such as when a user logs in or switches between different accounts. + +```ts +await reflagClient.setContext({ + user: { + id: "new-user-123", + name: "Jane Doe", + email: "jane@example.com", + role: "admin", + }, + company: { + id: "company-456", + name: "New Company Inc", + plan: "enterprise", + }, + other: { + feature: "beta", + locale: "en-US", + }, +}); +``` + +The method will: + +- Replace the entire context with the new values +- Re-evaluate all flags based on the new context +- Update the user and company information on Reflag servers +- Return a promise that resolves once the flags have been re-evaluated + +### getContext() + +The `getContext()` method returns the current context being used for flag evaluation. This is useful for debugging or when you need to inspect the current user, company, and other attributes. + +```ts +const currentContext = reflagClient.getContext(); +console.log(currentContext); +// { +// user: { id: "user-123", name: "John Doe", email: "john@example.com" }, +// company: { id: "company-456", name: "Acme Inc", plan: "enterprise" }, +// other: { locale: "en-US", feature: "beta" } +// } +``` + +The returned context object contains: + +- `user`: Current user attributes (if any) +- `company`: Current company attributes (if any) +- `other`: Additional context attributes not related to user or company + +## Toolbar + +The Reflag Toolbar is great for toggling flags on/off for yourself to ensure that everything works both when a flag is on and when it's off. + +Toolbar screenshot + +The toolbar will automatically appear on `localhost`. However, it can also be incredibly useful in production. +You have full control over when it appears through the `toolbar` configuration option passed to the `ReflagClient`. + +You can pass a simple boolean to force the toolbar to appear/disappear: + +```typescript +const client = new ReflagClient({ + // show the toolbar even in production if the user is an internal/admin user + toolbar: user?.isInternal, + ... +}); +``` + +You can also configure the position of the toolbar on the screen: + +```typescript +const client = new ReflagClient({ + toolbar: { + show: true; + position: { + placement: "bottom-left", + offset: {x: "1rem", y: "1rem"} + } + } + ... +}) +``` + +See [the reference](globals.md#toolbaroptions) for details. + +## Qualitative feedback on beta flags + +Reflag can collect qualitative feedback from your users in the form of a [Customer Satisfaction Score](https://en.wikipedia.org/wiki/Customer_satisfaction) and a comment. + +### Automated feedback collection + +The Reflag Browser SDK comes with automated feedback collection mode enabled by default, which lets the Reflag service ask your users for feedback for relevant flags just after they've used them. + +{% hint style="info" %} +To get started with automatic feedback collection, make sure you've set `user` in the `ReflagClient` constructor. +{% endhint %} + +Automated feedback surveys work even if you're not using the SDK to send events to Reflag. +It works because the Reflag Browser SDK maintains a live connection to Reflag's servers and can automatically show a feedback prompt whenever the Reflag servers determines that an event should trigger a prompt - regardless of how this event is sent to Reflag. + +You can find all the options to make changes to the default behavior in the [Reflag feedback documentation](feedback.md). + +### Reflag feedback UI + +Reflag can assist you with collecting your user's feedback by offering a pre-built UI, allowing you to get started with minimal code and effort. + +[Read the Reflag feedback UI documentation](feedback.md) + +### Reflag feedback SDK + +Feedback can be submitted to Reflag using the SDK: + +```ts +reflagClient.feedback({ + flagKey: "my-flag-key", // String (required), copy from Flag feedback tab + score: 5, // Number: 1-5 (optional) + comment: "Absolutely stellar work!", // String (optional) +}); +``` + +### Reflag feedback API + +If you are not using the Reflag Browser SDK, you can still submit feedback using the HTTP API. + +See details in [Feedback HTTP API](https://docs.reflag.com/api/http-api#post-feedback) + +## Tracking flag usage + +The `track` function lets you send events to Reflag to denote flag usage. +By default Reflag expects event names to align with the flag keys, but +you can customize it as you wish. + +```ts +reflagClient.track("huddle", { voiceHuddle: true }); +``` + +## Event listeners + +Event listeners allow for capturing various events occurring in the `ReflagClient`. This is useful to build integrations with other system or for various debugging purposes. The available events are: + +- `check`: Your code used `isEnabled` or `config` for a flag +- `flagsUpdated`: Flags were updated. Either because they were loaded as part of initialization or because the user/company updated +- `optInFlagsLoadingUpdated`: The opt-in flag loading state changed +- `user`: User information updated (similar to the `identify` call used in tracking terminology) +- `company`: Company information updated (sometimes to the `group` call used in tracking terminology) +- `track`: Track event occurred. + +Use the `on()` method to add an event listener to respond to certain events. See the API reference for details on each hook. + +```ts +import { ReflagClient, CheckEvent, RawFlags } from "@reflag/browser-sdk"; + +const client = new ReflagClient({ + // options +}); + +// or add the hooks after construction: +const unsub = client.on("check", (check: CheckEvent) => + console.log(`Check event ${check}`), +); +// use the returned function to unsubscribe, or call `off()` with the same arguments again +unsub(); +``` + +## Zero PII + +The Reflag Browser SDK doesn't collect any metadata and HTTP IP addresses are _not_ being stored. + +For tracking individual users, we recommend using something like database ID as userId, as it's unique and doesn't include any PII (personal identifiable information). If, however, you're using e.g. email address as userId, but prefer not to send any PII to Reflag, you can hash the sensitive data before sending it to Reflag: + +```ts +import reflag from "@reflag/browser-sdk"; +import { sha256 } from "crypto-hash"; + +reflag.user(await sha256("john_doe")); +``` + +## Use of cookies + +The Reflag Browser SDK uses a couple of cookies to support automated feedback surveys. These cookies are not used for tracking purposes and thus should not need to appear in cookie consent forms. + +The two cookies are: + +- `reflag-prompt-${userId}`: store the last automated feedback prompt message ID received to avoid repeating surveys +- `reflag-token-${userId}`: caching a token used to connect to Reflag's live messaging infrastructure that is used to deliver automated feedback surveys in real time. + +## TypeScript + +Types are bundled together with the library and exposed automatically when importing through a package manager. + +## Content Security Policy (CSP) + +If you are running with strict Content Security Policies active on your website, you will need to enable these directives in order to use the SDK: + +| Directive | Values | Reason | +| ----------- | ---------------------------------------------------- | ------------------------------------------------------------------------------------------------------- | +| connect-src | [https://front.reflag.com](https://front.reflag.com) | API requests plus Server-Sent Events for live flag updates and automated feedback surveys. | +| style-src | 'unsafe-inline' | The feedback UI is styled with inline styles. Not having this directive results unstyled HTML elements. | + +If you are including the Reflag tracking SDK with a ` +``` + +## Internationalization (i18n) + +By default, the feedback UI is written in English. However, you can supply your own +translations by passing an object in the options to either or both of the +`new ReflagClient(options)` or `reflagClient.requestFeedback(options)` calls. +These translations will replace the English ones used by the feedback interface. +See examples below. + +![image](https://github.com/reflagcom/javascript/assets/331790/68805b38-e9f6-4de5-9f55-188216983e3c) + +See [default English localization keys](https://github.com/reflagcom/javascript/tree/b4fe5b3d9386b87c6546175c323862d9878e1430/packages/browser-sdk/src/feedback/ui/config/defaultTranslations.tsx) +for a reference of what translation keys can be supplied. + +### Static language configuration + +If you know the language at page load, you can configure your translation keys while +initializing the Reflag Browser SDK: + +```typescript +new ReflagClient({ + publishableKey: "my-publishable-key", + feedback: { + ui: { + translations: { + DefaultQuestionLabel: + "Dans quelle mesure êtes-vous satisfait de cette fonctionnalité ?", + QuestionPlaceholder: + "Comment pouvons-nous améliorer cette fonctionnalité ?", + ScoreStatusDescription: "Choisissez une note et laissez un commentaire", + ScoreStatusLoading: "Chargement...", + ScoreStatusReceived: "La note a été reçue !", + ScoreVeryDissatisfiedLabel: "Très insatisfait", + ScoreDissatisfiedLabel: "Insatisfait", + ScoreNeutralLabel: "Neutre", + ScoreSatisfiedLabel: "Satisfait", + ScoreVerySatisfiedLabel: "Très satisfait", + SuccessMessage: "Merci d'avoir envoyé vos commentaires!", + SendButton: "Envoyer", + }, + }, + }, +}); +``` + +### Runtime language configuration + +If you only know the user's language after the page has loaded, you can provide +translations to either the `reflagClient.requestFeedback(options)` call or +the `autoFeedbackHandler` option before the feedback interface opens. +See examples below. + +```typescript +reflagClient.requestFeedback({ + ... // Other options + translations: { + // your translation keys + } +}) +``` + +### Translations + +When you are collecting feedback through the Reflag automation, you can intercept +the default prompt handling and override the defaults. + +If you set the prompt question in the Reflag app to be one of your own translation +keys, you can even get a translated version of the question you want to ask your +customer in the feedback UI. + +```javascript +new ReflagClient({ + publishableKey: "reflag-publishable-key", + feedback: { + autoFeedbackHandler: (message, handlers) => { + const translatedQuestion = + i18nLookup[message.question] ?? message.question; + handlers.openFeedbackForm({ + title: translatedQuestion, + translations: { + // your static translation keys + }, + }); + }, + }, +}); +``` + +## Custom styling + +You can adapt parts of the look of the Reflag feedback UI by applying CSS custom +properties to your page in your CSS `:root`-scope. + +For example, a dark mode theme might look like this: + +![image](https://github.com/reflagcom/javascript/assets/34348/5d579b7b-a830-4530-8b40-864488a8597e) + +```css +:root { + --reflag-feedback-dialog-background-color: #1e1f24; + --reflag-feedback-dialog-color: rgba(255, 255, 255, 0.92); + --reflag-feedback-dialog-secondary-color: rgba(255, 255, 255, 0.3); + --reflag-feedback-dialog-border: rgba(255, 255, 255, 0.16); + --reflag-feedback-dialog-primary-button-background-color: #655bfa; + --reflag-feedback-dialog-primary-button-color: white; + --reflag-feedback-dialog-input-border-color: rgba(255, 255, 255, 0.16); + --reflag-feedback-dialog-input-focus-border-color: rgba(255, 255, 255, 0.3); + --reflag-feedback-dialog-error-color: #f56565; + + --reflag-feedback-dialog-rating-1-color: #ed8936; + --reflag-feedback-dialog-rating-1-background-color: #7b341e; + --reflag-feedback-dialog-rating-2-color: #dd6b20; + --reflag-feedback-dialog-rating-2-background-color: #652b19; + --reflag-feedback-dialog-rating-3-color: #787c91; + --reflag-feedback-dialog-rating-3-background-color: #3e404c; + --reflag-feedback-dialog-rating-4-color: #38a169; + --reflag-feedback-dialog-rating-4-background-color: #1c4532; + --reflag-feedback-dialog-rating-5-color: #48bb78; + --reflag-feedback-dialog-rating-5-background-color: #22543d; + + --reflag-feedback-dialog-submitted-check-background-color: #38a169; + --reflag-feedback-dialog-submitted-check-color: #ffffff; +} +``` + +Other examples of custom styling can be found in our [development example style-sheet](https://github.com/reflagcom/javascript/tree/b4fe5b3d9386b87c6546175c323862d9878e1430/packages/browser-sdk/src/feedback/ui/index.css). + +## Using your own UI to collect feedback + +You may have very strict design guidelines for your app and maybe the Reflag feedback +UI doesn't quite work for you. In this case, you can implement your own feedback +collection mechanism, which follows your own design guidelines. This is the data +type you need to collect: + +```typescript +type DataToCollect = { + // Customer satisfaction score + score?: 1 | 2 | 3 | 4 | 5; + + // The comment. + comment?: string; +}; +``` + +Either `score` or `comment` must be defined in order to pass validation in the +Reflag API. + +### Manual feedback collection with custom UI + +Examples of a HTML-form that collects the relevant data can be found +in [feedback.html](https://github.com/reflagcom/javascript/tree/b4fe5b3d9386b87c6546175c323862d9878e1430/packages/browser-sdk/example/feedback/feedback.html) and [feedback.jsx](https://github.com/reflagcom/javascript/tree/b4fe5b3d9386b87c6546175c323862d9878e1430/packages/browser-sdk/example/feedback/Feedback.jsx). + +Once you have collected the feedback data, pass it along to `reflagClient.feedback()`: + +```javascript +reflagClient.feedback({ + flagKey: "reflag-flag-key", + userId: "your-user-id", + score: 5, + comment: "Best thing I've ever tried!", +}); +``` + +### Intercepting automated feedback survey events + +When using automated feedback surveys, the Reflag service will, when specified, +send a feedback prompt message to your user's instance of the Reflag Browser SDK. +This will result in the feedback UI being opened. + +You can intercept this behavior and open your own custom feedback collection form: + +```typescript +new ReflagClient({ + publishableKey: "reflag-publishable-key", + feedback: { + autoFeedbackHandler: async (promptMessage, handlers) => { + // This opens your custom UI + customFeedbackCollection({ + // The question configured in the Reflag UI for the flag + question: promptMessage.question, + // When the user successfully submits feedback data. + // Use this instead of `reflagClient.feedback()`, otherwise + // the feedback prompt handler will keep being called + // with the same prompt message + onFeedbackSubmitted: (feedback) => { + handlers.reply(feedback); + }, + // When the user closes the custom feedback form + // without leaving any response. + // It is important to feed this back, otherwise + // the feedback prompt handler will keep being called + // with the same prompt message + onFeedbackDismissed: () => { + handlers.reply(null); + }, + }); + }, + }, +}); +``` diff --git a/legacy/v1/browser-sdk/globals.md b/legacy/v1/browser-sdk/globals.md new file mode 100644 index 0000000..d4a0919 --- /dev/null +++ b/legacy/v1/browser-sdk/globals.md @@ -0,0 +1,5248 @@ +--- +layout: + visible: true +title: + visible: true +description: + visible: false +tableOfContents: + visible: true +outline: + visible: true +pagination: + visible: true +--- + +{% hint style="info" %} +**Protocol v1 — legacy.** [Current v2 documentation](../../../supported-languages/browser-sdk/globals.md) · [Migration guide](../../../supported-languages/migrating-from-v1.md) +{% endhint %} + +# @reflag/browser-sdk + +## Classes + +### ReflagClient + +ReflagClient lets you interact with the Reflag API. + +#### Constructors + +### new ReflagClient() + +```ts +new ReflagClient(opts: InitOptions): ReflagClient +``` + +Create a new ReflagClient instance. + +###### Parameters + + + + + + + + + + + + + + +
ParameterType
+ +`opts` + + + +[`InitOptions`](globals.md#initoptions) + +
+ +###### Returns + +[`ReflagClient`](globals.md#reflagclient) + +#### Properties + + + + + + + + + + + + + + + + +
PropertyModifierType
+ + `logger` + + + +`readonly` + + + +[`Logger`](globals.md#logger) + +
+ +#### Methods + +### applyBootstrappedState() + +```ts +applyBootstrappedState(bootstrappedState: BootstrappedState, triggerEvent: boolean): void +``` + +###### Parameters + + + + + + + + + + + + + + + + + + + + + +
ParameterTypeDefault value
+ +`bootstrappedState` + + + +[`BootstrappedState`](globals.md#bootstrappedstate) + + + +`undefined` + +
+ +`triggerEvent` + + + +`boolean` + + + +`true` + +
+ +###### Returns + +`void` + +### feedback() + +```ts +feedback(payload: Feedback): Promise< + | undefined +| Response> +``` + +Submit user feedback to Reflag. Must include either `score` or `comment`, or both. + +###### Parameters + + + + + + + + + + + + + + + + +
ParameterTypeDescription
+ +`payload` + + + +[`Feedback`](globals.md#feedback) + + + +The feedback details to submit. + +
+ +###### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\< + \| `undefined` + \| [`Response`](https://developer.mozilla.org/docs/Web/API/Response)\> + +The server response. + +### getConfig() + +```ts +getConfig(): Config +``` + +Get the current configuration. + +###### Returns + +[`Config`](globals.md#config) + +### getContext() + +```ts +getContext(): ReflagContext +``` + +Get the current context. + +###### Returns + +[`ReflagContext`](globals.md#reflagcontext) + +### ~~getFeature()~~ + +```ts +getFeature(flagKey: string): Flag +``` + +###### Parameters + + + + + + + + + + + + + + +
ParameterType
+ +`flagKey` + + + +`string` + +
+ +###### Returns + +[`Flag`](globals.md#flag) + +###### Deprecated + +Use `getFlag` instead. + +### ~~getFeatures()~~ + +```ts +getFeatures(): RawFlags +``` + +###### Returns + +[`RawFlags`](globals.md#rawflags) + +###### Deprecated + +Use `getFlags` instead. + +### getFlag() + +```ts +getFlag(flagKey: string): Flag +``` + +Return a flag. Accessing `isEnabled` or `config` will automatically send a `check` event. + +###### Parameters + + + + + + + + + + + + + + + + +
ParameterTypeDescription
+ +`flagKey` + + + +`string` + + + +The key of the flag to get. + +
+ +###### Returns + +[`Flag`](globals.md#flag) + +A flag. + +### getFlags() + +```ts +getFlags(): RawFlags +``` + +Returns a map of enabled flags. +Accessing a flag will *not* send a check event +and `isEnabled` does not take any flag overrides +into account. + +###### Returns + +[`RawFlags`](globals.md#rawflags) + +Map of flags. + +### getIsLoadingOptInFlags() + +```ts +getIsLoadingOptInFlags(): boolean +``` + +Returns whether opt-in flags are loading for the current context. + +Calling this method requests opt-in metadata if it is not already available. + +###### Returns + +`boolean` + +### getOptInFlags() + +```ts +getOptInFlags(): OptInFlag[] +``` + +Returns opt-in-enabled flags for the current context. + +###### Returns + +[`OptInFlag`](globals.md#optinflag)[] + +### getState() + +```ts +getState(): State +``` + +###### Returns + +[`State`](globals.md#state) + +### initialize() + +```ts +initialize(): Promise +``` + +Initialize the Reflag SDK. + +Must be called before calling other SDK methods. + +###### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> + +### off() + +```ts +off(type: THookType, handler: (args0: HookArgs[THookType]) => void): void +``` + +Remove an event listener + +###### Type Parameters + + + + + + + + + + + + +
Type Parameter
+ +`THookType` *extends* keyof [`HookArgs`](globals.md#hookargs) + +
+ +###### Parameters + + + + + + + + + + + + + + + + + + + + + +
ParameterTypeDescription
+ +`type` + + + +`THookType` + + + +Type of event to remove. + +
+ +`handler` + + + +(`args0`: [`HookArgs`](globals.md#hookargs)\[`THookType`\]) => `void` + + + +The same function that was passed to `on`. + +
+ +###### Returns + +`void` + +A function to remove the hook. + +### on() + +```ts +on(type: THookType, handler: (args0: HookArgs[THookType]) => void): () => void +``` + +Add an event listener + +###### Type Parameters + + + + + + + + + + + + +
Type Parameter
+ +`THookType` *extends* keyof [`HookArgs`](globals.md#hookargs) + +
+ +###### Parameters + + + + + + + + + + + + + + + + + + + + + +
ParameterTypeDescription
+ +`type` + + + +`THookType` + + + +Type of events to listen for + +
+ +`handler` + + + +(`args0`: [`HookArgs`](globals.md#hookargs)\[`THookType`\]) => `void` + + + +The function to call when the event is triggered. + +
+ +###### Returns + +`Function` + +A function to remove the hook. + +###### Returns + +`void` + +### refresh() + +```ts +refresh(): Promise +``` + +Force refresh flags from the API, bypassing cache. + +###### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`undefined` \| [`RawFlags`](globals.md#rawflags)\> + +### requestFeedback() + +```ts +requestFeedback(options: RequestFeedbackData): void +``` + +Display the Reflag feedback form UI programmatically. + +This can be used to collect feedback from users in Reflag in cases where Automated Feedback Surveys isn't appropriate. + +###### Parameters + + + + + + + + + + + + + + +
ParameterType
+ +`options` + + + +[`RequestFeedbackData`](globals.md#requestfeedbackdata) + +
+ +###### Returns + +`void` + +### setContext() + +```ts +setContext(context: ReflagDeprecatedContext): Promise +``` + +Update the context. +Replaces the existing context with a new context. + +###### Parameters + + + + + + + + + + + + + + + + +
ParameterTypeDescription
+ +`context` + + + +[`ReflagDeprecatedContext`](globals.md#reflagdeprecatedcontext) + + + +The context to update. + +
+ +###### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> + +### setOptIn() + +```ts +setOptIn(flagKey: string, options: SetOptInOptions): Promise< + | undefined +| Response> +``` + +Set whether the current user or company has opted into a flag. + +A successful Response is returned after the refreshed flag state confirms +the membership change. HTTP failures return a non-OK Response without +refreshing flags. Offline mode, invalid arguments, or missing scoped context +return undefined. Network and confirmation failures reject the promise; +a confirmation failure may occur after membership changed remotely. + +###### Parameters + + + + + + + + + + + + + + + + + + +
ParameterType
+ +`flagKey` + + + +`string` + +
+ +`options` + + + +[`SetOptInOptions`](globals.md#setoptinoptions) + +
+ +###### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\< + \| `undefined` + \| [`Response`](https://developer.mozilla.org/docs/Web/API/Response)\> + +### showToolbarToggle() + +```ts +showToolbarToggle(position?: ToolbarPosition): void +``` + +###### Parameters + + + + + + + + + + + + + + +
ParameterType
+ +`position`? + + + +[`ToolbarPosition`](globals.md#toolbarposition) + +
+ +###### Returns + +`void` + +### stop() + +```ts +stop(): Promise +``` + +Stop the SDK. +This will stop any automated feedback surveys. + +###### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> + +### track() + +```ts +track(eventName: string, attributes?: + | null + | Record): Promise< + | undefined +| Response> +``` + +Track an event in Reflag. + +###### Parameters + + + + + + + + + + + + + + + + + + + + + +
ParameterTypeDescription
+ +`eventName` + + + +`string` + + + +The name of the event. + +
+ +`attributes`? + + + + \| `null` \| [`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, `any`\> + + + +Any attributes you want to attach to the event. + +
+ +###### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\< + \| `undefined` + \| [`Response`](https://developer.mozilla.org/docs/Web/API/Response)\> + +### updateCompany() + +```ts +updateCompany(company: {}): Promise +``` + +Update the company context. +Performs a shallow merge with the existing company context. +It will not update the context if nothing has changed. + +###### Parameters + + + + + + + + + + + + + + + + +
ParameterTypeDescription
+ +`company` + + + +\{\} + + + +The company details. + +
+ +###### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> + +### updateFlags() + +```ts +updateFlags( + flags: RawFlags, + triggerEvent: boolean, + flagStateVersion?: number): void +``` + +Update the flags. + +###### Parameters + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ParameterTypeDefault valueDescription
+ +`flags` + + + +[`RawFlags`](globals.md#rawflags) + + + +`undefined` + + + +The flags to update. + +
+ +`triggerEvent` + + + +`boolean` + + + +`true` + + + +Whether to trigger the `flagsUpdated` event. + +
+ +`flagStateVersion`? + + + +`number` + + + +`undefined` + + + +‐ + +
+ +###### Returns + +`void` + +### updateOtherContext() + +```ts +updateOtherContext(otherContext: {}): Promise +``` + +Update the company context. +Performs a shallow merge with the existing company context. +It will not update the context if nothing has changed. + +###### Parameters + + + + + + + + + + + + + + + + +
ParameterTypeDescription
+ +`otherContext` + + + +\{\} + + + +Additional context. + +
+ +###### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> + +### updateUser() + +```ts +updateUser(user: {}): Promise +``` + +Update the user context. +Performs a shallow merge with the existing user context. +It will not update the context if nothing has changed. + +###### Parameters + + + + + + + + + + + + + + +
ParameterType
+ +`user` + + + +\{\} + +
+ +###### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> + +## Interfaces + +### CheckEvent + +Event representing checking the flag evaluation result + +#### Properties + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyTypeDescription
+ + `action` + + + +`"check-is-enabled"` \| `"check-config"` + + + +`check-is-enabled` means `isEnabled` was checked, `check-config` means `config` was checked. + +
+ + `evaluationErrors?` + + + +\{ `code`: `string`; `field`: `string`; `message`: `string`; `operator`: `string`; \}[] + + + +Non-fatal diagnostics produced while evaluating the flag. + +
+ + `key` + + + +`string` + + + +Flag key. + +
+ + ~~`missingContextFields?`~~ + + + +`string`[] + + + +Missing context fields. + +**Deprecated** + +Use `evaluationErrors` and check for `MISSING_CONTEXT_FIELD`. + +
+ + `ruleEvaluationResults?` + + + +`boolean`[] + + + +Rule evaluation results. + +
+ + `value?` + + + + \| `boolean` \| \{ `key`: `string`; `payload`: `any`; \} + + + +Result of flag or configuration evaluation. +If `action` is `check-is-enabled`, this is the result of the flag evaluation and `value` is a boolean. +If `action` is `check-config`, this is the result of the configuration evaluation. + +
+ + `version?` + + + +`number` + + + +Version of targeting rules. + +
+ +*** + +### CompanyContext + +Context is a set of key-value pairs. +This is used to determine if feature targeting matches and to track events. +Id should always be present so that it can be referenced to an existing company. + +#### Indexable + +```ts +[key: string]: ContextValue +``` + +#### Properties + + + + + + + + + + + + + + + + + + + + + +
PropertyTypeDescription
+ + `id` + + + +`undefined` \| `string` \| `number` + + + +Company id + +
+ + `name?` + + + +`string` + + + +Company name + +
+ +*** + +### Config + +ReflagClient configuration. + +#### Properties + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyTypeDescription
+ + `apiBaseUrl` + + + +`string` + + + +Base URL of Reflag servers. + +
+ + `appBaseUrl` + + + +`string` + + + +Base URL of the Reflag web app. + +
+ + `bootstrapped` + + + +`boolean` + + + +Whether the client is bootstrapped. + +
+ + `enableTracking` + + + +`boolean` + + + +Whether to enable tracking. + +
+ + `offline` + + + +`boolean` + + + +Whether to enable offline mode. + +
+ + `sseBaseUrl` + + + +`string` + + + +Base URL used for pubsub SSE connections. +Defaults to `apiBaseUrl`. + +
+ +*** + +### FeedbackScoreSubmission + +#### Properties + + + + + + + + + + + + + + + + + + + + + + +
PropertyType
+ + `feedbackId?` + + + +`string` + +
+ + `question` + + + +`string` + +
+ + `score` + + + +`number` + +
+ +*** + +### FeedbackSubmission + +#### Properties + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyType
+ + `comment` + + + +`string` + +
+ + `feedbackId?` + + + +`string` + +
+ + `question` + + + +`string` + +
+ + `score` + + + +`number` + +
+ +*** + +### Flag + +#### Properties + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyTypeDescription
+ + `config` + + + +[`FlagRemoteConfig`](globals.md#flagremoteconfig) + + + +‐ + +
+ + `isEnabled` + + + +`boolean` + + + +Result of flag flag evaluation. +Note: Does not take local overrides into account. + +
+ + `isEnabledOverride` + + + +`null` \| `boolean` + + + +The current override status of isEnabled for the flag. + +
+ + `requestFeedback` + + + +(`options`: [`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys)\<[`RequestFeedbackData`](globals.md#requestfeedbackdata), `"featureId"` \| `"flagKey"`\>) => `void` + + + +Function to request feedback for this flag. + +
+ + `track` + + + +() => [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\< \| `undefined` \| [`Response`](https://developer.mozilla.org/docs/Web/API/Response)\> + + + +Function to send analytics events for this flag. + +
+ +#### Methods + +### setIsEnabledOverride() + +```ts +setIsEnabledOverride(isEnabled: null | boolean): void +``` + +Set the override status for isEnabled for the flag. +Set to `null` to remove the override. + +###### Parameters + + + + + + + + + + + + + + +
ParameterType
+ +`isEnabled` + + + +`null` \| `boolean` + +
+ +###### Returns + +`void` + +*** + +### HookArgs + +#### Properties + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyTypeDescription
+ + `check` + + + +[`CheckEvent`](globals.md#checkevent) + + + +‐ + +
+ + `company` + + + +[`CompanyContext`](globals.md#companycontext) + + + +‐ + +
+ + ~~`featuresUpdated`~~ + + + +[`RawFlags`](globals.md#rawflags) + + + +**Deprecated** + +Use `flagsUpdated` instead. + +
+ + `flagsUpdated` + + + +[`RawFlags`](globals.md#rawflags) + + + +‐ + +
+ + `optInFlagsLoadingUpdated` + + + +`boolean` + + + +‐ + +
+ + `stateUpdated` + + + +[`State`](globals.md#state) + + + +‐ + +
+ + `track` + + + +[`TrackEvent`](globals.md#trackevent) + + + +‐ + +
+ + `user` + + + +[`UserContext`](globals.md#usercontext) + + + +‐ + +
+ +*** + +### Logger + +#### Methods + +### debug() + +```ts +debug(message: string, ...args: any[]): void +``` + +###### Parameters + + + + + + + + + + + + + + + + + + +
ParameterType
+ +`message` + + + +`string` + +
+ +...`args` + + + +`any`[] + +
+ +###### Returns + +`void` + +### error() + +```ts +error(message: string, ...args: any[]): void +``` + +###### Parameters + + + + + + + + + + + + + + + + + + +
ParameterType
+ +`message` + + + +`string` + +
+ +...`args` + + + +`any`[] + +
+ +###### Returns + +`void` + +### info() + +```ts +info(message: string, ...args: any[]): void +``` + +###### Parameters + + + + + + + + + + + + + + + + + + +
ParameterType
+ +`message` + + + +`string` + +
+ +...`args` + + + +`any`[] + +
+ +###### Returns + +`void` + +### warn() + +```ts +warn(message: string, ...args: any[]): void +``` + +###### Parameters + + + + + + + + + + + + + + + + + + +
ParameterType
+ +`message` + + + +`string` + +
+ +...`args` + + + +`any`[] + +
+ +###### Returns + +`void` + +*** + +### OnScoreSubmitResult + +#### Properties + + + + + + + + + + + + + + +
PropertyType
+ + `feedbackId` + + + +`string` + +
+ +*** + +### OpenFeedbackFormOptions + +#### Properties + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyTypeDescription
+ + `key` + + + +`string` + + + +‐ + +
+ + `onClose?` + + + +() => `void` + + + +‐ + +
+ + `onDismiss?` + + + +() => `void` + + + +‐ + +
+ + `onScoreSubmit?` + + + +(`data`: [`FeedbackScoreSubmission`](globals.md#feedbackscoresubmission)) => [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<[`OnScoreSubmitResult`](globals.md#onscoresubmitresult)\> + + + +‐ + +
+ + `onSubmit` + + + +(`data`: [`FeedbackSubmission`](globals.md#feedbacksubmission)) => \| `void` \| [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> + + + +‐ + +
+ + `openWithCommentVisible?` + + + +`boolean` + + + +Open the form with both the score and comment fields visible. +Defaults to `false` + +
+ + `position?` + + + +[`Position`](globals.md#position) + + + +Control the placement and behavior of the feedback form. + +
+ + `title?` + + + +`string` + + + +‐ + +
+ + `translations?` + + + +[`Partial`](https://www.typescriptlang.org/docs/handbook/utility-types.html#partialtype)\<[`FeedbackTranslations`](globals.md#feedbacktranslations)\> + + + +Add your own custom translations for the feedback form. +Undefined translation keys fall back to english defaults. + +
+ +*** + +### ReflagContext + +Context is a set of key-value pairs. +This is used to determine if feature targeting matches and to track events. + +#### Extended by + +- [`ReflagDeprecatedContext`](globals.md#reflagdeprecatedcontext) + +#### Properties + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyTypeDescription
+ + `company?` + + + +[`CompanyContext`](globals.md#companycontext) + + + +Company related context. If you provide `id` Reflag will enrich the evaluation context with +company attributes on Reflag servers. + +
+ + `other?` + + + +[`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, [`ContextValue`](globals.md#contextvalue)\> + + + +Context which is not related to a user or a company. + +
+ + `user?` + + + +[`UserContext`](globals.md#usercontext) + + + +User related context. If you provide `id` Reflag will enrich the evaluation context with +user attributes on Reflag servers. + +
+ +*** + +### ~~ReflagDeprecatedContext~~ + +**`Internal`** + +#### Deprecated + +Use `ReflagContext` instead, this interface will be removed in the next major version + +#### Extends + +- [`ReflagContext`](globals.md#reflagcontext) + +#### Properties + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyTypeDescription
+ + ~~`company?`~~ + + + +[`CompanyContext`](globals.md#companycontext) + + + +Company related context. If you provide `id` Reflag will enrich the evaluation context with +company attributes on Reflag servers. + +
+ + ~~`other?`~~ + + + +[`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, [`ContextValue`](globals.md#contextvalue)\> + + + +Context which is not related to a user or a company. + +
+ + ~~`otherContext?`~~ + + + +[`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, [`ContextValue`](globals.md#contextvalue)\> + + + +Context which is not related to a user or a company. + +**Deprecated** + +Use `other` instead, this property will be removed in the next major version + +
+ + ~~`user?`~~ + + + +[`UserContext`](globals.md#usercontext) + + + +User related context. If you provide `id` Reflag will enrich the evaluation context with +user attributes on Reflag servers. + +
+ +*** + +### ToolbarPosition + +#### Properties + + + + + + + + + + + + + + + + + + +
PropertyType
+ + `offset?` + + + +[`Offset`](globals.md#offset) + +
+ + `placement` + + + +[`DialogPlacement`](globals.md#dialogplacement) + +
+ +*** + +### UserContext + +Context is a set of key-value pairs. +This is used to determine if feature targeting matches and to track events. +Id should always be present so that it can be referenced to an existing user. + +#### Indexable + +```ts +[key: string]: ContextValue +``` + +#### Properties + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyTypeDescription
+ + `email?` + + + +`string` + + + +User email + +
+ + `id` + + + +`undefined` \| `string` \| `number` + + + +User id + +
+ + `name?` + + + +`string` + + + +User name + +
+ +## Type Aliases + +### BootstrappedState + +```ts +type BootstrappedState = { + context: ReflagContext; + flags: RawFlags; + flagStateVersion: number; +}; +``` + +Pre-fetched evaluated state used to bootstrap the client. + +#### Type declaration + + + + + + + + + + + + + + + + + + + + + + +
NameType
+ + `context` + + + +[`ReflagContext`](globals.md#reflagcontext) + +
+ + `flags` + + + +[`RawFlags`](globals.md#rawflags) + +
+ + `flagStateVersion`? + + + +`number` + +
+ +*** + +### ContextValue + +```ts +type ContextValue = DefinedContextValue | undefined; +``` + +A context value. Object properties set to `undefined` are omitted. + +*** + +### DefinedContextValue + +```ts +type DefinedContextValue = + | string + | number + | boolean + | null + | DefinedContextValue[] +| {}; +``` + +A JSON-compatible context value that is not `undefined`. + +*** + +### DialogPlacement + +```ts +type DialogPlacement = "bottom-right" | "bottom-left" | "top-right" | "top-left"; +``` + +*** + +### EventSourceFactory() + +```ts +type EventSourceFactory = (url: string) => EventSourceLike; +``` + +#### Parameters + + + + + + + + + + + + + + +
ParameterType
+ +`url` + + + +`string` + +
+ +#### Returns + +[`EventSourceLike`](globals.md#eventsourcelike) + +*** + +### EventSourceLike + +```ts +type EventSourceLike = { + addEventListener: (type: string, cb: (event: any) => void) => void; + close: () => void; +}; +``` + +#### Type declaration + + + + + + + + + + + + + + + + + + +
NameType
+ + `addEventListener` + + + +(`type`: `string`, `cb`: (`event`: `any`) => `void`) => `void` + +
+ + `close` + + + +() => `void` + +
+ +*** + +### FallbackFlagOverride + +```ts +type FallbackFlagOverride = + | { + key: string; + payload: any; + } + | true; +``` + +*** + +### Feedback + +```ts +type Feedback = UnassignedFeedback & { + companyId: string; + userId: string; +}; +``` + +#### Type declaration + + + + + + + + + + + + + + + + + + + + + +
NameTypeDescription
+ +`companyId`? + + + +`string` + + + +Company ID from your own application. + +
+ +`userId`? + + + +`string` + + + +User ID from your own application. + +
+ +*** + +### FeedbackOptions + +```ts +type FeedbackOptions = { + autoFeedbackHandler: FeedbackPromptHandler; + enableAutoFeedback: boolean; + ui: { + position: Position; + translations: Partial; + }; +}; +``` + +#### Type declaration + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameTypeDescription
+ + `autoFeedbackHandler`? + + + +[`FeedbackPromptHandler`](globals.md#feedbackprompthandler) + + + +‐ + +
+ + `enableAutoFeedback`? + + + +`boolean` + + + +Enables automatic feedback prompting if it's set up in Reflag + +
+ + `ui`? + + + +\{ + `position`: [`Position`](globals.md#position); + `translations`: [`Partial`](https://www.typescriptlang.org/docs/handbook/utility-types.html#partialtype)\<[`FeedbackTranslations`](globals.md#feedbacktranslations)\>; + \} + + + +With these options you can override the look of the feedback prompt + +
+ +`ui.position`? + + + +[`Position`](globals.md#position) + + + +Control the placement and behavior of the feedback form. + +
+ +`ui.translations`? + + + +[`Partial`](https://www.typescriptlang.org/docs/handbook/utility-types.html#partialtype)\<[`FeedbackTranslations`](globals.md#feedbacktranslations)\> + + + +Add your own custom translations for the feedback form. +Undefined translation keys fall back to english defaults. + +
+ +*** + +### FeedbackPrompt + +```ts +type FeedbackPrompt = { + featureId: string; + promptId: string; + question: string; + showAfter: Date; + showBefore: Date; +}; +``` + +#### Type declaration + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameTypeDescription
+ + `featureId` + + + +`string` + + + +Feature ID from Reflag + +
+ + `promptId` + + + +`string` + + + +Id of the prompt + +
+ + `question` + + + +`string` + + + +Specific question user was asked + +
+ + `showAfter` + + + +[`Date`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date) + + + +Feedback prompt should appear only after this time + +
+ + `showBefore` + + + +[`Date`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date) + + + +Feedback prompt will not be shown after this time + +
+ +*** + +### FeedbackPromptHandler() + +```ts +type FeedbackPromptHandler = (prompt: FeedbackPrompt, handlers: FeedbackPromptHandlerCallbacks) => void; +``` + +#### Parameters + + + + + + + + + + + + + + + + + + +
ParameterType
+ +`prompt` + + + +[`FeedbackPrompt`](globals.md#feedbackprompt) + +
+ +`handlers` + + + +[`FeedbackPromptHandlerCallbacks`](globals.md#feedbackprompthandlercallbacks) + +
+ +#### Returns + +`void` + +*** + +### FeedbackPromptHandlerCallbacks + +```ts +type FeedbackPromptHandlerCallbacks = { + openFeedbackForm: (options: FeedbackPromptHandlerOpenFeedbackFormOptions) => void; + reply: FeedbackPromptReplyHandler; +}; +``` + +#### Type declaration + + + + + + + + + + + + + + + + + + +
NameType
+ + `openFeedbackForm` + + + +(`options`: [`FeedbackPromptHandlerOpenFeedbackFormOptions`](globals.md#feedbackprompthandleropenfeedbackformoptions)) => `void` + +
+ + `reply` + + + +[`FeedbackPromptReplyHandler`](globals.md#feedbackpromptreplyhandler) + +
+ +*** + +### FeedbackPromptHandlerOpenFeedbackFormOptions + +```ts +type FeedbackPromptHandlerOpenFeedbackFormOptions = Omit; +``` + +*** + +### FeedbackPromptReply + +```ts +type FeedbackPromptReply = { + comment: string; + companyId: string; + question: string; + score: number; +}; +``` + +#### Type declaration + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameType
+ + `comment`? + + + +`string` + +
+ + `companyId`? + + + +`string` + +
+ + `question` + + + +`string` + +
+ + `score`? + + + +`number` + +
+ +*** + +### FeedbackPromptReplyHandler() + +```ts +type FeedbackPromptReplyHandler = (reply: T) => T extends null ? Promise : Promise<{ + feedbackId: string; +}>; +``` + +#### Type Parameters + + + + + + + + + + + + +
Type Parameter
+ +`T` *extends* [`FeedbackPromptReply`](globals.md#feedbackpromptreply) \| `null` + +
+ +#### Parameters + + + + + + + + + + + + + + +
ParameterType
+ +`reply` + + + +`T` + +
+ +#### Returns + +`T` *extends* `null` ? [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> : [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<\{ + `feedbackId`: `string`; + \}\> + +*** + +### FeedbackTranslations + +```ts +type FeedbackTranslations = { + DefaultQuestionLabel: string; + QuestionPlaceholder: string; + ScoreDissatisfiedLabel: string; + ScoreNeutralLabel: string; + ScoreSatisfiedLabel: string; + ScoreStatusDescription: string; + ScoreStatusLoading: string; + ScoreStatusReceived: string; + ScoreVeryDissatisfiedLabel: string; + ScoreVerySatisfiedLabel: string; + SendButton: string; + SuccessMessage: string; +}; +``` + +You can use this to override text values in the feedback form +with desired language translation + +#### Type declaration + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameType
+ + `DefaultQuestionLabel` + + + +`string` + +
+ + `QuestionPlaceholder` + + + +`string` + +
+ + `ScoreDissatisfiedLabel` + + + +`string` + +
+ + `ScoreNeutralLabel` + + + +`string` + +
+ + `ScoreSatisfiedLabel` + + + +`string` + +
+ + `ScoreStatusDescription` + + + +`string` + +
+ + `ScoreStatusLoading` + + + +`string` + +
+ + `ScoreStatusReceived` + + + +`string` + +
+ + `ScoreVeryDissatisfiedLabel` + + + +`string` + +
+ + `ScoreVerySatisfiedLabel` + + + +`string` + +
+ + `SendButton` + + + +`string` + +
+ + `SuccessMessage` + + + +`string` + +
+ +*** + +### FlagOverrides + +```ts +type FlagOverrides = Record; +``` + +*** + +### FlagRemoteConfig + +```ts +type FlagRemoteConfig = + | { + key: string; + payload: any; + } + | { + key: undefined; + payload: undefined; +}; +``` + +A remotely managed configuration value for a flag. + +#### Type declaration + +\{ + `key`: `string`; + `payload`: `any`; + \} + + + + + + + + + + + + + + + + + + + + + +
NameTypeDescription
+ +`key` + + + +`string` + + + +The key of the matched configuration value. + +
+ +`payload` + + + +`any` + + + +The optional user-supplied payload data. + +
+ +\{ + `key`: `undefined`; + `payload`: `undefined`; + \} + + + + + + + + + + + + + + + + + + +
NameType
+ +`key` + + + +`undefined` + +
+ +`payload` + + + +`undefined` + +
+ +*** + +### InitOptions + +```ts +type InitOptions = ReflagDeprecatedContext & { + apiBaseUrl: string; + appBaseUrl: string; + bootstrappedFlags: RawFlags; + bootstrappedState: BootstrappedState; + credentials: "include" | "same-origin" | "omit"; + enableLiveFlagUpdates: boolean; + enableTracking: boolean; + eventSourceFactory: EventSourceFactory; + expireTimeMs: number; + fallbackFlags: | string[] + | Record; + feedback: FeedbackOptions; + logger: Logger; + offline: boolean; + publishableKey: string; + sdkVersion: string; + sseBaseUrl: string; + staleTimeMs: number; + staleWhileRevalidate: boolean; + storage: StorageAdapter; + timeoutMs: number; + toolbar: ToolbarOptions; + trackingQueue: { + flushDelayMs: number; + maxSize: number; + retryBaseDelayMs: number; + retryMaxDelayMs: number; + }; +}; +``` + +ReflagClient initialization options. + +#### Type declaration + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameTypeDescription
+ +`apiBaseUrl`? + + + +`string` + + + +Base URL of Reflag servers. You can override this to use your mocked server. + +
+ +`appBaseUrl`? + + + +`string` + + + +Base URL of the Reflag web app. Links open ín this app by default. + +
+ +`bootstrappedFlags`? + + + +[`RawFlags`](globals.md#rawflags) + + + +Pre-fetched flags used for the initial flag state. +The client fetches opt-in metadata on demand when opt-in flags are requested. + +**Deprecated** + +Use `bootstrappedState` instead. + +
+ +`bootstrappedState`? + + + +[`BootstrappedState`](globals.md#bootstrappedstate) + + + +Pre-fetched evaluated state used for the initial flag state. +The client fetches opt-in metadata on demand when opt-in flags are requested. + +
+ +`credentials`? + + + +`"include"` \| `"same-origin"` \| `"omit"` + + + +When proxying requests, you may want to include credentials like cookies +so you can authorize the request in the proxy. +This option controls the `credentials` option of the fetch API. + +
+ +`enableLiveFlagUpdates`? + + + +`boolean` + + + +Whether to enable live flag updates. + +When enabled, the SDK opens a Server-Sent Events (SSE) connection and +refreshes flag definitions automatically whenever they change on the +server, without relying on context changes or manual refreshes. + +Defaults to `false` in the browser SDK. + +
+ +`enableTracking`? + + + +`boolean` + + + +Whether to enable tracking. Defaults to `true`. + +
+ +`eventSourceFactory`? + + + +[`EventSourceFactory`](globals.md#eventsourcefactory) + + + +Optional factory used to create SSE connections. + +By default the SDK uses the global `EventSource` implementation available +in browsers. This option is intended for alternative runtimes where you +need to provide an EventSource-compatible transport manually. The React +Native wrapper already injects a transport automatically. + +
+ +`expireTimeMs`? + + + +`number` + + + +If set, flags will be cached between page loads for this duration + +
+ +`fallbackFlags`? + + + + \| `string`[] + \| [`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, [`FallbackFlagOverride`](globals.md#fallbackflagoverride)\> + + + +Flag keys for which `isEnabled` should fallback to true +if SDK fails to fetch flags from Reflag servers. If a record +is supplied instead of array, the values of each key represent the +configuration values and `isEnabled` is assume `true`. + +
+ +`feedback`? + + + +[`FeedbackOptions`](globals.md#feedbackoptions) + + + +AutoFeedback specific configuration + +
+ +`logger`? + + + +[`Logger`](globals.md#logger) + + + +You can provide a logger to see the logs of the network calls. +This is undefined by default. +For debugging purposes you can just set the browser console to this property: +```javascript +options.logger = window.console; +``` + +
+ +`offline`? + + + +`boolean` + + + +Whether to enable offline mode. Defaults to `false`. + +
+ +`publishableKey` + + + +`string` + + + +Publishable key for authentication + +
+ +`sdkVersion`? + + + +`string` + + + +Version of the SDK + +
+ +`sseBaseUrl`? + + + +`string` + + + +**Deprecated** + +SSE now uses the same origin as `apiBaseUrl` by default. +Override only if you need a separate pubsub host temporarily. + +
+ +`staleTimeMs`? + + + +`number` + + + +Stale flags will be returned if staleWhileRevalidate is true if no new flags can be fetched + +
+ +`staleWhileRevalidate`? + + + +`boolean` + + + +If set to true stale flags will be returned while refetching flags + +
+ +`storage`? + + + +[`StorageAdapter`](globals.md#storageadapter) + + + +Optional storage adapter used for caching flags and overrides. +Useful for React Native (AsyncStorage). + +
+ +`timeoutMs`? + + + +`number` + + + +Timeout in milliseconds when fetching flags + +
+ +`toolbar`? + + + +[`ToolbarOptions`](globals.md#toolbaroptions) + + + +Toolbar configuration + +
+ +`trackingQueue`? + + + +\{ + `flushDelayMs`: `number`; + `maxSize`: `number`; + `retryBaseDelayMs`: `number`; + `retryMaxDelayMs`: `number`; + \} + + + +Queue settings for tracking updates sent to `/bulk`. +Applies to user/company updates, check events, and prompt events. +Events are buffered in memory and flushed in the background. + +
+ +`trackingQueue.flushDelayMs`? + + + +`number` + + + +Delay in milliseconds before flushing queued events. +Lower values send sooner; slightly higher values batch better. +Defaults to 200ms. + +
+ +`trackingQueue.maxSize`? + + + +`number` + + + +Maximum number of queued events retained locally. +Oldest events are dropped when the cap is exceeded. +Defaults to 100. + +
+ +`trackingQueue.retryBaseDelayMs`? + + + +`number` + + + +Deprecated: retries are no longer performed for bulk delivery. + +
+ +`trackingQueue.retryMaxDelayMs`? + + + +`number` + + + +Deprecated: retries are no longer performed for bulk delivery. + +
+ +*** + +### Offset + +```ts +type Offset = { + x: string | number; + y: string | number; +}; +``` + +#### Type declaration + + + + + + + + + + + + + + + + + + + + + +
NameTypeDescription
+ + `x`? + + + +`string` \| `number` + + + +Offset from the nearest horizontal screen edge after placement is resolved + +
+ + `y`? + + + +`string` \| `number` + + + +Offset from the nearest vertical screen edge after placement is resolved + +
+ +*** + +### OptInFlag + +```ts +type OptInFlag = RawFlagOptIn & { + isEnabled: boolean; + key: string; +}; +``` + +#### Type declaration + + + + + + + + + + + + + + + + + + + + + +
NameTypeDescription
+ +`isEnabled` + + + +`boolean` + + + +Result of flag evaluation. + +
+ +`key` + + + +`string` + + + +Flag key. + +
+ +*** + +### PopoverPlacement + +```ts +type PopoverPlacement = Placement; +``` + +*** + +### Position + +```ts +type Position = + | { + type: "MODAL"; + } + | { + offset: Offset; + placement: DialogPlacement; + type: "DIALOG"; + } + | { + anchor: any | null; + placement: PopoverPlacement; + type: "POPOVER"; +}; +``` + +*** + +### RawFlag + +```ts +type RawFlag = { + config: { + evaluationErrors: RawFlag["evaluationErrors"]; + key: string; + missingContextFields: string[]; + payload: any; + ruleEvaluationResults: boolean[]; + version: number; + }; + evaluationErrors: { + code: string; + field: string; + message: string; + operator: string; + }[]; + isEnabled: boolean; + isEnabledOverride: boolean | null; + key: string; + missingContextFields: string[]; + optIn: RawFlagOptIn | null; + optInEnabled: boolean; + ruleEvaluationResults: boolean[]; + targetingVersion: number; +}; +``` + +A flag fetched from the server. + +#### Type declaration + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameTypeDescription
+ + `config`? + + + +\{ + `evaluationErrors`: [`RawFlag`](globals.md#rawflag)\[`"evaluationErrors"`\]; + `key`: `string`; + `missingContextFields`: `string`[]; + `payload`: `any`; + `ruleEvaluationResults`: `boolean`[]; + `version`: `number`; + \} + + + +Optional user-defined dynamic configuration. + +
+ +`config.evaluationErrors`? + + + +[`RawFlag`](globals.md#rawflag)\[`"evaluationErrors"`\] + + + +Non-fatal diagnostics produced while evaluating targeting rules. + +
+ +`config.key` + + + +`string` + + + +The key of the matched configuration value. + +
+ +`config.missingContextFields`? + + + +`string`[] + + + +The missing context fields. + +**Deprecated** + +Use `evaluationErrors` and check for `MISSING_CONTEXT_FIELD`. + +
+ +`config.payload`? + + + +`any` + + + +The optional user-supplied payload data. + +
+ +`config.ruleEvaluationResults`? + + + +`boolean`[] + + + +The rule evaluation results. + +
+ +`config.version`? + + + +`number` + + + +The version of the matched configuration value. + +
+ + `evaluationErrors`? + + + +\{ + `code`: `string`; + `field`: `string`; + `message`: `string`; + `operator`: `string`; + \}[] + + + +Non-fatal diagnostics produced while evaluating targeting rules. + +
+ + `isEnabled` + + + +`boolean` + + + +Result of flag evaluation. +Note: does not take local overrides into account. + +
+ + `isEnabledOverride`? + + + +`boolean` \| `null` + + + +If not null or undefined, the result is being overridden locally + +
+ + `key` + + + +`string` + + + +Flag key. + +
+ + `missingContextFields`? + + + +`string`[] + + + +Missing context fields. + +**Deprecated** + +Use `evaluationErrors` and check for `MISSING_CONTEXT_FIELD`. + +
+ + `optIn`? + + + +[`RawFlagOptIn`](globals.md#rawflagoptin) \| `null` + + + +Opt-in metadata for this flag and the current context. + +
+ + `optInEnabled`? + + + +`boolean` + + + +Whether end-user opt-in is enabled for this flag. + +
+ + `ruleEvaluationResults`? + + + +`boolean`[] + + + +Rule evaluation results. + +
+ + `targetingVersion`? + + + +`number` + + + +Version of targeting rules. + +
+ +*** + +### RawFlagOptIn + +```ts +type RawFlagOptIn = { + companyOptedIn: boolean; + description: string | null; + isOptedIn: boolean; + name: string; + userOptedIn: boolean; +}; +``` + +#### Type declaration + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameTypeDescription
+ + `companyOptedIn` + + + +`boolean` + + + +Whether the current company has opted into the flag. + +
+ + `description` + + + +`string` \| `null` + + + +SDK-facing opt-in description. + +
+ + `isOptedIn` + + + +`boolean` + + + +Whether either the current user or company has opted into the flag. + +
+ + `name` + + + +`string` + + + +Display name of the opt-in flag. + +
+ + `userOptedIn` + + + +`boolean` + + + +Whether the current user has opted into the flag. + +
+ +*** + +### RawFlags + +```ts +type RawFlags = Record; +``` + +*** + +### RequestFeedbackData + +```ts +type RequestFeedbackData = Omit & { + companyId: string; + flagKey: string; + onAfterSubmit: (data: FeedbackSubmission) => void; +}; +``` + +#### Type declaration + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameTypeDescription
+ +`companyId`? + + + +`string` + + + +Company ID from your own application. + +
+ +`flagKey` + + + +`string` + + + +Flag key. + +
+ +`onAfterSubmit`? + + + +(`data`: [`FeedbackSubmission`](globals.md#feedbacksubmission)) => `void` + + + +Allows you to handle a copy of the already submitted +feedback. + +This can be used for side effects, such as storing a +copy of the feedback in your own application or CRM. + +
+ +*** + +### RequestFeedbackOptions + +```ts +type RequestFeedbackOptions = RequestFeedbackData & { + userId: string; +}; +``` + +#### Type declaration + + + + + + + + + + + + + + + + +
NameTypeDescription
+ +`userId` + + + +`string` + + + +User ID from your own application. + +
+ +*** + +### SetOptInOptions + +```ts +type SetOptInOptions = { + optedIn: boolean; + scope?: "user" | "company"; +}; +``` + +Options for changing the current user or company's opt-in membership. + +#### Type declaration + + + + + + + + + + + + + + + + + + + + + +
NameTypeDescription
+ + `optedIn` + + + +`boolean` + + + +Whether the scoped subject has opted in. + +
+ + `scope`? + + + +`"user"` \| `"company"` + + + +Whether to update the current user or current company. Defaults to `user`. + +
+ +*** + +### State + +```ts +type State = "idle" | "initializing" | "initialized" | "stopped"; +``` + +State of the client. + +*** + +### StorageAdapter + +```ts +type StorageAdapter = { + getItem: Promise; + removeItem: Promise; + setItem: Promise; +}; +``` + +#### Type declaration + + + + + + + + + + + + + + + + + + + + + + +
NameType
+ + `getItem()` + + + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`null` \| `string`\> + +
+ + `removeItem()`? + + + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> + +
+ + `setItem()` + + + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> + +
+ +*** + +### ToolbarOptions + +```ts +type ToolbarOptions = + | boolean + | { + position: ToolbarPosition; + show: boolean; +}; +``` + +Toolbar options. + +*** + +### TrackEvent + +```ts +type TrackEvent = { + attributes: | Record + | null; + company: CompanyContext; + eventName: string; + user: UserContext; +}; +``` + +#### Type declaration + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameType
+ + `attributes`? + + + + \| [`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, `any`\> + \| `null` + +
+ + `company`? + + + +[`CompanyContext`](globals.md#companycontext) + +
+ + `eventName` + + + +`string` + +
+ + `user` + + + +[`UserContext`](globals.md#usercontext) + +
+ +*** + +### UnassignedFeedback + +```ts +type UnassignedFeedback = { + comment: string; + feedbackId: string; + flagKey: string; + promptedQuestion: string; + promptId: string; + question: string; + score: number; + source: "prompt" | "sdk" | "widget"; +}; +``` + +#### Type declaration + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameTypeDescription
+ + `comment`? + + + +`string` + + + +User supplied comment about your flag. + +
+ + `feedbackId`? + + + +`string` + + + +Reflag feedback ID + +
+ + `flagKey` + + + +`string` + + + +Flag key. + +
+ + `promptedQuestion`? + + + +`string` + + + +The original question. +This only needs to be populated if the feedback was submitted through the automated feedback surveys channel. + +
+ + `promptId`? + + + +`string` + + + +Reflag feedback prompt ID. + +This only exists if the feedback was submitted +as part of an automated prompt from Reflag. + +Used for internal state management of automated +feedback. + +
+ + `question`? + + + +`string` + + + +The question that was presented to the user. + +
+ + `score`? + + + +`number` + + + +Customer satisfaction score. + +
+ + `source`? + + + +`"prompt"` \| `"sdk"` \| `"widget"` + + + +Source of the feedback, depending on how the user was asked +- `prompt` - Feedback submitted by way of an automated feedback survey (prompted) +- `widget` - Feedback submitted via `requestFeedback` +- `sdk` - Feedback submitted via `feedback` + +
+ +## Variables + +### DEFAULT\_TRANSLATIONS + +```ts +const DEFAULT_TRANSLATIONS: FeedbackTranslations; +``` + +```tsx +import { FeedbackTranslations } from "../types"; +/** + * {@includeCode ./defaultTranslations.tsx} + */ +export const DEFAULT_TRANSLATIONS: FeedbackTranslations = { + DefaultQuestionLabel: "How satisfied are you with this feature?", + QuestionPlaceholder: "Write a comment", + ScoreStatusDescription: "Pick a score and leave a comment", + ScoreStatusLoading: "Saving score, please wait...", + ScoreStatusReceived: "Score has been received!", + ScoreVeryDissatisfiedLabel: "Very dissatisfied (1/5)", + ScoreDissatisfiedLabel: "Dissatisfied (2/5)", + ScoreNeutralLabel: "Neutral (3/5)", + ScoreSatisfiedLabel: "Satisfied (4/5)", + ScoreVerySatisfiedLabel: "Very satisfied (5/5)", + SuccessMessage: "Feedback received, thank you!", + SendButton: "Send feedback", +}; +``` + +*** + +### feedbackContainerId + +```ts +const feedbackContainerId: "reflag-feedback-dialog-container" = "reflag-feedback-dialog-container"; +``` + +ID of HTML DIV element which contains the feedback dialog + +*** + +### propagatedEvents + +```ts +const propagatedEvents: string[]; +``` + +These events will be propagated to the feedback dialog + +#### See + +[https://developer.mozilla.org/en-US/docs/Web/API/Element#events](https://developer.mozilla.org/en-US/docs/Web/API/Element#events) diff --git a/legacy/v1/node-sdk/README.md b/legacy/v1/node-sdk/README.md new file mode 100644 index 0000000..df62519 --- /dev/null +++ b/legacy/v1/node-sdk/README.md @@ -0,0 +1,1153 @@ +--- +layout: + visible: true +title: + visible: true +description: + visible: false +tableOfContents: + visible: true +outline: + visible: true +pagination: + visible: true +--- + +{% hint style="info" %} +**Protocol v1 — legacy.** [Current v2 documentation](../../../supported-languages/node-sdk/README.md) · [Migration guide](../../../supported-languages/migrating-from-v1.md) +{% endhint %} + +# Reflag Node.js SDK + +Node.js, JavaScript/TypeScript client for [Reflag.com](https://reflag.com). + +Reflag supports flag toggling, tracking flag usage, collecting feedback on features, and [remotely configuring flags](#remote-config). + +## Installation + +Install using your favorite package manager: + +{% tabs %} +{% tab title="npm" %} + +```sh +npm i @reflag/node-sdk@1 +``` + +{% endtab %} + +{% tab title="yarn" %} + +```sh +yarn add @reflag/node-sdk@1 +``` + +{% endtab %} + +{% tab title="bun" %} + +```sh +bun add @reflag/node-sdk@1 +``` + +{% endtab %} + +{% tab title="pnpm" %} + +```sh +pnpm add @reflag/node-sdk@1 +``` + +{% endtab %} + +{% tab title="deno" %} + +```sh +deno add npm:@reflag/node-sdk@1 +``` + +{% endtab %} +{% endtabs %} + +Other supported languages/frameworks are in the [Supported languages](https://docs.reflag.com/quickstart/supported-languages) documentation pages. + +You can also [use the HTTP API directly](https://docs.reflag.com/api/http-api) + +## Basic usage + +To get started you need to obtain your secret key from the [environment settings](https://app.reflag.com/env-current/settings/app-environments) +in Reflag. + +Reflag will load settings through the various environment variables automatically (see [Configuring](#configuring) below). + +1. Find the Reflag secret key for your development environment under [environment settings](https://app.reflag.com/env-current/settings/app-environments) in Reflag. +2. Set `REFLAG_SECRET_KEY` in your `.env` file +3. Create a `reflag.ts` file containing the following: + +```typescript +import { ReflagClient } from "@reflag/node-sdk"; + +// Create a new instance of the client with the secret key. Additional options +// are available, such as supplying a logger and other custom properties. +// +// We recommend that only one global instance of `client` should be created +// to avoid multiple round-trips to our servers. +export const reflagClient = new ReflagClient(); + +// Initialize the client and begin fetching flag targeting definitions. +// You must call this method prior to any calls to `getFlags()`, +// otherwise an empty object will be returned. +reflagClient.initialize().then(() => { + console.log("Reflag initialized!"); +}); +``` + +Once the client is initialized, you can obtain flags along with the `isEnabled` +status to indicate whether the flag is targeted for this user/company: + +{% hint style="warning" %} +If `user.id` is not given, the whole `user` object is ignore. Similarly, without `company.id` the `company` object is ignored. +{% endhint %} + +```typescript +// configure the client +const boundClient = reflagClient.bindClient({ + user: { + id: "john_doe", + name: "John Doe", + email: "john@acme.com", + avatar: "https://example.com/users/jdoe", + }, + company: { + id: "acme_inc", + name: "Acme, Inc.", + avatar: "https://example.com/companies/acme", + }, +}); + +// get the huddle flag using company, user and custom context to +// evaluate the targeting. +const { isEnabled, track, config } = boundClient.getFlag("huddle"); + +if (isEnabled) { + // this is your flag gated code ... + // send an event when the flag is used: + track(); + + if (config?.key === "zoom") { + // this code will run if a given remote configuration + // is set up. + } + + // CAUTION: if you plan to use the event for automated feedback surveys + // call `flush` immediately after `track`. It can optionally be awaited + // to guarantee the sent happened. + boundClient.flush(); +} +``` + +You can also use the `getFlags()` method which returns a map of all flags: + +```typescript +// get the current flags (uses company, user and custom context to +// evaluate the flags). +const flags = boundClient.getFlags(); +const bothEnabled = flags.huddle?.isEnabled && flags.voiceHuddle?.isEnabled; +``` + +## High performance flag targeting + +The SDK contacts the Reflag servers when you call `initialize()` +and downloads the flags with their targeting rules. +These rules are then matched against the user/company information you provide +to `getFlags()` (or through `bindClient(..).getFlags()`). That means the +`getFlags()` call does not need to contact the Reflag servers once +`initialize()` has completed. By default, `ReflagClient` uses +`flagsSyncMode: "push"`, which keeps targeting rules up to date via live SSE +updates. You can switch `flagsSyncMode` to `polling` for periodic background +refreshes or `in-request` for request-driven refreshes instead. + +### Batch Operations + +The SDK automatically batches operations like user/company updates and flag tracking events to minimize API calls. +The batch buffer is configurable through the client options: + +```typescript +const client = new ReflagClient({ + batchOptions: { + maxSize: 100, // Maximum number of events to batch + intervalMs: 10000, // Flush interval in milliseconds (default: 10000) + }, +}); +``` + +You can manually flush the batch buffer at any time: + +```typescript +await client.flush(); +``` + +{% hint style="success" %} +It's recommended to call `flush()` before your application shuts down to ensure all events are sent. +{% endhint %} + +### Rate Limiting + +The SDK includes automatic rate limiting for flag events to prevent overwhelming the API. +Rate limiting is applied per unique combination of flag key and evaluation context. +This behavior is built in and does not currently require configuration. + +### Flag definitions + +Flag definitions include the rules needed to determine which flags should be enabled and which config values should be applied to any given user/company. +Flag definitions are automatically fetched when calling `initialize()`. +They are then cached and refreshed in the background. Ordinary refreshes use +ETags to avoid downloading unchanged definitions. A `304 Not Modified` response +keeps the cached definitions and resets their freshness without recompiling +rules or writing a new fallback snapshot. Initial fetches and refreshes with a +`waitForVersion` target remain unconditional. When a fallback provider is +configured, the SDK retains the ETag only after the snapshot is saved +successfully. A failed or pending save keeps ordinary refreshes unconditional +so persistence can recover, without delaying flag availability. + +Custom HTTP clients can enable this optimization by returning the exact ETag +value in `HttpClientResponse.etag` and returning 304 responses with +`body: undefined`. Clients that omit the ETag continue using full fetches. + +It's also possible to get the currently in use flag definitions: + +```typescript +import fs from "fs"; + +const client = new ReflagClient(); + +const flagDefs = await client.getFlagDefinitions(); +// [{ +// key: "huddle", +// description: "Live voice conversations with colleagues." +// flag: { ... } +// config: { ... } +// }] +``` + +### Fallback provider + +`flagsFallbackProvider` is a reliability feature that lets the SDK persist the latest successfully fetched raw flag definitions to fallback storage such as a local file, Redis, S3, GCS, or a custom backend. + +{% hint style="info" %} + +`fallbackFlags` is deprecated. Prefer `flagsFallbackProvider` for startup fallback and outage recovery. +`flagsFallbackProvider` is not used in offline mode. +{% endhint %} + +#### How it works + +Reflag servers remain the primary source of truth. On `initialize()`, the SDK always tries to fetch a live copy of the flag definitions first, and it continues refreshing those definitions from the Reflag servers over time. + +If that initial live fetch fails, the SDK can call `flagsFallbackProvider.load()` and start with the last saved snapshot instead. This is mainly useful for cold starts in the exceedingly rare case that Reflag has an outage. + +If Reflag becomes unavailable after the SDK has already initialized successfully, the SDK keeps using the last successfully fetched definitions it already has in memory. In other words, the fallback provider is mainly what helps future processes start, not what keeps an already running process alive. + +After successfully fetching updated flag definitions, the SDK calls `flagsFallbackProvider.save()` to keep the stored snapshot up to date. + +Typical reliability flow: + +1. The SDK starts and tries to fetch live flag definitions from Reflag. +2. If that succeeds, those definitions are used immediately and the SDK continues operating normally. +3. After successfully fetching updated flag definitions, the SDK saves the latest snapshot through the fallback provider so a recent copy is available if needed later. +4. If a future process starts while Reflag is unavailable, it can load the last saved snapshot from the fallback provider and still initialize. +5. Once Reflag becomes available again, the SDK resumes using live data and refreshes the fallback snapshot. + +Most deployments run multiple SDK processes, so more than one process may save identical flag definitions to the fallback storage at roughly the same time. This is expected and generally harmless for backends like a local file, Redis, S3, or GCS because the operation is cheap. In practice, this only becomes worth thinking about once you have many thousands of SDK processes writing to the same fallback storage. + +{% hint style="success" %} +If you are building a web or client-side application and want the most resilient setup, combine `flagsFallbackProvider` on the server with bootstrapped flags on the client. + +`flagsFallbackProvider` helps new server processes start if they cannot reach Reflag during initialization. Bootstrapping helps clients render from server-provided flags instead of depending on an initial client-side fetch from the Reflag servers. + +This applies to React (`getFlagsForBootstrap()` + `ReflagBootstrappedProvider`), React Native, the Browser SDK (`bootstrappedState`), and the Vue SDK (bootstrapped flags via the provider). +{% endhint %} + +#### Built-in providers + +You can access the built-in providers through the `fallbackProviders` namespace: + +- `fallbackProviders.static(...)` +- `fallbackProviders.file(...)` +- `fallbackProviders.redis(...)` +- `fallbackProviders.s3(...)` +- `fallbackProviders.gcs(...)` + +### Static provider + +If you just want a fixed fallback copy of simple enabled/disabled flags, you can provide a static map: + +```typescript +import { ReflagClient, fallbackProviders } from "@reflag/node-sdk"; + +const client = new ReflagClient({ + secretKey: process.env.REFLAG_SECRET_KEY, + flagsFallbackProvider: fallbackProviders.static({ + flags: { + huddle: true, + "smart-summaries": false, + }, + }), +}); + +await client.initialize(); +``` + +### File provider + +```typescript +import { ReflagClient, fallbackProviders } from "@reflag/node-sdk"; + +const client = new ReflagClient({ + secretKey: process.env.REFLAG_SECRET_KEY, + flagsFallbackProvider: fallbackProviders.file({ + directory: ".reflag", + }), +}); + +await client.initialize(); +``` + +The file provider stores one snapshot file per environment in the configured +`directory`, using the filename +`flags-fallback-.json`. + +### Redis provider + +The built-in Redis provider creates a Redis client automatically when omitted and uses `REDIS_URL` from the environment. It stores snapshots under the configured `keyPrefix` and appends the first 16 characters of the secret key hash to that prefix. + +Without a `keyPrefix` set, it will default to the key `reflag:flags-fallback:`. When you provide a custom `keyPrefix`, any trailing `:` is trimmed before the hash suffix is appended. + +```typescript +import { ReflagClient, fallbackProviders } from "@reflag/node-sdk"; + +const client = new ReflagClient({ + secretKey: process.env.REFLAG_SECRET_KEY, + flagsFallbackProvider: fallbackProviders.redis(), +}); + +await client.initialize(); +``` + +### S3 provider + +The built-in S3 provider works out of the box using the AWS SDK's default credential chain and region resolution. It stores the snapshot object under the configured `keyPrefix` and uses the filename `flags-fallback-.json`. + +Without a `keyPrefix` set, it will default to the object key `reflag/flags-fallback/flags-fallback-.json`. When you provide a custom `keyPrefix`, any trailing `/` is trimmed before the filename is appended. + +```typescript +import { ReflagClient, fallbackProviders } from "@reflag/node-sdk"; + +const client = new ReflagClient({ + secretKey: process.env.REFLAG_SECRET_KEY, + flagsFallbackProvider: fallbackProviders.s3({ + bucket: "reflag-fallback-bucket", + }), +}); + +await client.initialize(); +``` + +### GCS provider + +The built-in GCS provider works out of the box using Google Cloud's default application credentials. It stores the snapshot object under the configured `keyPrefix` and uses the filename `flags-fallback-.json`. + +Without a `keyPrefix` set, it will default to the object key `reflag/flags-fallback/flags-fallback-.json`. When you provide a custom `keyPrefix`, any trailing `/` is trimmed before the filename is appended. + +```typescript +import { ReflagClient, fallbackProviders } from "@reflag/node-sdk"; + +const client = new ReflagClient({ + secretKey: process.env.REFLAG_SECRET_KEY, + flagsFallbackProvider: fallbackProviders.gcs({ + bucket: "reflag-fallback-bucket", + }), +}); + +await client.initialize(); +``` + +#### Testing fallback startup locally + +To test fallback startup in your own app, first run it once with a working Reflag connection so a snapshot is saved. Then restart it with the same secret key and fallback provider configuration, but set `apiBaseUrl` (or set the `REFLAG_API_BASE_URL` environment variable) to `http://127.0.0.1:65535`. That forces the live fetch to fail and lets you verify that the SDK initializes from the saved snapshot instead. + +#### Writing a custom provider + +If you just store definitions in your database or similar, a custom provider can be very small: + +```typescript +import type { + FlagsFallbackProvider, + FlagsFallbackSnapshot, +} from "@reflag/node-sdk"; + +export const customFallbackProvider: FlagsFallbackProvider = { + async load(context) { + // load snapshot from database + // optionally, look up the snapshot using the context.secretKeyHash as a key + return snapshot; + }, + + async save(context, snapshot) { + const serialized = JSON.stringify(snapshot); + // write serialized snapshot to database, optionally using context.secretKeyHash as a key + }, +}; +``` + +## Bootstrapping client-side applications + +The `getFlagsForBootstrap()` method is useful whenever you need to pass flag data to another runtime or serialize it without wrapper functions. Server-side rendering (SSR) is a common example, but it is also useful for other bootstrapping and hydration flows. + +```typescript +const client = new ReflagClient(); +await client.initialize(); + +// Get bootstrapped state with full context +const bootstrappedState = client.getFlagsForBootstrap({ + user: { + id: "user123", + name: "John Doe", + email: "john@acme.com", + }, + company: { + id: "company456", + name: "Acme Inc", + plan: "enterprise", + }, + other: { + source: "web", + platform: "desktop", + }, +}); + +// Pass this data to your client-side application +console.log(bootstrappedState); +// { +// context: { ... }, +// flags: { +// "huddle": { +// "key": "huddle", +// "isEnabled": true, +// "config": { +// "key": "enhanced", +// "payload": { "maxParticipants": 50, "videoQuality": "hd" }, +// } +// } +// }, +// flagStateVersion: 42 +// } +``` + +You can also use a bound client for simpler API: + +```typescript +const boundClient = client.bindClient({ + user: { id: "user123", name: "John Doe", email: "john@acme.com" }, + company: { id: "company456", name: "Acme Inc", plan: "enterprise" }, +}); + +const bootstrappedState = boundClient.getFlagsForBootstrap(); +``` + +### Key differences from `getFlags()` + +- **Raw data**: Returns plain objects without `track()` functions, making them JSON serializable +- **Context included**: Returns both the evaluated flags and the context used for evaluation +- **Version included**: Returns `flagStateVersion` when known so bootstrapped clients can avoid redundant live-update refreshes +- **Bootstrapping focus**: Designed specifically for passing data to client-side applications + +## Edge-runtimes like Cloudflare Workers + +To use the Reflag NodeSDK with Cloudflare workers, set the `node_compat` flag [in your wrangler file](https://developers.cloudflare.com/workers/runtime-apis/nodejs/#get-started). + +Instead of using `ReflagClient`, use `EdgeClient` and make sure you call `ctx.waitUntil(reflag.flush());` before returning from your worker function. + +```typescript +import { EdgeClient } from "@reflag/node-sdk"; + +// set the REFLAG_SECRET_KEY environment variable or pass the secret key in the constructor +const reflag = new EdgeClient(); + +export default { + async fetch(request, _env, ctx): Promise { + // initialize the client and wait for it to complete + // if the client was initialized on a previous invocation, this is a no-op. + await reflag.initialize(); + const flags = reflag.getFlags({ + user: { id: "userId" }, + company: { id: "companyId" }, + }); + + // ensure all events are flushed and any requests to refresh the flag cache + // have completed after the response is sent + ctx.waitUntil(reflag.flush()); + + return new Response( + `Flags for user ${userId} and company ${companyId}: ${JSON.stringify(flags, null, 2)}`, + ); + }, +}; +``` + +See [examples/cloudflare-worker](https://github.com/reflagcom/javascript/tree/b4fe5b3d9386b87c6546175c323862d9878e1430/packages/node-sdk/examples/cloudflare-worker/src/index.ts) for a deployable example. + +Reflag maintains a cached set of flag definitions in the memory of your worker which it uses to decide which flags to turn on for which users/companies. + +The SDK caches flag definitions in memory for fast performance. The first request to a new worker instance fetches definitions from Reflag's servers, while subsequent requests use the cache. When the cache expires, it's updated in the background. `ctx.waitUntil(reflag.flush())` ensures completion of the background work, so response times are not affected. This background work may increase wall-clock time for your worker, but it will not measurably increase billable CPU time on platforms like Cloudflare. + +`EdgeClient` uses `flagsSyncMode: "in-request"`. Refresh fetch starts are throttled to at most once per second, and Cloudflare Workers cannot rely on delayed timer callbacks to run follow-up refreshes later. That means `refreshFlags()` calls made during the throttle window only mark a refresh as pending, so the call itself may resolve before the fetch runs. The queued refresh runs on the next request/access or `refreshFlags()` call after the throttle window expires. + +## Error Handling + +The SDK is designed to fail gracefully and never throw exceptions to the caller. Instead, it logs errors and provides +fallback behavior: + +1. **Flag Evaluation Failures**: + + ```typescript + const { isEnabled } = client.getFlag("my-flag"); + // If flag evaluation fails, isEnabled will be false + ``` + +2. **Network Errors**: + + ```typescript + // Network errors during tracking are logged but don't affect your application + const { isEnabled, track } = client.getFlag("my-flag"); + if (isEnabled) { + // network errors are caught internally and logged and never bubbled up to your application + // no need to try/catch around "track" or "getFlag" + await track(); + } + ``` + +3. **Missing Context**: + + ```typescript + // The SDK tracks missing context fields but continues operation + const flags = client.getFlags({ + user: { id: "user123" }, + // Missing company context will be logged but won't cause errors + }); + ``` + +4. **Offline Mode**: + + ```typescript + // In offline mode, the SDK uses explicit local configuration only. + // It does not fetch from Reflag or use flagsFallbackProvider. + const client = new ReflagClient({ + offline: true, + flagOverrides: () => ({ + "my-flag": true, + }), + }); + ``` + +The SDK logs all errors with appropriate severity levels. You can customize logging by providing your own logger: + +```typescript +const client = new ReflagClient({ + logger: { + debug: (msg) => console.debug(msg), + info: (msg) => console.info(msg), + warn: (msg) => console.warn(msg), + error: (msg, error) => { + console.error(msg, error); + // Send to your error tracking service + errorTracker.capture(error); + }, + }, +}); +``` + +## Remote config + +Remote config is a dynamic and flexible approach to configuring flag behavior outside of your app – without needing to re-deploy it. + +Similar to `isEnabled`, each flag has a `config` property. This configuration is managed from within Reflag. +It is managed similar to the way access to flags is managed, but instead of the binary `isEnabled` you can have +multiple configuration values which are given to different user/companies. + +```ts +const flags = reflagClient.getFlags(); +// { +// huddle: { +// isEnabled: true, +// targetingVersion: 42, +// config: { +// key: "gpt-3.5", +// payload: { maxTokens: 10000, model: "gpt-3.5-beta1" } +// } +// } +// } +``` + +`key` is mandatory for a config, but if a flag has no config or no config value was matched against the context, the `key` will be `undefined`. Make sure to check against this case when trying to use the configuration in your application. `payload` is an optional JSON value for arbitrary configuration needs. + +Just as `isEnabled`, accessing `config` on the object returned by `getFlags` does not automatically +generate a `check` event, contrary to the `config` property on the object returned by `getFlag`. + +## Configuring + +The Reflag `Node.js` SDK can be configured through environment variables, +a configuration file on disk or by passing options to the `ReflagClient` +constructor. By default, the SDK searches for `reflag.config.json` in the +current working directory. + +| Option | Type | Description | Env Var | +| ----------------------- | ------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------- | +| `secretKey` | string | The secret key used for authentication with Reflag's servers. | REFLAG_SECRET_KEY | +| `logLevel` | string | The log level for the SDK (e.g., `"DEBUG"`, `"INFO"`, `"WARN"`, `"ERROR"`). Default: `INFO` | REFLAG_LOG_LEVEL | +| `offline` | boolean | Operate in offline mode. Default: `false`, except in tests it will default to `true` based off of the `TEST` env. var. In offline mode the SDK does not fetch from Reflag and does not use `flagsFallbackProvider`. | REFLAG_OFFLINE | +| `apiBaseUrl` | string | The base API URL for the Reflag servers. | REFLAG_API_BASE_URL | +| `flagOverrides` | Record | An object specifying flag overrides for testing or local development. See [examples/express/app.test.ts](https://github.com/reflagcom/javascript/tree/b4fe5b3d9386b87c6546175c323862d9878e1430/packages/node-sdk/examples/express/app.test.ts) for how to use `flagOverrides` in tests. | REFLAG_FLAGS_ENABLED, REFLAG_FLAGS_DISABLED | +| `flagsFallbackProvider` | `FlagsFallbackProvider` | Optional provider used to load and save raw flag definitions for fallback startup when the initial live fetch fails. Available only through the constructor. Ignored in offline mode. | - | +| `flagsSyncMode` | `"polling" \| "in-request" \| "push"` | Flag-definition sync mode. `push` subscribes to live updates, `polling` uses periodic background refresh, and `in-request` refreshes stale flags during request handling. Default: `"push"`. | - | +| `flagsPushUrl` | string | Push endpoint used when `flagsSyncMode: "push"`. The SDK opens it as an authenticated streaming GET. Default: `https://front.reflag.com/sse/server`. | - | +| `configFile` | string | Load this config file from disk. Default: `reflag.config.json` | REFLAG_CONFIG_FILE | + +{% hint style="info" %} + +`REFLAG_FLAGS_ENABLED` and `REFLAG_FLAGS_DISABLED` are comma separated lists of flags which will be enabled or disabled respectively. +{% endhint %} + +`reflag.config.json` example: + +```json +{ + "secretKey": "...", + "logLevel": "warn", + "offline": true, + "apiBaseUrl": "https://proxy.slick-demo.com", + "flagOverrides": { + "huddles": true, + "voiceChat": { "isEnabled": false }, + "aiAssist": { + "isEnabled": true, + "config": { + "key": "gpt-4.0", + "payload": { + "maxTokens": 50000 + } + } + } + } +} +``` + +When using a `reflag.config.json` for local development, make sure you add it to your +`.gitignore` file. You can also set these options directly in the `ReflagClient` +constructor. The precedence for configuration options is as follows, listed in the +order of importance: + +1. Options passed along to the constructor directly, +2. Environment variable, +3. The config file. + +## Type safe flags + +To get type checked flags, install the Reflag CLI: + +```sh +npm i --save-dev @reflag/cli@1 +``` + +then generate the types: + +```sh +npx reflag flags types +``` + +This will generate a `reflag.d.ts` containing all your flags. +Any flag look ups will now be checked against the flags that exist in Reflag. + +Here's an example of a failed type check: + +```typescript +import { ReflagClient } from "@reflag/node-sdk"; + +export const reflagClient = new ReflagClient(); + +reflagClient.initialize().then(() => { + console.log("Reflag initialized!"); + + // TypeScript will catch this error: "invalid-flag" doesn't exist + reflagClient.getFlag("invalid-flag"); + + const { + isEnabled, + config: { payload }, + } = reflagClient.getFlag("create-todos"); +}); +``` + +![Type check failed](../_media/type-check-failed.png "Type check failed") + +This is an example of a failed config payload check: + +```typescript +reflagClient.initialize().then(() => { + // TypeScript will catch this error as well: "minLength" is not part of the payload. + if (isEnabled && todo.length > config.payload.minLength) { + // ... + } +}); +``` + +![Config type check failed](../_media/type-check-payload-failed.png "Remote config type check failed") + +## Testing with flag overrides + +When writing tests that cover code with flags, you can toggle flags on/off programmatically to test different behavior. For tests, you will often want to run the client in offline mode: + +`reflag.ts`: + +```typescript +import { ReflagClient } from "@reflag/node-sdk"; + +export const reflag = new ReflagClient({ + offline: true, +}); +``` + +There are a few ways to programmatically manipulate the overrides which are appropriate when testing: + +### Base overrides + +You can set base overrides for a test run by passing `flagOverrides` in the constructor, replacing them later with `setFlagOverrides()` and clearing them with `clearFlagOverrides()`: + +```typescript +// pass directly in the constructor +const client = new ReflagClient({ + offline: true, + flagOverrides: { myFlag: true }, +}); + +// or replace the base overrides at a later time +client.setFlagOverrides({ myFlag: false }); + +// clear only the base overrides +client.clearFlagOverrides(); +``` + +`app.test.ts`: + +```typescript +import { reflag } from "./reflag.ts"; + +beforeAll(async () => await reflag.initialize()); +afterEach(() => { + reflag.clearFlagOverrides(); +}); + +describe("API Tests", () => { + it("should return 200 for the root endpoint", async () => { + reflag.setFlagOverrides({ + "show-todo": true, + }); + + const response = await request(app).get("/"); + expect(response.status).toBe(200); + expect(response.body).toEqual({ message: "Ready to manage some TODOs!" }); + }); +}); +``` + +### Layering overrides + +`pushFlagOverrides()` serves a different purpose: it adds a temporary layer on top of the base overrides and returns a remove function that removes only that layer. This is useful for nested tests: + +```typescript +export const flag = function (name: string, enabled: boolean): void { + let remove: (() => void) | undefined; + + beforeEach(function () { + remove = reflagClient.pushFlagOverrides({ [name]: enabled }); + }); + + afterEach(function () { + remove?.(); + remove = undefined; + }); +}; + +describe("foo", () => { + describe("with new search ranking enabled", () => { + flag("search-ranking-v2", true); + + describe("with summaries enabled", () => { + flag("smart-summaries", true); + + // ... + }); + }); +}); +``` + +The precedence is: + +1. Base overrides from the constructor or `setFlagOverrides()` +2. Temporary layers added by `pushFlagOverrides()` + +If the same flag is set in both places, the pushed override wins until its remove function is called. + +### Context dependent overrides + +`setFlagOverrides()` and `pushFlagOverrides()` also accept a function if the override depends on the evaluation context: + +```typescript +const remove = client.pushFlagOverrides((context) => ({ + "smart-summaries": context.user?.id === "qa-user", +})); + +// ... + +remove(); +``` + +### Additional ways to provide flag overrides + +You also have these additional ways to provide overrides, which can be helpful when testing out locally: + +1. Through environment variables: + +```bash +REFLAG_FLAGS_ENABLED=flag1,flag2 +REFLAG_FLAGS_DISABLED=flag3,flag4 +``` + +1. Through `reflag.config.json`: + +```json +{ + "flagOverrides": { + "delete-todos": { + "isEnabled": true, + "config": { + "key": "dev-config", + "payload": { + "requireConfirmation": true, + "maxDeletionsPerDay": 5 + } + } + } + } +} +``` + +## Remote Flag Evaluation + +In addition to local flag evaluation, Reflag supports remote evaluation using stored context. This is useful when you want to evaluate flags using user/company attributes that were previously sent to Reflag: + +```typescript +// First, update user and company attributes +await client.updateUser("user123", { + attributes: { + role: "admin", + subscription: "premium", + }, +}); + +await client.updateCompany("company456", { + attributes: { + tier: "enterprise", + employees: 1000, + }, +}); + +// Later, evaluate flags remotely using stored context. +// Note: the argument order is (userId, companyId, additionalContext?) +const userId = "user123"; +const companyId = "company456"; + +const flags = await client.getFlagsRemote(userId, companyId); +// Or evaluate a single flag +const flag = await client.getFlagRemote("create-todos", userId, companyId); + +// You can also provide additional context +const flagsWithContext = await client.getFlagsRemote(userId, companyId, { + other: { + location: "US", + platform: "mobile", + }, +}); +``` + +Remote evaluation is particularly useful when: + +- You want to use the most up-to-date user/company attributes stored in Reflag +- You don't want to pass all context attributes with every evaluation +- You need to ensure consistent flag evaluation across different services + +## Using with Express + +A popular way to integrate the Reflag Node.js SDK is through an express middleware. + +```typescript +import reflag from "./reflag"; +import express from "express"; +import { BoundReflagClient } from "@reflag/node-sdk"; + +// Augment the Express types to include a `boundReflagClient` property on the +// `res.locals` object. +// This will allow us to access the ReflagClient instance in our route handlers +// without having to pass it around manually +declare global { + namespace Express { + interface Locals { + boundReflagClient: BoundReflagClient; + } + } +} + +// Add express middleware +app.use((req, res, next) => { + // Extract the user and company IDs from the request + // You'll want to use a proper authentication and identification + // mechanism in a real-world application + const user = { + id: req.user?.id, + name: req.user?.name, + email: req.user?.email + } + + const company = { + id: req.user?.companyId, + name: req.user?.companyName + } + + // Create a new BoundReflagClient instance by calling the `bindClient` + // method on a `ReflagClient` instance + // This will create a new instance that is bound to the user/company given. + const boundReflagClient = reflag.bindClient({ user, company }); + + // Store the BoundReflagClient instance in the `res.locals` object so we + // can access it in our route handlers + res.locals.boundReflagClient = boundReflagClient; + next(); +}); + +// Now use res.locals.boundReflagClient in your handlers +app.get("/todos", async (_req, res) => { + const { track, isEnabled } = res.locals.boundReflagClient.getFlag("show-todos"); + + if (!isEnabled) { + res.status(403).send({"error": "flag inaccessible"}) + return + } + + ... +} +``` + +See [examples/express/app.ts](https://github.com/reflagcom/javascript/tree/b4fe5b3d9386b87c6546175c323862d9878e1430/packages/node-sdk/example/express/app.ts) for a full example. + +## Remote flag evaluation with stored context + +If you don't want to provide context each time when evaluating flags but +rather you would like to utilize the attributes you sent to Reflag previously +(by calling `updateCompany` and `updateUser`) you can do so by calling `getFlagsRemote` +(or `getFlagRemote` for a specific flag) with just `userId` and `companyId` +in that order. +These methods will call Reflag's servers and flags will be evaluated remotely +using the stored attributes. + +```typescript +// Update user and company attributes +client.updateUser("john_doe", { + attributes: { + name: "John O.", + role: "admin", + }, +}); + +client.updateCompany("acme_inc", { + attributes: { + name: "Acme, Inc", + tier: "premium" + }, +}); +... + +// This will evaluate flags using the stored attributes for the user/company pair +const flags = await client.getFlagsRemote("john_doe", "acme_inc"); +``` + +{% hint style="warning" %} +User and company attribute updates are processed asynchronously, so there might +be a small delay between when attributes are updated and when they are available +for evaluation. +{% endhint %} + +## Opting out of tracking + +There are use cases in which you not want to be sending `user`, `company` and +`track` events to [Reflag.com](https://reflag.com). These are usually cases where you could be impersonating +another user in the system and do not want to interfere with the data being +collected by Reflag. + +To disable tracking, bind the client using `bindClient()` as follows: + +```typescript +// binds the client to a given user and company and set `enableTracking` to `false`. +const boundClient = client.bindClient({ user, company, enableTracking: false }); + +boundClient.track("some event"); // this will not actually send the event to Reflag. + +// the following code will not update the `user` nor `company` in Reflag and will +// not send `track` events either. +const { isEnabled, track } = boundClient.getFlag("user-menu"); +if (isEnabled) { + track(); +} +``` + +Another way way to disable tracking without employing a bound client is to call `getFlag()` +or `getFlags()` by supplying `enableTracking: false` in the arguments passed to +these functions. + +{% hint style="warning" %} +Note, however, that calling `track()`, `updateCompany()` or `updateUser()` in the `ReflagClient` +will still send tracking data. As such, it is always recommended to use `bindClient()` +when using this SDK. +{% endhint %} + +## Flushing + +ReflagClient employs a batching technique to minimize the number of calls that are sent to +Reflag's servers. + +By default, the SDK attempts to flush pending events when the Node.js event loop empties +(the `beforeExit` event). This behavior is controlled by the `flushOnExit` option in the client configuration: + +```typescript +const client = new ReflagClient({ + batchOptions: { + flushOnExit: false, // disable automatic flushing on exit + }, +}); +``` + +Node.js does not emit `beforeExit` for unhandled termination signals (such as `SIGTERM` or +`SIGINT`) or explicit `process.exit()` calls. For these shutdown paths, **await `client.flush()` +in your application's existing graceful shutdown hook**, after stopping incoming work and +waiting for in-flight requests or jobs to finish, and before exiting. This ensures events +produced during shutdown are included. Automatic flushing is best-effort and does not replace +an application-managed shutdown hook. + +## Tracking custom events and setting custom attributes + +Tracking allows events and updating user/company attributes in Reflag. +For example, if a customer changes their plan, you'll want Reflag to know about it, +in order to continue to provide up-do-date targeting information in the Reflag interface. + +The following example shows how to register a new user, associate it with a company +and finally update the plan they are on. + +```typescript +// registers the user with Reflag using the provided unique ID, and +// providing a set of custom attributes (can be anything) +client.updateUser("user_id", { + attributes: { longTimeUser: true, payingCustomer: false }, +}); +client.updateCompany("company_id", { userId: "user_id" }); + +// the user started a voice huddle +client.track("user_id", "huddle", { attributes: { voice: true } }); +``` + +It's also possible to achieve the same through a bound client in the following manner: + +```typescript +const boundClient = client.bindClient({ + user: { id: "user_id", longTimeUser: true, payingCustomer: false }, + company: { id: "company_id" }, +}); + +boundClient.track("huddle", { attributes: { voice: true } }); +``` + +Some attributes are used by Reflag to improve the UI, and are recommended +to provide for easier navigation: + +- `name` -- display name for `user`/`company`, +- `email` -- the email of the user, +- `avatar` -- the URL for `user`/`company` avatar image. + +Attributes cannot be nested (multiple levels) and must be either strings, +integers or booleans. + +## Managing `Last seen` + +By default `updateUser`/`updateCompany` calls automatically update the given +user/company `Last seen` property on Reflag servers. + +You can control if `Last seen` should be updated when the events are sent by setting +`meta.active = false`. This is often useful if you +have a background job that goes through a set of companies just to update their +attributes but not their activity. + +Example: + +```typescript +client.updateUser("john_doe", { + attributes: { name: "John O." }, + meta: { active: true }, +}); + +client.updateCompany("acme_inc", { + attributes: { name: "Acme, Inc" }, + meta: { active: false }, +}); +``` + +`bindClient()` updates attributes on the Reflag servers but does not automatically +update `Last seen`. + +## Zero PII + +The Reflag SDK doesn't collect any metadata and HTTP IP addresses are _not_ being +stored. For tracking individual users, we recommend using something like database +ID as userId, as it's unique and doesn't include any PII (personal identifiable +information). If, however, you're using e.g. email address as userId, but prefer +not to send any PII to Reflag, you can hash the sensitive data before sending +it to Reflag: + +```typescript +import { sha256 } from 'crypto-hash'; + +client.updateUser({ userId: await sha256("john_doe"), ... }); +``` + +## Migrating from Bucket SDK + +If you have been using the Bucket SDKs previously, the following list will help you migrate to Reflag SDK: + +- `Bucket*` classes, and types have been renamed to `Reflag*` (e.g. `BucketClient` is now `ReflagClient`) +- `Feature*` classes, and types have been renamed to `Flag*` (e.g. `Feature` is now `Flag`, `RawFeatures` is now `RawFlags`) +- When using strongly-typed flags, the new `Flags` interface replaced `Features` interface +- All methods that contained `feature` in the name have been renamed to use the `flag` terminology (e.g. `getFeature` is `getFlag`) +- All environment variables that were prefixed with `BUCKET_` are now prefixed with `REFLAG_` +- The `BUCKET_HOST` environment variable and `host` option have been removed from `ReflagClient` constructor, use `REFLAG_API_BASE_URL` instead +- The `BUCKET_FEATURES_ENABLED` and `BUCKET_FEATURES_DISABLED` have been renamed to `REFLAG_FLAGS_ENABLED` and `REFLAG_FLAGS_DISABLED` +- The default configuration file has been renamed from `bucketConfig.json` to `reflag.config.json` +- The `fallbackFeatures` property in client constructor and configuration files has been renamed to `fallbackFlags` +- `featureKey` has been renamed to `flagKey` in all methods that accepts that argument +- The SDKs will not emit `evaluate` and `evaluate-config` events anymore + +## Typescript + +Types are bundled together with the library and exposed automatically when importing +through a package manager. + +## License + +> MIT License +> Copyright (c) 2025 Bucket ApS diff --git a/legacy/v1/node-sdk/globals.md b/legacy/v1/node-sdk/globals.md new file mode 100644 index 0000000..d122108 --- /dev/null +++ b/legacy/v1/node-sdk/globals.md @@ -0,0 +1,6455 @@ +--- +layout: + visible: true +title: + visible: true +description: + visible: false +tableOfContents: + visible: true +outline: + visible: true +pagination: + visible: true +--- + +{% hint style="info" %} +**Protocol v1 — legacy.** [Current v2 documentation](../../../supported-languages/node-sdk/globals.md) · [Migration guide](../../../supported-languages/migrating-from-v1.md) +{% endhint %} + +# @reflag/node-sdk + +## Classes + +### BoundReflagClient + +A client bound with a specific user, company, and other context. + +### Constructors + +### new BoundReflagClient() + +```ts +new BoundReflagClient(client: ReflagClient, options: ContextWithTracking): BoundReflagClient +``` + +**`Internal`** + +(Internal) Creates a new BoundReflagClient. Use `bindClient` to create a new client bound with a specific context. + +###### Parameters + + + + + + + + + + + + + + + + + + + + + +
ParameterTypeDescription
+ +`client` + + + +[`ReflagClient`](globals.md#reflagclient) + + + +The `ReflagClient` to use. + +
+ +`options` + + + +[`ContextWithTracking`](globals.md#contextwithtracking) + + + +The options for the client. + +
+ +###### Returns + +[`BoundReflagClient`](globals.md#boundreflagclient) + +#### Accessors + +### company + +###### Get Signature + +```ts +get company(): + | undefined + | { +[k: string]: any; avatar: string; + id: undefined | string | number; + name: string; +} +``` + +Gets the company associated with the client. + +###### Returns + + \| `undefined` + \| \{ +`[k: string]`: `any`; `avatar`: `string`; + `id`: `undefined` \| `string` \| `number`; + `name`: `string`; + \} + +The company or `undefined` if it is not set. + +### otherContext + +###### Get Signature + +```ts +get otherContext(): + | undefined +| Record +``` + +Gets the "other" context associated with the client. + +###### Returns + + \| `undefined` + \| [`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, `any`\> + +The "other" context or `undefined` if it is not set. + +### user + +###### Get Signature + +```ts +get user(): + | undefined + | { +[k: string]: any; avatar: string; + email: string; + id: undefined | string | number; + name: string; +} +``` + +Gets the user associated with the client. + +###### Returns + + \| `undefined` + \| \{ +`[k: string]`: `any`; `avatar`: `string`; + `email`: `string`; + `id`: `undefined` \| `string` \| `number`; + `name`: `string`; + \} + +The user or `undefined` if it is not set. + +#### Methods + +### bindClient() + +```ts +bindClient(context: ContextWithTracking): BoundReflagClient +``` + +Create a new client bound with the additional context. +Note: This performs a shallow merge for user/company/other individually. + +###### Parameters + + + + + + + + + + + + + + + + +
ParameterTypeDescription
+ +`context` + + + +[`ContextWithTracking`](globals.md#contextwithtracking) + + + +The context to bind the client to. + +
+ +###### Returns + +[`BoundReflagClient`](globals.md#boundreflagclient) + +new client bound with the additional context + +### flush() + +```ts +flush(): Promise +``` + +Flushes the batch buffer. + +###### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> + +### getFlag() + +```ts +getFlag(key: TKey): Flag +``` + +Get a specific flag for the user/company/other context bound to this client. +Using the `isEnabled` property sends a `check` event to Reflag. + +###### Type Parameters + + + + + + + + + + + + +
Type Parameter
+ +`TKey` *extends* `string` + +
+ +###### Parameters + + + + + + + + + + + + + + + + +
ParameterTypeDescription
+ +`key` + + + +`TKey` + + + +The key of the flag to get. + +
+ +###### Returns + +[`Flag`](globals.md#flagtconfig) + +Flags for the given user/company and whether each one is enabled or not + +### getFlagRemote() + +```ts +getFlagRemote(key: string): Promise +``` + +Get remotely evaluated flag for the user/company/other context bound to this client. + +###### Parameters + + + + + + + + + + + + + + + + +
ParameterTypeDescription
+ +`key` + + + +`string` + + + +The key of the flag to get. + +
+ +###### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<[`Flag`](globals.md#flagtconfig)\> + +Flag for the given user/company and key and whether it's enabled or not + +### getFlags() + +```ts +getFlags(): Record +``` + +Get flags for the user/company/other context bound to this client. +Meant for use in serialization of flags for transferring to the client-side/browser. + +###### Returns + +[`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, [`Flag`](globals.md#flagtconfig)\> + +Flags for the given user/company and whether each one is enabled or not + +### getFlagsForBootstrap() + +```ts +getFlagsForBootstrap(): BootstrappedFlags +``` + +Get raw flags for the user/company/other context bound to this client without wrapping them in getters. +This method returns raw flag data suitable for bootstrapping client-side applications. + +###### Returns + +[`BootstrappedFlags`](globals.md#bootstrappedflags) + +Raw flags for the given user/company and whether each one is enabled or not + +### getFlagsRemote() + +```ts +getFlagsRemote(): Promise> +``` + +Get remotely evaluated flag for the user/company/other context bound to this client. + +###### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<[`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, [`Flag`](globals.md#flagtconfig)\>\> + +Flags for the given user/company and whether each one is enabled or not + +### refreshFlags() + +```ts +refreshFlags(waitForVersion?: number): Promise +``` + +Refreshes the flag definitions from the server. + +Fetch starts are throttled to at most once per second. Outside +`in-request` mode, a call to `refreshFlags(waitForVersion)` still waits +until the cache has applied that version or newer. + +In `in-request` mode, a throttled call only records pending refresh work. +The fetch then runs on the next request/access or `refreshFlags()` call +after the throttle window expires. + +###### Parameters + + + + + + + + + + + + + + + + +
ParameterTypeDescription
+ +`waitForVersion`? + + + +`number` + + + +Optional flag state version to wait for before returning updated definitions. + +
+ +###### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> + +### track() + +```ts +track(event: string, options?: TrackOptions & { + companyId: string; +}): Promise +``` + +Track an event in Reflag. + +###### Parameters + + + + + + + + + + + + + + + + + + + + + +
ParameterTypeDescription
+ +`event` + + + +`string` + + + +The event to track. + +
+ +`options`? + + + +[`TrackOptions`](globals.md#trackoptions) & \{ `companyId`: `string`; \} + + + +The options for the event. + +
+ +###### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> + +###### Throws + +An error if the event is invalid or the options are invalid. + +*** + +### EdgeClient + +The EdgeClient is ReflagClient pre-configured to be used in edge runtimes, like +Cloudflare Workers. + +It always uses `flagsSyncMode: "in-request"`. Refresh fetch starts are +throttled to at most once per second. A `refreshFlags()` call made during +that throttle window only records pending refresh work, so the call may +resolve before the fetch runs. That pending refresh is executed on the next +request/access or `refreshFlags()` call after the window expires. + +#### Example + +```ts +// set the REFLAG_SECRET_KEY environment variable or pass the secret key in the constructor +const client = new EdgeClient(); + +// evaluate a flag +const context = { + user: { id: "user-id" }, + company: { id: "company-id" }, +} +const { isEnabled } = client.getFlag(context, "flag-key"); + +``` + +#### Extends + +- [`ReflagClient`](globals.md#reflagclient) + +#### Constructors + +### new EdgeClient() + +```ts +new EdgeClient(options: EdgeClientOptions): EdgeClient +``` + +###### Parameters + + + + + + + + + + + + + + +
ParameterType
+ +`options` + + + +[`EdgeClientOptions`](globals.md#edgeclientoptions) + +
+ +###### Returns + +[`EdgeClient`](globals.md#edgeclient) + +###### Overrides + +[`ReflagClient`](globals.md#reflagclient).[`constructor`](globals.md#constructors) + +#### Properties + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyModifierTypeDescription
+ + `httpClient` + + + +`public` + + + +[`HttpClient`](globals.md#httpclient) + + + +‐ + +
+ + `logger` + + + +`readonly` + + + +[`Logger`](globals.md#logger) + + + +Gets the logger associated with the client. + +
+ +#### Accessors + +### flagOverrides + +###### Set Signature + +```ts +set flagOverrides(overrides: + | Partial> + | FlagOverridesFn): void +``` + +###### Deprecated + +Use `setFlagOverrides()` for replacing the base override set. + +###### Parameters + + + + + + + + + + + + + + +
ParameterType
+ +`overrides` + + + + \| [`Partial`](https://www.typescriptlang.org/docs/handbook/utility-types.html#partialtype)\<[`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, [`FlagOverride`](globals.md#flagoverride)\>\> \| [`FlagOverridesFn`](globals.md#flagoverridesfn) + +
+ +###### Returns + +`void` + +###### Inherited from + +[`ReflagClient`](globals.md#reflagclient).[`flagOverrides`](globals.md#flagoverrides) + +#### Methods + +### bindClient() + +```ts +bindClient(context: ContextWithTracking): BoundReflagClient +``` + +Returns a new BoundReflagClient with the user/company/otherContext +set to be used in subsequent calls. +For example, for evaluating flag targeting or tracking events. + +###### Parameters + + + + + + + + + + + + + + + + +
ParameterTypeDescription
+ +`context` + + + +[`ContextWithTracking`](globals.md#contextwithtracking) + + + +The context to bind the client to. + +
+ +###### Returns + +[`BoundReflagClient`](globals.md#boundreflagclient) + +A new client bound with the arguments given. + +###### Throws + +An error if the user/company is given but their ID is not a string. + +###### Remarks + +The `updateUser` / `updateCompany` methods will automatically be called when +the user/company is set respectively. + +###### Inherited from + +[`ReflagClient`](globals.md#reflagclient).[`bindClient`](globals.md#bindclient) + +### clearFlagOverrides() + +```ts +clearFlagOverrides(): void +``` + +Clears the base flag overrides. + +###### Returns + +`void` + +###### Remarks + +This does not affect temporary layers added with `pushFlagOverrides()`. + +###### Example + +```ts +client.clearFlagOverrides(); +``` + +###### Inherited from + +[`ReflagClient`](globals.md#reflagclient).[`clearFlagOverrides`](globals.md#clearflagoverrides) + +### destroy() + +```ts +destroy(): void +``` + +Destroys the client and cleans up all resources including timers and background processes. + +###### Returns + +`void` + +###### Remarks + +After calling this method, the client should not be used anymore. +This is particularly useful in development environments with hot reloading to prevent +multiple background processes from running simultaneously. + +###### Inherited from + +[`ReflagClient`](globals.md#reflagclient).[`destroy`](globals.md#destroy) + +### flush() + +```ts +flush(): Promise +``` + +Flushes and completes any in-flight fetches in the flag cache. + +###### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> + +###### Remarks + +It is recommended to call this method when the application is shutting down to ensure all events are sent +before the process exits. + +This method is automatically called on natural process exit (`beforeExit`) if +`batchOptions.flushOnExit` is `true` in the options (default). For signal-driven +shutdown or an explicit `process.exit()`, await this method in your application's +shutdown hook before exiting. The SDK does not install signal handlers. + +###### Inherited from + +[`ReflagClient`](globals.md#reflagclient).[`flush`](globals.md#flush) + +### getFlag() + +```ts +getFlag(__namedParameters: ContextWithTracking, key: TKey): Flag +``` + +Gets the evaluated flag for the current context which includes the user, company, and custom context. +Using the `isEnabled` property sends a `check` event to Reflag. + +###### Type Parameters + + + + + + + + + + + + +
Type Parameter
+ +`TKey` *extends* `string` + +
+ +###### Parameters + + + + + + + + + + + + + + + + + + + + + +
ParameterTypeDescription
+ +`__namedParameters` + + + +[`ContextWithTracking`](globals.md#contextwithtracking) + + + +‐ + +
+ +`key` + + + +`TKey` + + + +The key of the flag to get. + +
+ +###### Returns + +[`Flag`](globals.md#flagtconfig) + +The evaluated flag. + +###### Remarks + +Call `initialize` before calling this method to ensure the flag definitions are cached, no flags will be returned otherwise. + +###### Inherited from + +[`ReflagClient`](globals.md#reflagclient).[`getFlag`](globals.md#getflag) + +### getFlagDefinitions() + +```ts +getFlagDefinitions(): FlagDefinition[] +``` + +Gets the flag definitions, including all config values. +To evaluate which flags are enabled for a given user/company, use `getFlags`. + +###### Returns + +[`FlagDefinition`](globals.md#flagdefinition)[] + +The flags definitions. + +###### Inherited from + +[`ReflagClient`](globals.md#reflagclient).[`getFlagDefinitions`](globals.md#getflagdefinitions) + +### getFlagRemote() + +```ts +getFlagRemote( + key: TKey, + userId?: IdType, + companyId?: IdType, +additionalContext?: Context): Promise +``` + +Gets evaluated flag with the usage of remote context. +This method triggers a network request every time it's called. + +###### Type Parameters + + + + + + + + + + + + +
Type Parameter
+ +`TKey` *extends* `string` + +
+ +###### Parameters + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ParameterTypeDescription
+ +`key` + + + +`TKey` + + + +The key of the flag to get. + +
+ +`userId`? + + + +[`IdType`](globals.md#idtype) + + + +The userId of the user to get the flag for. + +
+ +`companyId`? + + + +[`IdType`](globals.md#idtype) + + + +The companyId of the company to get the flag for. + +
+ +`additionalContext`? + + + +[`Context`](globals.md#context) + + + +The additional context to get the flag for. + +
+ +###### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<[`Flag`](globals.md#flagtconfig)\> + +evaluated flag + +###### Inherited from + +[`ReflagClient`](globals.md#reflagclient).[`getFlagRemote`](globals.md#getflagremote) + +### getFlags() + +```ts +getFlags(options: ContextWithTracking): Record +``` + +Gets the evaluated flags for the current context which includes the user, company, and custom context. + +###### Parameters + + + + + + + + + + + + + + + + +
ParameterTypeDescription
+ +`options` + + + +[`ContextWithTracking`](globals.md#contextwithtracking) + + + +The options for the context. + +
+ +###### Returns + +[`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, [`Flag`](globals.md#flagtconfig)\> + +The evaluated flags. + +###### Remarks + +Call `initialize` before calling this method to ensure the flag definitions are cached, no flags will be returned otherwise. + +###### Inherited from + +[`ReflagClient`](globals.md#reflagclient).[`getFlags`](globals.md#getflags) + +### getFlagsForBootstrap() + +```ts +getFlagsForBootstrap(options: ContextWithTracking): BootstrappedFlags +``` + +Gets the evaluated flags for the current context without wrapping them in getters. +This method returns raw flag data suitable for bootstrapping client-side applications. + +###### Parameters + + + + + + + + + + + + + + + + +
ParameterTypeDescription
+ +`options` + + + +[`ContextWithTracking`](globals.md#contextwithtracking) + + + +The options for the context. + +
+ +###### Returns + +[`BootstrappedFlags`](globals.md#bootstrappedflags) + +The evaluated raw flags and the context. + +###### Remarks + +Call `initialize` before calling this method to ensure the flag definitions are cached, no flags will be returned otherwise. +This method returns RawFlag objects without wrapping them in getters, making them suitable for serialization. + +###### Inherited from + +[`ReflagClient`](globals.md#reflagclient).[`getFlagsForBootstrap`](globals.md#getflagsforbootstrap) + +### getFlagsRemote() + +```ts +getFlagsRemote( + userId?: IdType, + companyId?: IdType, +additionalContext?: Context): Promise> +``` + +Gets evaluated flags with the usage of remote context. +This method triggers a network request every time it's called. + +###### Parameters + + + + + + + + + + + + + + + + + + + + + + + + + + +
ParameterTypeDescription
+ +`userId`? + + + +[`IdType`](globals.md#idtype) + + + +The userId of the user to get the flags for. + +
+ +`companyId`? + + + +[`IdType`](globals.md#idtype) + + + +The companyId of the company to get the flags for. + +
+ +`additionalContext`? + + + +[`Context`](globals.md#context) + + + +The additional context to get the flags for. + +
+ +###### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<[`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, [`Flag`](globals.md#flagtconfig)\>\> + +evaluated flags + +###### Inherited from + +[`ReflagClient`](globals.md#reflagclient).[`getFlagsRemote`](globals.md#getflagsremote) + +### initialize() + +```ts +initialize(): Promise +``` + +Initializes the client by caching the flags definitions. + +###### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> + +###### Remarks + +Call this method before calling `getFlags` to ensure the flag definitions are cached. +The client will ignore subsequent calls to this method. + +###### Inherited from + +[`ReflagClient`](globals.md#reflagclient).[`initialize`](globals.md#initialize) + +### pushFlagOverrides() + +```ts +pushFlagOverrides(overrides: + | Partial> + | FlagOverridesFn): () => void +``` + +Temporarily layers flag overrides on top of the current overrides. + +###### Parameters + + + + + + + + + + + + + + + + +
ParameterTypeDescription
+ +`overrides` + + + + \| [`Partial`](https://www.typescriptlang.org/docs/handbook/utility-types.html#partialtype)\<[`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, [`FlagOverride`](globals.md#flagoverride)\>\> \| [`FlagOverridesFn`](globals.md#flagoverridesfn) + + + +The flag overrides to apply for the scoped period. + +
+ +###### Returns + +`Function` + +A remove function that removes only this override layer. + +###### Returns + +`void` + +###### Remarks + +This is intended for tests or other short-lived local overrides. The remove +function is idempotent and can safely be called multiple times. + +###### Example + +```ts +let remove: (() => void) | undefined; + +beforeEach(() => { + remove = client.pushFlagOverrides({ "flag-1": true }); +}); + +afterEach(() => { + remove?.(); + remove = undefined; +}); +``` + +###### Inherited from + +[`ReflagClient`](globals.md#reflagclient).[`pushFlagOverrides`](globals.md#pushflagoverrides) + +### refreshFlags() + +```ts +refreshFlags(waitForVersion?: number): Promise +``` + +Refreshes the flag definitions from the server. + +###### Parameters + + + + + + + + + + + + + + + + +
ParameterTypeDescription
+ +`waitForVersion`? + + + +`number` + + + +Optional flag state version to wait for before returning updated definitions. + +
+ +###### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> + +###### Remarks + +This triggers an on-demand refresh of the cached flag definitions. +Useful when you know flags have changed and don't want to wait for the next automatic refresh cycle. + +Note: updated flag rules take a few seconds to propagate to all servers. + +Fetch starts are throttled to at most once per second. +Outside `in-request` mode, throttling only delays when the next fetch +begins: `refreshFlags(99)` still waits until the cache has applied flag +definitions from version `99` or newer before the promise resolves. +Concurrent callers are deduplicated and may share the same in-flight or +scheduled follow-up refresh. + +In `in-request` mode, delayed follow-up refreshes are not scheduled. On edge +runtimes like Cloudflare Workers, a call during the throttle window only +records pending refresh work, and the promise may resolve before that fetch +runs. The pending refresh is executed on the next request/access or +`refreshFlags()` call after the throttle window expires. + +###### Inherited from + +[`ReflagClient`](globals.md#reflagclient).[`refreshFlags`](globals.md#refreshflags) + +### setFlagOverrides() + +```ts +setFlagOverrides(overrides: + | Partial> + | FlagOverridesFn): void +``` + +Replaces the base flag overrides used by the client. + +###### Parameters + + + + + + + + + + + + + + + + +
ParameterTypeDescription
+ +`overrides` + + + + \| [`Partial`](https://www.typescriptlang.org/docs/handbook/utility-types.html#partialtype)\<[`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, [`FlagOverride`](globals.md#flagoverride)\>\> \| [`FlagOverridesFn`](globals.md#flagoverridesfn) + + + +The flag overrides. + +
+ +###### Returns + +`void` + +###### Remarks + +Base overrides are always applied before any temporary layers added through +`pushFlagOverrides()`. + +###### Example + +```ts +client.setFlagOverrides({ + "flag-1": true, + "flag-2": false, +}); +``` + +###### Inherited from + +[`ReflagClient`](globals.md#reflagclient).[`setFlagOverrides`](globals.md#setflagoverrides) + +### track() + +```ts +track( + userId: IdType, + event: string, + options?: TrackOptions & { + companyId: IdType; +}): Promise +``` + +Tracks an event in Reflag. + +###### Parameters + + + + + + + + + + + + + + + + + + + + + + +
ParameterType
+ +`userId` + + + +[`IdType`](globals.md#idtype) + +
+ +`event` + + + +`string` + +
+ +`options`? + + + +[`TrackOptions`](globals.md#trackoptions) & \{ `companyId`: [`IdType`](globals.md#idtype); \} + +
+ +###### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> + +###### Throws + +An error if the user is not set or the event is invalid or the options are invalid. + +###### Remarks + +If the company is set, the event will be associated with the company. + +###### Inherited from + +[`ReflagClient`](globals.md#reflagclient).[`track`](globals.md#track) + +### updateCompany() + +```ts +updateCompany(companyId: IdType, options?: TrackOptions & { + userId: IdType; +}): Promise +``` + +Updates the associated company in Reflag. + +###### Parameters + + + + + + + + + + + + + + + + + + + + + +
ParameterTypeDescription
+ +`companyId` + + + +[`IdType`](globals.md#idtype) + + + +The companyId of the company to update. + +
+ +`options`? + + + +[`TrackOptions`](globals.md#trackoptions) & \{ `userId`: [`IdType`](globals.md#idtype); \} + + + +The options for the company. + +
+ +###### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> + +###### Throws + +An error if the company is not set or the options are invalid. + +###### Remarks + +The company must be set using `withCompany` before calling this method. +If the user is set, the company will be associated with the user. + +###### Inherited from + +[`ReflagClient`](globals.md#reflagclient).[`updateCompany`](globals.md#updatecompany) + +### updateUser() + +```ts +updateUser(userId: IdType, options?: TrackOptions): Promise +``` + +Updates the associated user in Reflag. + +###### Parameters + + + + + + + + + + + + + + + + + + + + + +
ParameterTypeDescription
+ +`userId` + + + +[`IdType`](globals.md#idtype) + + + +The userId of the user to update. + +
+ +`options`? + + + +[`TrackOptions`](globals.md#trackoptions) + + + +The options for the user. + +
+ +###### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> + +###### Throws + +An error if the company is not set or the options are invalid. + +###### Remarks + +The company must be set using `withCompany` before calling this method. +If the user is set, the company will be associated with the user. + +###### Inherited from + +[`ReflagClient`](globals.md#reflagclient).[`updateUser`](globals.md#updateuser) + +*** + +### ReflagClient + +The SDK client. + +#### Remarks + +This is the main class for interacting with Reflag. +It is used to evaluate flags, update user and company contexts, and track events. + +#### Example + +```ts +// set the REFLAG_SECRET_KEY environment variable or pass the secret key to the constructor +const client = new ReflagClient(); + +// evaluate a flag +const isFlagEnabled = client.getFlag("flag-key", { + user: { id: "user-id" }, + company: { id: "company-id" }, +}); +``` + +#### Extended by + +- [`EdgeClient`](globals.md#edgeclient) + +#### Constructors + +### new ReflagClient() + +```ts +new ReflagClient(options: ClientOptions): ReflagClient +``` + +Creates a new SDK client. +See README for configuration options. + +###### Parameters + + + + + + + + + + + + + + + + +
ParameterTypeDescription
+ +`options` + + + +[`ClientOptions`](globals.md#clientoptions) + + + +The options for the client or an existing client to clone. + +
+ +###### Returns + +[`ReflagClient`](globals.md#reflagclient) + +###### Throws + +An error if the options are invalid. + +#### Properties + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyModifierTypeDescription
+ + `httpClient` + + + +`public` + + + +[`HttpClient`](globals.md#httpclient) + + + +‐ + +
+ + `logger` + + + +`readonly` + + + +[`Logger`](globals.md#logger) + + + +Gets the logger associated with the client. + +
+ +#### Accessors + +### flagOverrides + +###### Set Signature + +```ts +set flagOverrides(overrides: + | Partial> + | FlagOverridesFn): void +``` + +###### Deprecated + +Use `setFlagOverrides()` for replacing the base override set. + +###### Parameters + + + + + + + + + + + + + + +
ParameterType
+ +`overrides` + + + + \| [`Partial`](https://www.typescriptlang.org/docs/handbook/utility-types.html#partialtype)\<[`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, [`FlagOverride`](globals.md#flagoverride)\>\> \| [`FlagOverridesFn`](globals.md#flagoverridesfn) + +
+ +###### Returns + +`void` + +#### Methods + +### bindClient() + +```ts +bindClient(context: ContextWithTracking): BoundReflagClient +``` + +Returns a new BoundReflagClient with the user/company/otherContext +set to be used in subsequent calls. +For example, for evaluating flag targeting or tracking events. + +###### Parameters + + + + + + + + + + + + + + + + +
ParameterTypeDescription
+ +`context` + + + +[`ContextWithTracking`](globals.md#contextwithtracking) + + + +The context to bind the client to. + +
+ +###### Returns + +[`BoundReflagClient`](globals.md#boundreflagclient) + +A new client bound with the arguments given. + +###### Throws + +An error if the user/company is given but their ID is not a string. + +###### Remarks + +The `updateUser` / `updateCompany` methods will automatically be called when +the user/company is set respectively. + +### clearFlagOverrides() + +```ts +clearFlagOverrides(): void +``` + +Clears the base flag overrides. + +###### Returns + +`void` + +###### Remarks + +This does not affect temporary layers added with `pushFlagOverrides()`. + +###### Example + +```ts +client.clearFlagOverrides(); +``` + +### destroy() + +```ts +destroy(): void +``` + +Destroys the client and cleans up all resources including timers and background processes. + +###### Returns + +`void` + +###### Remarks + +After calling this method, the client should not be used anymore. +This is particularly useful in development environments with hot reloading to prevent +multiple background processes from running simultaneously. + +### flush() + +```ts +flush(): Promise +``` + +Flushes and completes any in-flight fetches in the flag cache. + +###### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> + +###### Remarks + +It is recommended to call this method when the application is shutting down to ensure all events are sent +before the process exits. + +This method is automatically called on natural process exit (`beforeExit`) if +`batchOptions.flushOnExit` is `true` in the options (default). For signal-driven +shutdown or an explicit `process.exit()`, await this method in your application's +shutdown hook before exiting. The SDK does not install signal handlers. + +### getFlag() + +```ts +getFlag(__namedParameters: ContextWithTracking, key: TKey): Flag +``` + +Gets the evaluated flag for the current context which includes the user, company, and custom context. +Using the `isEnabled` property sends a `check` event to Reflag. + +###### Type Parameters + + + + + + + + + + + + +
Type Parameter
+ +`TKey` *extends* `string` + +
+ +###### Parameters + + + + + + + + + + + + + + + + + + + + + +
ParameterTypeDescription
+ +`__namedParameters` + + + +[`ContextWithTracking`](globals.md#contextwithtracking) + + + +‐ + +
+ +`key` + + + +`TKey` + + + +The key of the flag to get. + +
+ +###### Returns + +[`Flag`](globals.md#flagtconfig) + +The evaluated flag. + +###### Remarks + +Call `initialize` before calling this method to ensure the flag definitions are cached, no flags will be returned otherwise. + +### getFlagDefinitions() + +```ts +getFlagDefinitions(): FlagDefinition[] +``` + +Gets the flag definitions, including all config values. +To evaluate which flags are enabled for a given user/company, use `getFlags`. + +###### Returns + +[`FlagDefinition`](globals.md#flagdefinition)[] + +The flags definitions. + +### getFlagRemote() + +```ts +getFlagRemote( + key: TKey, + userId?: IdType, + companyId?: IdType, +additionalContext?: Context): Promise +``` + +Gets evaluated flag with the usage of remote context. +This method triggers a network request every time it's called. + +###### Type Parameters + + + + + + + + + + + + +
Type Parameter
+ +`TKey` *extends* `string` + +
+ +###### Parameters + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ParameterTypeDescription
+ +`key` + + + +`TKey` + + + +The key of the flag to get. + +
+ +`userId`? + + + +[`IdType`](globals.md#idtype) + + + +The userId of the user to get the flag for. + +
+ +`companyId`? + + + +[`IdType`](globals.md#idtype) + + + +The companyId of the company to get the flag for. + +
+ +`additionalContext`? + + + +[`Context`](globals.md#context) + + + +The additional context to get the flag for. + +
+ +###### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<[`Flag`](globals.md#flagtconfig)\> + +evaluated flag + +### getFlags() + +```ts +getFlags(options: ContextWithTracking): Record +``` + +Gets the evaluated flags for the current context which includes the user, company, and custom context. + +###### Parameters + + + + + + + + + + + + + + + + +
ParameterTypeDescription
+ +`options` + + + +[`ContextWithTracking`](globals.md#contextwithtracking) + + + +The options for the context. + +
+ +###### Returns + +[`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, [`Flag`](globals.md#flagtconfig)\> + +The evaluated flags. + +###### Remarks + +Call `initialize` before calling this method to ensure the flag definitions are cached, no flags will be returned otherwise. + +### getFlagsForBootstrap() + +```ts +getFlagsForBootstrap(options: ContextWithTracking): BootstrappedFlags +``` + +Gets the evaluated flags for the current context without wrapping them in getters. +This method returns raw flag data suitable for bootstrapping client-side applications. + +###### Parameters + + + + + + + + + + + + + + + + +
ParameterTypeDescription
+ +`options` + + + +[`ContextWithTracking`](globals.md#contextwithtracking) + + + +The options for the context. + +
+ +###### Returns + +[`BootstrappedFlags`](globals.md#bootstrappedflags) + +The evaluated raw flags and the context. + +###### Remarks + +Call `initialize` before calling this method to ensure the flag definitions are cached, no flags will be returned otherwise. +This method returns RawFlag objects without wrapping them in getters, making them suitable for serialization. + +### getFlagsRemote() + +```ts +getFlagsRemote( + userId?: IdType, + companyId?: IdType, +additionalContext?: Context): Promise> +``` + +Gets evaluated flags with the usage of remote context. +This method triggers a network request every time it's called. + +###### Parameters + + + + + + + + + + + + + + + + + + + + + + + + + + +
ParameterTypeDescription
+ +`userId`? + + + +[`IdType`](globals.md#idtype) + + + +The userId of the user to get the flags for. + +
+ +`companyId`? + + + +[`IdType`](globals.md#idtype) + + + +The companyId of the company to get the flags for. + +
+ +`additionalContext`? + + + +[`Context`](globals.md#context) + + + +The additional context to get the flags for. + +
+ +###### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<[`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, [`Flag`](globals.md#flagtconfig)\>\> + +evaluated flags + +### initialize() + +```ts +initialize(): Promise +``` + +Initializes the client by caching the flags definitions. + +###### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> + +###### Remarks + +Call this method before calling `getFlags` to ensure the flag definitions are cached. +The client will ignore subsequent calls to this method. + +### pushFlagOverrides() + +```ts +pushFlagOverrides(overrides: + | Partial> + | FlagOverridesFn): () => void +``` + +Temporarily layers flag overrides on top of the current overrides. + +###### Parameters + + + + + + + + + + + + + + + + +
ParameterTypeDescription
+ +`overrides` + + + + \| [`Partial`](https://www.typescriptlang.org/docs/handbook/utility-types.html#partialtype)\<[`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, [`FlagOverride`](globals.md#flagoverride)\>\> \| [`FlagOverridesFn`](globals.md#flagoverridesfn) + + + +The flag overrides to apply for the scoped period. + +
+ +###### Returns + +`Function` + +A remove function that removes only this override layer. + +###### Returns + +`void` + +###### Remarks + +This is intended for tests or other short-lived local overrides. The remove +function is idempotent and can safely be called multiple times. + +###### Example + +```ts +let remove: (() => void) | undefined; + +beforeEach(() => { + remove = client.pushFlagOverrides({ "flag-1": true }); +}); + +afterEach(() => { + remove?.(); + remove = undefined; +}); +``` + +### refreshFlags() + +```ts +refreshFlags(waitForVersion?: number): Promise +``` + +Refreshes the flag definitions from the server. + +###### Parameters + + + + + + + + + + + + + + + + +
ParameterTypeDescription
+ +`waitForVersion`? + + + +`number` + + + +Optional flag state version to wait for before returning updated definitions. + +
+ +###### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> + +###### Remarks + +This triggers an on-demand refresh of the cached flag definitions. +Useful when you know flags have changed and don't want to wait for the next automatic refresh cycle. + +Note: updated flag rules take a few seconds to propagate to all servers. + +Fetch starts are throttled to at most once per second. +Outside `in-request` mode, throttling only delays when the next fetch +begins: `refreshFlags(99)` still waits until the cache has applied flag +definitions from version `99` or newer before the promise resolves. +Concurrent callers are deduplicated and may share the same in-flight or +scheduled follow-up refresh. + +In `in-request` mode, delayed follow-up refreshes are not scheduled. On edge +runtimes like Cloudflare Workers, a call during the throttle window only +records pending refresh work, and the promise may resolve before that fetch +runs. The pending refresh is executed on the next request/access or +`refreshFlags()` call after the throttle window expires. + +### setFlagOverrides() + +```ts +setFlagOverrides(overrides: + | Partial> + | FlagOverridesFn): void +``` + +Replaces the base flag overrides used by the client. + +###### Parameters + + + + + + + + + + + + + + + + +
ParameterTypeDescription
+ +`overrides` + + + + \| [`Partial`](https://www.typescriptlang.org/docs/handbook/utility-types.html#partialtype)\<[`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, [`FlagOverride`](globals.md#flagoverride)\>\> \| [`FlagOverridesFn`](globals.md#flagoverridesfn) + + + +The flag overrides. + +
+ +###### Returns + +`void` + +###### Remarks + +Base overrides are always applied before any temporary layers added through +`pushFlagOverrides()`. + +###### Example + +```ts +client.setFlagOverrides({ + "flag-1": true, + "flag-2": false, +}); +``` + +### track() + +```ts +track( + userId: IdType, + event: string, + options?: TrackOptions & { + companyId: IdType; +}): Promise +``` + +Tracks an event in Reflag. + +###### Parameters + + + + + + + + + + + + + + + + + + + + + + +
ParameterType
+ +`userId` + + + +[`IdType`](globals.md#idtype) + +
+ +`event` + + + +`string` + +
+ +`options`? + + + +[`TrackOptions`](globals.md#trackoptions) & \{ `companyId`: [`IdType`](globals.md#idtype); \} + +
+ +###### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> + +###### Throws + +An error if the user is not set or the event is invalid or the options are invalid. + +###### Remarks + +If the company is set, the event will be associated with the company. + +### updateCompany() + +```ts +updateCompany(companyId: IdType, options?: TrackOptions & { + userId: IdType; +}): Promise +``` + +Updates the associated company in Reflag. + +###### Parameters + + + + + + + + + + + + + + + + + + + + + +
ParameterTypeDescription
+ +`companyId` + + + +[`IdType`](globals.md#idtype) + + + +The companyId of the company to update. + +
+ +`options`? + + + +[`TrackOptions`](globals.md#trackoptions) & \{ `userId`: [`IdType`](globals.md#idtype); \} + + + +The options for the company. + +
+ +###### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> + +###### Throws + +An error if the company is not set or the options are invalid. + +###### Remarks + +The company must be set using `withCompany` before calling this method. +If the user is set, the company will be associated with the user. + +### updateUser() + +```ts +updateUser(userId: IdType, options?: TrackOptions): Promise +``` + +Updates the associated user in Reflag. + +###### Parameters + + + + + + + + + + + + + + + + + + + + + +
ParameterTypeDescription
+ +`userId` + + + +[`IdType`](globals.md#idtype) + + + +The userId of the user to update. + +
+ +`options`? + + + +[`TrackOptions`](globals.md#trackoptions) + + + +The options for the user. + +
+ +###### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> + +###### Throws + +An error if the company is not set or the options are invalid. + +###### Remarks + +The company must be set using `withCompany` before calling this method. +If the user is set, the company will be associated with the user. + +## Interfaces + +### ContextWithTracking + +A context with tracking option. + +#### Extends + +- [`Context`](globals.md#context) + +#### Properties + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyTypeDescription
+ + `company?` + + + +\{ `[k: string]`: `any`; `avatar`: `string`; `id`: `undefined` \| `string` \| `number`; `name`: `string`; \} + + + +The company context. If no `id` key is set, the whole object is ignored. + +
+ +`company.avatar?` + + + +`string` + + + +The avatar URL of the company. + +
+ +`company.id` + + + +`undefined` \| `string` \| `number` + + + +The identifier of the company. + +
+ +`company.name?` + + + +`string` + + + +The name of the company. + +
+ + `enableTracking?` + + + +`boolean` + + + +Enable tracking for the context. +If set to `false`, tracking will be disabled for the context. Default is `true`. + +
+ + `meta?` + + + +[`TrackingMeta`](globals.md#trackingmeta) + + + +The meta context used to update the user or company when syncing is required during +feature retrieval. + +
+ + `other?` + + + +[`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, `any`\> + + + +The other context. This is used for any additional context that is not related to user or company. + +
+ + `user?` + + + +\{ `[k: string]`: `any`; `avatar`: `string`; `email`: `string`; `id`: `undefined` \| `string` \| `number`; `name`: `string`; \} + + + +The user context. If no `id` key is set, the whole object is ignored. + +
+ +`user.avatar?` + + + +`string` + + + +The avatar URL of the user. + +
+ +`user.email?` + + + +`string` + + + +The email of the user. + +
+ +`user.id` + + + +`undefined` \| `string` \| `number` + + + +The identifier of the user. + +
+ +`user.name?` + + + +`string` + + + +The name of the user. + +
+ +*** + +### Flag\ + +Describes a feature + +#### Type Parameters + + + + + + + + + + + + + + +
Type ParameterDefault type
+ +`TConfig` *extends* [`FlagType`](globals.md#flagtype)\[`"config"`\] + + + +[`EmptyFlagRemoteConfig`](globals.md#emptyflagremoteconfig) + +
+ +#### Properties + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyTypeDescription
+ + `config` + + + + \| [`EmptyFlagRemoteConfig`](globals.md#emptyflagremoteconfig) \| \{ `key`: `string`; \} & `TConfig` + + + +‐ + +
+ + `isEnabled` + + + +`boolean` + + + +If the feature is enabled. + +
+ + `key` + + + +`string` + + + +The key of the feature. + +
+ +#### Methods + +### track() + +```ts +track(): Promise +``` + +Track feature usage in Reflag. + +###### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> + +*** + +### Flags + +Describes a collection of evaluated features. + +#### Remarks + +You should extend the Flags interface to define the available features. + +*** + +### FlagsFallbackProvider + +Provider used to load and save raw flag definition snapshots. + +#### Methods + +### load() + +```ts +load(context: FlagsFallbackProviderContext): Promise +``` + +Load a previously saved snapshot. + +###### Parameters + + + + + + + + + + + + + + +
ParameterType
+ +`context` + + + +[`FlagsFallbackProviderContext`](globals.md#flagsfallbackprovidercontext) + +
+ +###### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`undefined` \| [`FlagsFallbackSnapshot`](globals.md#flagsfallbacksnapshot)\> + +### save() + +```ts +save(context: FlagsFallbackProviderContext, snapshot: FlagsFallbackSnapshot): Promise +``` + +Persist a snapshot after a successful live fetch. + +###### Parameters + + + + + + + + + + + + + + + + + + +
ParameterType
+ +`context` + + + +[`FlagsFallbackProviderContext`](globals.md#flagsfallbackprovidercontext) + +
+ +`snapshot` + + + +[`FlagsFallbackSnapshot`](globals.md#flagsfallbacksnapshot) + +
+ +###### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> + +*** + +### HttpClient + +Defines the interface for an HTTP client. + +#### Remarks + +This interface is used to abstract the HTTP client implementation from the SDK. +Define your own implementation of this interface to use a different HTTP client. + +#### Methods + +### get() + +```ts +get( + url: string, + headers: Record, +timeoutMs: number): Promise> +``` + +Sends a GET request to the specified URL. + +###### Type Parameters + + + + + + + + + + + + +
Type Parameter
+ +`TResponse` + +
+ +###### Parameters + + + + + + + + + + + + + + + + + + + + + + + + + + +
ParameterTypeDescription
+ +`url` + + + +`string` + + + +The URL to send the request to. + +
+ +`headers` + + + +[`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, `string`\> + + + +The headers to include in the request. + +
+ +`timeoutMs` + + + +`number` + + + +‐ + +
+ +###### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<[`HttpClientResponse`](globals.md#httpclientresponsetresponse)\<`TResponse`\>\> + +The response from the server. + +### post() + +```ts +post( + url: string, + headers: Record, +body: TBody): Promise> +``` + +Sends a POST request to the specified URL. + +###### Type Parameters + + + + + + + + + + + + + + + +
Type Parameter
+ +`TBody` + +
+ +`TResponse` + +
+ +###### Parameters + + + + + + + + + + + + + + + + + + + + + + + + + + +
ParameterTypeDescription
+ +`url` + + + +`string` + + + +The URL to send the request to. + +
+ +`headers` + + + +[`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, `string`\> + + + +The headers to include in the request. + +
+ +`body` + + + +`TBody` + + + +The body of the request. + +
+ +###### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<[`HttpClientResponse`](globals.md#httpclientresponsetresponse)\<`TResponse`\>\> + +The response from the server. + +*** + +### Logger + +Logger interface for logging messages + +#### Properties + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyTypeDescription
+ + `debug` + + + +(`message`: `string`, `data`?: `any`) => `void` + + + +Log a debug messages + +
+ + `error` + + + +(`message`: `string`, `data`?: `any`) => `void` + + + +Log an error messages + +
+ + `info` + + + +(`message`: `string`, `data`?: `any`) => `void` + + + +Log an info messages + +
+ + `warn` + + + +(`message`: `string`, `data`?: `any`) => `void` + + + +Log a warning messages + +
+ +*** + +### RawFlag + +Describes a feature. + +#### Properties + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyTypeDescription
+ + `config?` + + + +[`RawFlagRemoteConfig`](globals.md#rawflagremoteconfig) + + + +The remote configuration value for the feature. + +
+ + `evaluationErrors?` + + + +`EvaluationError`[] + + + +Non-fatal diagnostics produced while evaluating targeting rules. + +
+ + `isEnabled` + + + +`boolean` + + + +If the feature is enabled. + +
+ + `key` + + + +`string` + + + +The key of the feature. + +
+ + ~~`missingContextFields?`~~ + + + +`string`[] + + + +The missing fields in the evaluation context (optional). + +**Deprecated** + +Use `evaluationErrors` and check for `MISSING_CONTEXT_FIELD`. + +
+ + `ruleEvaluationResults?` + + + +`boolean`[] + + + +The rule results of the evaluation (optional). + +
+ + `targetingVersion?` + + + +`number` + + + +The version of the targeting used to evaluate if the feature is enabled (optional). + +
+ +## Type Aliases + +### Attributes + +```ts +type Attributes = Record; +``` + +Describes the attributes of a user, company or event. + +*** + +### BatchBufferOptions\ + +```ts +type BatchBufferOptions = { + flushHandler: (items: T[]) => Promise; + flushOnExit: boolean; + intervalMs: number; + logger: Logger; + maxSize: number; +}; +``` + +Options for configuring the BatchBuffer. + +#### Type Parameters + + + + + + + + + + + + + + +
Type ParameterDescription
+ +`T` + + + +The type of items in the buffer. + +
+ +#### Type declaration + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameTypeDescription
+ + `flushHandler` + + + +(`items`: `T`[]) => [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> + + + +A function that handles flushing the items in the buffer. + +
+ + `flushOnExit`? + + + +`boolean` + + + +Whether to flush the buffer on natural process exit (`beforeExit`). +This does not install signal handlers. For signal-driven shutdown or an +explicit `process.exit()`, await `client.flush()` in your application's +shutdown hook before exiting. + +
+ + `intervalMs`? + + + +`number` + + + +The interval in milliseconds at which the buffer is flushed. + +**Remarks** + +If `0`, the buffer is flushed only when `maxSize` is reached. + +
+ + `logger`? + + + +[`Logger`](globals.md#logger) + + + +The logger to use for logging (optional). + +
+ + `maxSize`? + + + +`number` + + + +The maximum size of the buffer before it is flushed. + +
+ +*** + +### BootstrappedFlags + +```ts +type BootstrappedFlags = { + context: Context; + flags: RawFlags; + flagStateVersion: number; +}; +``` + +Describes a collection of evaluated raw flags and the context for bootstrapping. + +#### Type declaration + + + + + + + + + + + + + + + + + + + + + + +
NameType
+ + `context` + + + +[`Context`](globals.md#context) + +
+ + `flags` + + + +[`RawFlags`](globals.md#rawflags) + +
+ + `flagStateVersion`? + + + +`number` + +
+ +*** + +### CacheStrategy + +```ts +type CacheStrategy = "periodically-update" | "in-request"; +``` + +*** + +### ClientOptions + +```ts +type ClientOptions = { + apiBaseUrl: string; + batchOptions: Omit, "flushHandler" | "logger">; + cacheStrategy: CacheStrategy; + configFile: string; + emitEvaluationEvents: boolean; + fallbackFlags: | TypedFlagKey[] + | Record>; + fetchTimeoutMs: number; + flagOverrides: | FlagOverrides + | (context: Context) => FlagOverrides; + flagsFallbackProvider: FlagsFallbackProvider; + flagsFetchRetries: number; + flagsPushUrl: string; + flagsSyncMode: FlagsSyncMode; + host: string; + httpClient: HttpClient; + logger: Logger; + logLevel: LogLevel; + offline: boolean; + secretKey: string; +}; +``` + +Defines the options for the SDK client. + +#### Type declaration + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameTypeDescription
+ + `apiBaseUrl`? + + + +`string` + + + +The host to send requests to (optional). + +
+ + `batchOptions`? + + + +[`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys)\<[`BatchBufferOptions`](globals.md#batchbufferoptionst)\<`any`\>, `"flushHandler"` \| `"logger"`\> + + + +The options for the batch buffer (optional). +If not provided, the default options are used. + +
+ + `cacheStrategy`? + + + +[`CacheStrategy`](globals.md#cachestrategy) + + + +**Deprecated** + +Use `flagsSyncMode`. + +
+ + `configFile`? + + + +`string` + + + +The path to the config file. If supplied, the config file will be loaded. +Defaults to `reflag.config.json` when NODE_ENV is not production. Can also be +set through the environment variable REFLAG_CONFIG_FILE. + +
+ + `emitEvaluationEvents`? + + + +`boolean` + + + +Deprecated: evaluation events are no longer emitted. + +**Deprecated** + +This option has no effect and will be removed in the next major version. + +
+ + `fallbackFlags`? + + + + \| [`TypedFlagKey`](globals.md#typedflagkey)[] + \| [`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<[`TypedFlagKey`](globals.md#typedflagkey), [`Exclude`](https://www.typescriptlang.org/docs/handbook/utility-types.html#excludeuniontype-excludedmembers)\<[`FlagOverride`](globals.md#flagoverride), `false`\>\> + + + +The features to "enable" as fallbacks when the API is unavailable (optional). +Can be an array of feature keys, or a record of feature keys and boolean or object values. + +If a record is supplied instead of array, the values of each key are either the +configuration values or the boolean value `true`. + +**Deprecated** + +Use `flagsFallbackProvider` instead. + +
+ + `fetchTimeoutMs`? + + + +`number` + + + +The timeout in milliseconds for fetching feature targeting data (optional). +Default is 10000 ms. + +
+ + `flagOverrides`? + + + + \| [`FlagOverrides`](globals.md#flagoverrides) + \| (`context`: [`Context`](globals.md#context)) => [`FlagOverrides`](globals.md#flagoverrides) + + + +Local flag overrides for testing or development. + +If a function is specified, the function will be called with the context +and should return a record of flag keys and boolean or object values. + +
+ + `flagsFallbackProvider`? + + + +[`FlagsFallbackProvider`](globals.md#flagsfallbackprovider) + + + +Optional provider used to load and save raw flag definitions for fallback startup. +Ignored in offline mode. + +
+ + `flagsFetchRetries`? + + + +`number` + + + +Number of times to retry fetching feature definitions (optional). +Default is 3 times. + +
+ + `flagsPushUrl`? + + + +`string` + + + +Push endpoint used when `flagsSyncMode` is `"push"`. + +
+ + `flagsSyncMode`? + + + +[`FlagsSyncMode`](globals.md#flagssyncmode) + + + +How flag definitions are synchronized. + +- `push` (default): live updates over SSE keep flag definitions up to date. +- `polling`: periodic background refresh. +- `in-request`: stale refresh is triggered during request handling. + +
+ + `host`? + + + +`string` + + + +**Deprecated** + +Use `apiBaseUrl` instead. + +
+ + `httpClient`? + + + +[`HttpClient`](globals.md#httpclient) + + + +The HTTP client to use for sending requests (optional). Default is the built-in fetch client. + +
+ + `logger`? + + + +[`Logger`](globals.md#logger) + + + +The logger to use for logging (optional). Default is info level logging to console. + +
+ + `logLevel`? + + + +[`LogLevel`](globals.md#loglevel) + + + +Use the console logger, but set a log level. Ineffective if a custom logger is provided. + +
+ + `offline`? + + + +`boolean` + + + +In offline mode, no data is sent or fetched from the the Reflag API, +and `flagsFallbackProvider` is not used. +This is useful for testing or development. + +
+ + `secretKey`? + + + +`string` + + + +The secret key used to authenticate with the Reflag API. + +
+ +*** + +### Context + +```ts +type Context = { + company: { + [k: string]: any; avatar: string; + id: string | number | undefined; + name: string; + }; + other: Record; + user: { + [k: string]: any; avatar: string; + email: string; + id: string | number | undefined; + name: string; + }; +}; +``` + +Describes the current user context, company context, and other context. +This is used to determine if feature targeting matches and to track events. + +#### Type declaration + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameTypeDescription
+ + `company`? + + + +\{ +`[k: string]`: `any`; `avatar`: `string`; + `id`: `string` \| `number` \| `undefined`; + `name`: `string`; + \} + + + +The company context. If no `id` key is set, the whole object is ignored. + +
+ +`company.avatar`? + + + +`string` + + + +The avatar URL of the company. + +
+ +`company.id` + + + +`string` \| `number` \| `undefined` + + + +The identifier of the company. + +
+ +`company.name`? + + + +`string` + + + +The name of the company. + +
+ + `other`? + + + +[`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, `any`\> + + + +The other context. This is used for any additional context that is not related to user or company. + +
+ + `user`? + + + +\{ +`[k: string]`: `any`; `avatar`: `string`; + `email`: `string`; + `id`: `string` \| `number` \| `undefined`; + `name`: `string`; + \} + + + +The user context. If no `id` key is set, the whole object is ignored. + +
+ +`user.avatar`? + + + +`string` + + + +The avatar URL of the user. + +
+ +`user.email`? + + + +`string` + + + +The email of the user. + +
+ +`user.id` + + + +`string` \| `number` \| `undefined` + + + +The identifier of the user. + +
+ +`user.name`? + + + +`string` + + + +The name of the user. + +
+ +*** + +### EdgeClientOptions + +```ts +type EdgeClientOptions = Omit; +``` + +*** + +### EmptyFlagRemoteConfig + +```ts +type EmptyFlagRemoteConfig = { + key: undefined; + payload: undefined; +}; +``` + +#### Type declaration + + + + + + + + + + + + + + + + + + +
NameType
+ + `key` + + + +`undefined` + +
+ + `payload` + + + +`undefined` + +
+ +*** + +### FileFallbackProviderOptions + +```ts +type FileFallbackProviderOptions = { + directory: string; +}; +``` + +#### Type declaration + + + + + + + + + + + + + + + + +
NameTypeDescription
+ + `directory`? + + + +`string` + + + +Directory where per-environment snapshots are stored. + +
+ +*** + +### FlagAPIResponse + +```ts +type FlagAPIResponse = { + config: { + variants: FlagConfigVariant[]; + version: number; + }; + description: string | null; + key: string; + targeting: { + rules: { + filter: RuleFilter; + }[]; + version: number; + }; +}; +``` + +**`Internal`** + +(Internal) Describes a specific feature in the API response. + +#### Type declaration + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameTypeDescription
+ + `config`? + + + +\{ + `variants`: [`FlagConfigVariant`](globals.md#flagconfigvariant)[]; + `version`: `number`; + \} + + + +The remote configuration for the feature. + +
+ +`config.variants` + + + +[`FlagConfigVariant`](globals.md#flagconfigvariant)[] + + + +The variants of the remote configuration. + +
+ +`config.version` + + + +`number` + + + +The version of the remote configuration. + +
+ + `description` + + + +`string` \| `null` + + + +Description of the feature. + +
+ + `key` + + + +`string` + + + +The key of the feature. + +
+ + `targeting` + + + +\{ + `rules`: \{ + `filter`: `RuleFilter`; + \}[]; + `version`: `number`; + \} + + + +The targeting rules for the feature. + +
+ +`targeting.rules` + + + +\{ + `filter`: `RuleFilter`; + \}[] + + + +The targeting rules. + +
+ +`targeting.version` + + + +`number` + + + +The version of the targeting rules. + +
+ +*** + +### FlagConfigVariant + +```ts +type FlagConfigVariant = { + filter: RuleFilter; + key: string; + payload: any; +}; +``` + +Describes a remote feature config variant. + +#### Type declaration + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameTypeDescription
+ + `filter` + + + +`RuleFilter` + + + +The filter for the variant. + +
+ + `key` + + + +`string` + + + +The key of the variant. + +
+ + `payload` + + + +`any` + + + +The optional user-supplied payload data. + +
+ +*** + +### FlagDefinition + +```ts +type FlagDefinition = { + config: { + variants: FlagConfigVariant[]; + version: number; + }; + description: string | null; + flag: { + rules: { + filter: RuleFilter; + }[]; + version: number; + }; + key: string; +}; +``` + +Describes a feature definition. + +#### Type declaration + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameTypeDescription
+ + `config`? + + + +\{ + `variants`: [`FlagConfigVariant`](globals.md#flagconfigvariant)[]; + `version`: `number`; + \} + + + +The remote configuration for the feature. + +
+ +`config.variants` + + + +[`FlagConfigVariant`](globals.md#flagconfigvariant)[] + + + +The variants of the remote configuration. + +
+ +`config.version` + + + +`number` + + + +The version of the remote configuration. + +
+ + `description` + + + +`string` \| `null` + + + +Description of the feature. + +
+ + `flag` + + + +\{ + `rules`: \{ + `filter`: `RuleFilter`; + \}[]; + `version`: `number`; + \} + + + +The targeting rules for the feature. + +
+ +`flag.rules` + + + +\{ + `filter`: `RuleFilter`; + \}[] + + + +The targeting rules. + +
+ +`flag.version` + + + +`number` + + + +The version of the targeting rules. + +
+ + `key` + + + +`string` + + + +The key of the feature. + +
+ +*** + +### FlagOverride + +```ts +type FlagOverride = + | FlagType & { + config: { + key: string; + }; + isEnabled: boolean; + } + | boolean; +``` + +*** + +### FlagOverrides + +```ts +type FlagOverrides = Partial : { [FlagKey in keyof Flags]: Flags[FlagKey] extends FlagOverride ? Flags[FlagKey] : Exclude }>; +``` + +Describes the feature overrides. + +*** + +### FlagOverridesFn() + +```ts +type FlagOverridesFn = (context: Context) => FlagOverrides; +``` + +#### Parameters + + + + + + + + + + + + + + +
ParameterType
+ +`context` + + + +[`Context`](globals.md#context) + +
+ +#### Returns + +[`FlagOverrides`](globals.md#flagoverrides) + +*** + +### FlagRemoteConfig + +```ts +type FlagRemoteConfig = + | { + key: string; + payload: any; + } + | EmptyFlagRemoteConfig; +``` + +A remotely managed configuration value for a feature. + +#### Type declaration + +\{ + `key`: `string`; + `payload`: `any`; + \} + + + + + + + + + + + + + + + + + + + + + +
NameTypeDescription
+ +`key` + + + +`string` + + + +The key of the matched configuration value. + +
+ +`payload` + + + +`any` + + + +The optional user-supplied payload data. + +
+ +[`EmptyFlagRemoteConfig`](globals.md#emptyflagremoteconfig) + +*** + +### FlagsAPIResponse + +```ts +type FlagsAPIResponse = { + features: FlagAPIResponse[]; + flagStateVersion: number; +}; +``` + +**`Internal`** + +(Internal) Describes the response of the features endpoint. + +#### Type declaration + + + + + + + + + + + + + + + + + + + + + +
NameTypeDescription
+ + `features` + + + +[`FlagAPIResponse`](globals.md#flagapiresponse)[] + + + +The feature definitions. + +
+ + `flagStateVersion`? + + + +`number` + + + +Optional for backward compatibility; when absent, the snapshot version +should be treated as unknown by consumers. + +
+ +*** + +### FlagsFallbackProviderContext + +```ts +type FlagsFallbackProviderContext = { + secretKeyHash: string; +}; +``` + +Non-secret context passed to fallback providers so they can derive +storage keys without access to the raw secret key. + +#### Type declaration + + + + + + + + + + + + + + + + +
NameTypeDescription
+ + `secretKeyHash` + + + +`string` + + + +Deterministic hash of the configured secret key. + +
+ +*** + +### FlagsFallbackSnapshot + +```ts +type FlagsFallbackSnapshot = { + flags: FlagAPIResponse[]; + savedAt: string; + version: number; +}; +``` + +Snapshot of flag definitions used for fallback initialization. + +#### Type declaration + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameTypeDescription
+ + `flags` + + + +[`FlagAPIResponse`](globals.md#flagapiresponse)[] + + + +Raw flag definitions as returned by the API. + +
+ + `savedAt` + + + +`string` + + + +ISO timestamp indicating when the snapshot was saved. + +
+ + `version` + + + +`number` + + + +Snapshot schema version. + +
+ +*** + +### FlagsSyncMode + +```ts +type FlagsSyncMode = "polling" | "in-request" | "push"; +``` + +*** + +### FlagType + +```ts +type FlagType = { + config: { + payload: any; + }; +}; +``` + +#### Type declaration + + + + + + + + + + + + + + + + + + +
NameType
+ + `config`? + + + +\{ + `payload`: `any`; + \} + +
+ +`config.payload` + + + +`any` + +
+ +*** + +### GCSFallbackProviderClient + +```ts +type GCSFallbackProviderClient = + | GCSLegacyClient + | GCSGoogleApisClient; +``` + +*** + +### GCSFallbackProviderOptions + +```ts +type GCSFallbackProviderOptions = { + bucket: string; + client: GCSFallbackProviderClient; + keyPrefix: string; +}; +``` + +#### Type declaration + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameTypeDescription
+ + `bucket` + + + +`string` + + + +Bucket where snapshots are stored. + +
+ + `client`? + + + +[`GCSFallbackProviderClient`](globals.md#gcsfallbackproviderclient) + + + +Optional GCS client. A default client is created when omitted. + +Accepts either a legacy `bucket().file()` client or a generated +`@googleapis/storage` client. + +TODO(next major): Replace this with a simpler object-store interface. + +
+ + `keyPrefix`? + + + +`string` + + + +Prefix for generated per-environment keys. + +
+ +*** + +### GCSGoogleApisClient + +```ts +type GCSGoogleApisClient = { + objects: { + get: Promise<{ + data: unknown; + }>; + insert: Promise; + }; +}; +``` + +#### Type declaration + + + + + + + + + + + + + + + + + + + + + + +
NameType
+ + `objects` + + + +\{ + `get`: [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<\{ + `data`: `unknown`; + \}\>; + `insert`: [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`unknown`\>; + \} + +
+ + `get()` + + + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<\{ + `data`: `unknown`; + \}\> + +
+ + `insert()` + + + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`unknown`\> + +
+ +*** + +### GCSLegacyClient + +```ts +type GCSLegacyClient = { + bucket: { + file: { + download: Promise<[Uint8Array]>; + exists: Promise<[boolean]>; + save: Promise; + }; + }; +}; +``` + +#### Type declaration + + + + + + + + + + + + + + +
NameType
+ + `bucket()` + + + +\{ + `file`: \{ + `download`: [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<\[[`Uint8Array`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array)\]\>; + `exists`: [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<\[`boolean`\]\>; + `save`: [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`unknown`\>; + \}; + \} + +
+ +*** + +### HttpClientResponse\ + +```ts +type HttpClientResponse = { + body: TResponse | undefined; + etag: string; + ok: boolean; + status: number; +}; +``` + +Describes the response of a HTTP client. + +#### Type Parameters + + + + + + + + + + + + + + +
Type ParameterDescription
+ +`TResponse` + + + +The type of the response body. + +
+ +#### Type declaration + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameTypeDescription
+ + `body` + + + +`TResponse` \| `undefined` + + + +The body of the response if available. + +
+ + `etag`? + + + +`string` + + + +The response's ETag, if available. Return its exact value to enable +conditional flag-definition refreshes with a custom HTTP client. + +
+ + `ok` + + + +`boolean` + + + +Indicates that the request succeeded. + +
+ + `status` + + + +`number` + + + +The status code of the response. + +
+ +*** + +### IdType + +```ts +type IdType = string | number; +``` + +*** + +### LogLevel + +```ts +type LogLevel = typeof LOG_LEVELS[number]; +``` + +*** + +### RawFlagRemoteConfig + +```ts +type RawFlagRemoteConfig = { + evaluationErrors: EvaluationError[]; + key: string; + missingContextFields: string[]; + payload: any; + ruleEvaluationResults: boolean[]; + targetingVersion: number; +}; +``` + +A remotely managed configuration value for a feature. + +#### Type declaration + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameTypeDescription
+ + `evaluationErrors`? + + + +`EvaluationError`[] + + + +Non-fatal diagnostics produced while evaluating targeting rules. + +
+ + `key` + + + +`string` + + + +The key of the matched configuration value. + +
+ + `missingContextFields`? + + + +`string`[] + + + +The missing fields in the evaluation context (optional). + +**Deprecated** + +Use `evaluationErrors` and check for `MISSING_CONTEXT_FIELD`. + +
+ + `payload` + + + +`any` + + + +The optional user-supplied payload data. + +
+ + `ruleEvaluationResults`? + + + +`boolean`[] + + + +The rule results of the evaluation (optional). + +
+ + `targetingVersion`? + + + +`number` + + + +The version of the targeting rules used to select the config value. + +
+ +*** + +### RawFlags + +```ts +type RawFlags = Record; +``` + +Describes a collection of evaluated raw flags. + +*** + +### RedisFallbackProviderOptions + +```ts +type RedisFallbackProviderOptions = { + client: { + get: Promise; + set: Promise; + }; + keyPrefix: string; +}; +``` + +#### Type declaration + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameTypeDescription
+ + `client`? + + + +\{ + `get`: [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`undefined` \| `null` \| `string`\>; + `set`: [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`unknown`\>; + \} + + + +Optional Redis client. When omitted, a client is created using `REDIS_URL`. + +
+ + `get()` + + + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`undefined` \| `null` \| `string`\> + + + +‐ + +
+ + `set()` + + + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`unknown`\> + + + +‐ + +
+ + `keyPrefix`? + + + +`string` + + + +Prefix for generated per-environment keys. + +
+ +*** + +### S3FallbackProviderOptions + +```ts +type S3FallbackProviderOptions = { + bucket: string; + client: { + send: Promise; + }; + keyPrefix: string; +}; +``` + +#### Type declaration + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameTypeDescription
+ + `bucket` + + + +`string` + + + +Bucket where snapshots are stored. + +
+ + `client`? + + + +\{ + `send`: [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`any`\>; + \} + + + +Optional S3 client. A default client is created when omitted. + +
+ + `send()` + + + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`any`\> + + + +‐ + +
+ + `keyPrefix`? + + + +`string` + + + +Prefix for generated per-environment keys. + +
+ +*** + +### StaticFallbackProviderOptions + +```ts +type StaticFallbackProviderOptions = { + flags: Record; +}; +``` + +#### Type declaration + + + + + + + + + + + + + + + + +
NameTypeDescription
+ + `flags` + + + +[`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, `boolean`\> + + + +Static fallback flags keyed by flag key. + +
+ +*** + +### TrackingMeta + +```ts +type TrackingMeta = { + active: boolean; +}; +``` + +Describes the meta context associated with tracking. + +#### Type declaration + + + + + + + + + + + + + + + + +
NameTypeDescription
+ + `active`? + + + +`boolean` + + + +Whether the user or company is active. + +
+ +*** + +### TrackOptions + +```ts +type TrackOptions = { + attributes: Attributes; + meta: TrackingMeta; +}; +``` + +Defines the options for tracking of entities. + +#### Type declaration + + + + + + + + + + + + + + + + + + + + + +
NameTypeDescription
+ + `attributes`? + + + +[`Attributes`](globals.md#attributes) + + + +The attributes associated with the event. + +
+ + `meta`? + + + +[`TrackingMeta`](globals.md#trackingmeta) + + + +The meta context associated with the event. + +
+ +*** + +### TypedFlagKey + +```ts +type TypedFlagKey = keyof TypedFlags; +``` + +*** + +### TypedFlags + +```ts +type TypedFlags = keyof Flags extends never ? Record : { [FlagKey in keyof Flags]: Flags[FlagKey] extends FlagType ? Flag : Flag }; +``` + +Describes a collection of evaluated feature. + +#### Remarks + +This types falls back to a generic Record if the Flags interface +has not been extended. + +## Variables + +### fallbackProviders + +```ts +const fallbackProviders: { + file: (__namedParameters: FileFallbackProviderOptions) => FlagsFallbackProvider; + gcs: (__namedParameters: GCSFallbackProviderOptions) => FlagsFallbackProvider; + redis: (__namedParameters: RedisFallbackProviderOptions) => FlagsFallbackProvider; + s3: (__namedParameters: S3FallbackProviderOptions) => FlagsFallbackProvider; + static: (__namedParameters: StaticFallbackProviderOptions) => FlagsFallbackProvider; +}; +``` + +#### Type declaration + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameTypeDefault value
+ + `file` + + + +(`__namedParameters`: [`FileFallbackProviderOptions`](globals.md#filefallbackprovideroptions)) => [`FlagsFallbackProvider`](globals.md#flagsfallbackprovider) + + + +createFileFallbackProvider + +
+ + `gcs` + + + +(`__namedParameters`: [`GCSFallbackProviderOptions`](globals.md#gcsfallbackprovideroptions)) => [`FlagsFallbackProvider`](globals.md#flagsfallbackprovider) + + + +createGCSFallbackProvider + +
+ + `redis` + + + +(`__namedParameters`: [`RedisFallbackProviderOptions`](globals.md#redisfallbackprovideroptions)) => [`FlagsFallbackProvider`](globals.md#flagsfallbackprovider) + + + +createRedisFallbackProvider + +
+ + `s3` + + + +(`__namedParameters`: [`S3FallbackProviderOptions`](globals.md#s3fallbackprovideroptions)) => [`FlagsFallbackProvider`](globals.md#flagsfallbackprovider) + + + +createS3FallbackProvider + +
+ + `static` + + + +(`__namedParameters`: [`StaticFallbackProviderOptions`](globals.md#staticfallbackprovideroptions)) => [`FlagsFallbackProvider`](globals.md#flagsfallbackprovider) + + + +createStaticFallbackProvider + +
+ +*** + +### LOG\_LEVELS + +```ts +const LOG_LEVELS: readonly ["DEBUG", "INFO", "WARN", "ERROR"]; +``` diff --git a/legacy/v1/react-sdk/README.md b/legacy/v1/react-sdk/README.md new file mode 100644 index 0000000..90cc1a6 --- /dev/null +++ b/legacy/v1/react-sdk/README.md @@ -0,0 +1,982 @@ +--- +layout: + visible: true +title: + visible: true +description: + visible: false +tableOfContents: + visible: true +outline: + visible: true +pagination: + visible: true +--- + +{% hint style="info" %} +**Protocol v1 — legacy.** [Current v2 documentation](../../../supported-languages/react-sdk/README.md) · [Migration guide](../../../supported-languages/migrating-from-v1.md) +{% endhint %} + +# Reflag React SDK + +React client side library for [Reflag.com](https://reflag.com) + +Reflag supports flag toggling, tracking flag usage, [requesting feedback](#userequestfeedback) on features, and [remotely configuring flags](#remote-config). + +The Reflag React SDK comes with a [built-in toolbar](../browser-sdk/README.md#toolbar) which appears on `localhost` by default. + +## Install + +Install via npm: + +```shell +npm i @reflag/react-sdk@1 +``` + +## Get started + +### 1. Add the `ReflagProvider` context provider + +Add the `ReflagProvider` context provider to your application: + +**Example:** + +```tsx +import { ReflagProvider } from "@reflag/react-sdk"; + +} +> + {/* children here are shown when loading finishes or immediately if no `loadingComponent` is given */} +; +``` + +### 2. Create a new flag and set up type safety + +Install the Reflag CLI: + +```shell +npm i --save-dev @reflag/cli@1 +``` + +Run `npx reflag new` to create your first flag! +On the first run, it will sign into Reflag and set up type generation for your project: + +```shell +❯ npx reflag new +Opened web browser to facilitate login: https://app.reflag.com/api/oauth/cli/authorize + +Welcome to ◪ Reflag! + +? Where should we generate the types? gen/flags.d.ts +? What is the output format? react +✔ Configuration created at reflag.config.json. + +Creating flag for app Slick app. +? New flag name: Huddle +? New flag key: huddle +✔ Created flag Huddle with key huddle (https://app.reflag.com/features/huddles) +✔ Generated react types in gen/flags.d.ts. +``` + +> [!Note] +> By default, types will be generated in `gen/flags.d.ts`. +> The default `tsconfig.json` file `include`s this file by default, but if your `tsconfig.json` is different, make sure the file is covered in the `include` property. + +### 3. Use `useFlag()` to get flag status + +Using the `useFlag` hook from your components lets you toggle flags on/off and track flag usage: + +**Example:** + +```tsx +function StartHuddleButton() { + const { + isEnabled, // boolean indicating if the flag is enabled + track, // track usage of the flag + } = useFlag("huddle"); + + if (!isEnabled) { + return null; + } + + return ; +} +``` + +`useFlag` can help you do much more. See a full example for `useFlag` [see below](#useflag). + +## Setting context + +Reflag determines which flags are active for a given `user`, `company`, or `other` context. +You can pass these to the `ReflagProvider` using the `context` prop. + +### Using the `context` prop + +```tsx + + + {/* children here are shown when loading finishes */} + + +``` + +### Legacy individual props (deprecated) + +For backward compatibility, you can still use individual props, but these are deprecated and will be removed in the next major version: + +```tsx + + + {/* children here are shown when loading finishes */} + + +``` + +> [!Important] +> The `user`, `company`, and `otherContext` props are deprecated. Use the `context` prop instead, which provides the same functionality in a more structured way. + +### Context requirements + +If you supply `user` or `company` objects, they must include at least the `id` property otherwise they will be ignored in their entirety. +In addition to the `id`, you must also supply anything additional that you want to be able to evaluate flag targeting rules against. +Attributes which are not properties of the `user` or `company` can be supplied using the `other` property. + +Attributes cannot be nested (multiple levels) and must be either strings, numbers or booleans. +A number of special attributes exist: + +- `name` -- display name for `user`/`company`, +- `email` -- the email of the user, +- `avatar` -- the URL for `user`/`company` avatar image. + +To retrieve flags along with their targeting information, use `useFlag(key: string)` hook (described in a section below). + +Note that accessing `isEnabled` on the object returned by `useFlag()` automatically +generates a `check` event. + +## React Native + +For React Native, use `@reflag/react-native-sdk`, which is a thin wrapper around +`@reflag/react-sdk` and wires up AsyncStorage by default. + +An Expo example app lives at `packages/react-native-sdk/dev/expo`. + +## Remote config + +Remote config is a dynamic and flexible approach to configuring flag behavior outside of your app – without needing to re-deploy it. + +Similar to `isEnabled`, each flag accessed using the `useFlag()` hook, has a `config` property. This configuration is managed from within Reflag. It is managed similar to the way access to flags is managed, but instead of the +binary `isEnabled` you can have multiple configuration values which are given to different user/companies. + +### Get started with Remote config + +1. Update your flag definitions: + +```typescript +import "@reflag/react-sdk"; + +// Define your flags by extending the `Flags` interface in @reflag/react-sdk +declare module "@reflag/react-sdk" { + interface Flags { + huddle: { + // change from `boolean` to an object which sets + // a type for the remote config for `questionnaire` + maxTokens: number; + model: string; + }; + } +} +``` + +```ts +const { + isEnabled, + config: { key, payload }, +} = useFlag("huddles"); + +// isEnabled: true, +// key: "gpt-3.5", +// payload: { maxTokens: 10000, model: "gpt-3.5-beta1" } +``` + +`key` is mandatory for a config, but if a flag has no config or no config value was matched against the context, the `key` will be `undefined`. Make sure to check against this case when trying to use the configuration in your application. `payload` is an optional JSON value for arbitrary configuration needs. + +Note that, similar to `isEnabled`, accessing `config` on the object returned by `useFlag()` automatically +generates a `check` event. + +## Toolbar + +The Reflag Toolbar is great for toggling flags on/off for yourself to ensure that everything works both when a flag is on and when it's off. + +Toolbar + +The toolbar will automatically appear on `localhost`. However, it can also be incredibly useful in production. You have full control over when it appears through the `toolbar` configuration option passed to the ReflagProvider. + +You can pass a simple boolean to force the toolbar to appear/disappear: + +```ts + + +For server-side rendered applications, you can render immediately with pre-fetched flag data using the `ReflagBootstrappedProvider`. + +Bootstrapping is also the recommended setup if you want the most resilient feature flag architecture in React. The client renders immediately from flags provided by your server instead of making its initial render depend on a request to Reflag. + +If you want "bullet proof feature flags" in a React application, use React bootstrapping together with `flagsFallbackProvider` in the Node SDK. The fallback provider helps your server start with the latest saved snapshot if it cannot reach Reflag during initialization, and bootstrapping gives the React client server-provided flags for its first render. + +### Using `ReflagBootstrappedProvider` + +The `` component is a specialized version of `ReflagProvider` designed for server-side rendering, preloaded flag scenarios, and high-reliability setups. It uses pre-fetched evaluated state for the initial render, resulting in faster initial page loads, better SSR compatibility, and a more resilient startup path for React applications. + +```tsx +import { useState, useEffect } from "react"; +import { BootstrappedFlags } from "@reflag/react-sdk"; + +interface BootstrapData { + user: User; + flags: BootstrappedFlags; +} + +function useBootstrap() { + const [data, setData] = useState(null); + + useEffect(() => { + fetch("/bootstrap") + .then((res) => res.json()) + .then(setData); + }, []); + + return data; +} + +// Usage in your app +function App() { + const { user, flags } = useBootstrap(); + + return ( + + + + + + ); +} +``` + +### Server-side endpoint setup + +Create an endpoint that provides bootstrap data to your client application: + +```typescript +// server.js or your Express app +import { ReflagClient as ReflagNodeClient } from "@reflag/node-sdk"; + +const reflagClient = new ReflagNodeClient({ + secretKey: process.env.REFLAG_SECRET_KEY, +}); +await reflagClient.initialize(); + +app.get("/bootstrap", (req, res) => { + const user = getUser(req); // Get user from your auth system + const company = getCompany(req); // Get company from your auth system + + const flags = reflagClient.getFlagsForBootstrap({ + user: { id: "user123", name: "John Doe", email: "john@acme.com" }, + company: { id: "company456", name: "Acme Inc", plan: "enterprise" }, + other: { source: "web" }, + }); + + res.status(200).json({ + user, + flags, + }); +}); +``` + +The `flags` object returned by `getFlagsForBootstrap()` contains the full bootstrapped state package: + +- `context`: the evaluation context used on the server +- `flags`: the evaluated raw flags +- `flagStateVersion`: an optional version used to avoid redundant live-update refreshes immediately after bootstrapping + +If you want live flag updates to continue working after bootstrapping, use a recent `@reflag/node-sdk` so `getFlagsForBootstrap()` includes `flagStateVersion`. + +### Next.js Page Router SSR example + +For Next.js applications using server-side rendering, you can pre-fetch flags in `getServerSideProps`: + +```typescript +// pages/index.tsx +import { GetServerSideProps } from "next"; +import { ReflagClient as ReflagNodeClient } from "@reflag/node-sdk"; +import { ReflagBootstrappedProvider, BootstrappedFlags, useFlag } from "@reflag/react-sdk"; + +interface PageProps { + bootstrapData: BootstrappedFlags; +} + +export const getServerSideProps: GetServerSideProps = async (context) => { + const serverClient = new ReflagNodeClient({ + secretKey: process.env.REFLAG_SECRET_KEY + }); + await serverClient.initialize(); + + const user = await getUserFromSession(context.req); + const company = await getCompanyFromUser(user); + + const bootstrapData = serverClient.getFlagsForBootstrap({ + user: { id: "user123", name: "John Doe", email: "john@acme.com" }, + company: { id: "company456", name: "Acme Inc", plan: "enterprise" }, + other: { page: "homepage" } + }); + + return { props: { bootstrapData } }; +}; + +export default function HomePage({ bootstrapData }: PageProps) { + return ( + + + + ); +} + +function HuddleFeature() { + const { isEnabled, track, config } = useFlag("huddle"); + + if (!isEnabled) return null; + + return ( +
+

Start a Huddle

+

Max participants: {config.payload?.maxParticipants ?? 10}

+

Video quality: {config.payload?.videoQuality ?? "standard"}

+ +
+ ); +} +``` + +This approach eliminates loading states and removes the initial render's dependency on the flags API. + +### Next.js App Router example + +For Next.js applications using the App Router (Next.js 13+), you can pre-fetch flags in Server Components and pass them to client components: + +```typescript +// app/layout.tsx (Server Component) +import { ReflagClient as ReflagNodeClient } from "@reflag/node-sdk"; +import { ClientProviders } from "./providers"; + +async function getBootstrapData() { + const serverClient = new ReflagNodeClient({ + secretKey: process.env.REFLAG_SECRET_KEY! + }); + await serverClient.initialize(); + + // In a real app, you'd get user/company from your auth system + const bootstrapData = serverClient.getFlagsForBootstrap({ + user: { id: "user123", name: "John Doe", email: "john@acme.com" }, + company: { id: "company456", name: "Acme Inc", plan: "enterprise" }, + other: { source: "web" } + }); + + return bootstrapData; +} + +export default async function RootLayout({ + children, +}: { + children: React.ReactNode; +}) { + const bootstrapData = await getBootstrapData(); + + return ( + + + + {children} + + + + ); +} +``` + +```typescript +// app/providers.tsx (Client Component) +"use client"; + +import { ReflagBootstrappedProvider, BootstrappedFlags } from "@reflag/react-sdk"; + +interface ClientProvidersProps { + children: React.ReactNode; + bootstrapData: BootstrappedFlags; +} + +export function ClientProviders({ children, bootstrapData }: ClientProvidersProps) { + return ( + + {children} + + ); +} +``` + +```typescript +// app/page.tsx (Server Component) +import { HuddleFeature } from "./huddle-feature"; + +export default function HomePage() { + return ( +
+

My App

+ +
+ ); +} +``` + +```typescript +// app/huddle-feature.tsx (Client Component) +"use client"; + +import { useFlag } from "@reflag/react-sdk"; + +export function HuddleFeature() { + const { isEnabled, track, config } = useFlag("huddle"); + + if (!isEnabled) return null; + + return ( +
+

Start a Huddle

+

Max participants: {config.payload?.maxParticipants ?? 10}

+

Video quality: {config.payload?.videoQuality ?? "standard"}

+ +
+ ); +} +``` + +This App Router approach leverages Server Components for server-side flag fetching while using Client Components only where React state and hooks are needed. + +## `` component + +The `` is a lower-level component that accepts a `ReflagClient` instance. This is useful for advanced use cases where you need full control over client initialization or want to share a client instance across multiple parts of your application. + +In most cases you should initialize the client before rendering this provider. If you pass an idle client and enable `suspense`, a `useFlag()` call that suspends can initialize the client on demand; without Suspense, you must initialize the client yourself. + +### Usage + +```tsx +import { ReflagClient } from "@reflag/browser-sdk"; +import { ReflagClientProvider } from "@reflag/react-sdk"; + +// Initialize the client yourself +const client = new ReflagClient({ + publishableKey: "your-publishable-key", + user: { id: "user123", name: "John Doe" }, + company: { id: "company456", name: "Acme Inc" }, + // ... other configuration options +}); + +// Initialize the client +await client.initialize(); + +function App() { + return ( + }> + + + ); +} +``` + +### Props + +The `ReflagClientProvider` accepts the following props: + +- `client`: A `ReflagClient` instance. Prefer passing an already-initialized client; idle clients are initialized on demand only by suspense-enabled `useFlag()` calls. +- `loadingComponent`: Optional React component to show while the client is initializing (same as `ReflagProvider`) +- `suspense`: Optional. Set to `true` to make `useFlag()` suspend while the client is loading + +> [!Note] +> Most applications should use `ReflagProvider` or `ReflagBootstrappedProvider` instead of `ReflagClientProvider`. Only use this component when you need the advanced control it provides. + +## `` component + +The `` initializes the Reflag SDK, fetches flags and starts listening for automated feedback survey events. The component can be configured using a number of props: + +- `publishableKey` is used to connect the provider to an _environment_ on Reflag. Find your `publishableKey` under [environment settings](https://app.reflag.com/env-current/settings/app-environments) in Reflag, +- `context` (recommended): An object containing `user`, `company`, and `other` properties that make up the evaluation context used to determine if a flag is enabled or not. `company` and `user` contexts are automatically transmitted to Reflag servers so the Reflag app can show you which companies have access to which flags etc. +- `company`, `user` and `other` (deprecated): Individual props for context. These are deprecated in favor of the `context` prop and will be removed in the next major version. + > [!Note] + > If you specify `company` and/or `user` they must have at least the `id` property, otherwise they will be ignored in their entirety. You should also supply anything additional you want to be able to evaluate flag targeting against, +- `fallbackFlags`: A list of strings which specify which flags to consider enabled if the SDK is unable to fetch flags. Can be provided in two formats: + + ```ts + // Simple array of flag keys + fallbackFlags={["flag1", "flag2"]} + + // Or with configuration overrides + fallbackFlags: { + "flag1": true, // just enable the flag + "flag2": { // enable with configuration + key: "variant-a", + payload: { + limit: 100, + mode: "test" + } + } + } + ``` + +- `timeoutMs`: Timeout in milliseconds when fetching flags from the server. +- `staleWhileRevalidate`: If set to `true`, stale flags will be returned while refetching flags in the background. +- `expireTimeMs`: If set, flags will be cached between page loads for this duration (in milliseconds). +- `staleTimeMs`: Maximum time (in milliseconds) that stale flags will be returned if `staleWhileRevalidate` is true and new flags cannot be fetched. +- `offline`: Provide this option when testing or in local development environments to avoid contacting Reflag servers. +- `loadingComponent` lets you specify an React component to be rendered instead of the children while the Reflag provider is initializing. If you want more control over loading screens, `useFlag()` and `useIsLoading` returns `isLoading` which you can use to customize the loading experience. +- `suspense`: Set to `true` to make `useFlag()` suspend while the provider is loading and `useOptInFlags()` suspend while required opt-in metadata is loading. Wrap components that call these hooks in React `` boundaries and omit `loadingComponent` if you want Suspense fallbacks to control loading UI. +- `enableTracking`: Set to `false` to stop sending tracking events and user/company updates to Reflag. Useful when you're impersonating a user (defaults to `true`), +- `enableLiveFlagUpdates`: Enables live flag updates over SSE. Defaults to `true` in the React SDK. +- `apiBaseUrl`: Optional base URL for the Reflag API. This also controls the SSE origin used for live flag updates and automated feedback, +- `credentials`: Optional fetch credentials mode. Set to `"include"` when proxying through your backend and authenticating with cookies; this also enables credentials for live-update SSE connections. +- `appBaseUrl`: Optional base URL for the Reflag application. Use this to override the default app URL, + +- `logger`: Optional custom logger implementation (`debug`, `info`, `warn`, `error`) used by the underlying client, +- `debug`: Set to `true` to enable debug logging to the console. If both `logger` and `debug` are provided, `logger` takes precedence, +- `toolbar`: Optional [configuration](../browser-sdk/globals.md#toolbaroptions) for the Reflag toolbar, +- `feedback`: Optional configuration for feedback collection + +## `` component + +The `` is a specialized version of the `ReflagProvider` that uses pre-fetched flag data for the initial render. This is ideal for server-side rendering scenarios. + +The component accepts the following props: + +- `flags`: Pre-fetched bootstrapped state of type `BootstrappedFlags` obtained from the Node SDK's `getFlagsForBootstrap()` method. This contains the context (`flags.context`), the evaluated flags (`flags.flags`), and an optional `flags.flagStateVersion`. +- All other props available in [`ReflagProvider`](#reflagprovider-component) are supported except `context`, `user`, `company`, and `other` (which are extracted from `flags.context`). + +**Example:** + +```tsx +import { + ReflagBootstrappedProvider, + BootstrappedFlags, +} from "@reflag/react-sdk"; + +interface AppProps { + bootstrapData: BootstrappedFlags; +} + +function App({ bootstrapData }: AppProps) { + return ( + } + debug={process.env.NODE_ENV === "development"} + > + + + ); +} +``` + +> [!Note] +> When using `ReflagBootstrappedProvider`, pass the entire object returned by `getFlagsForBootstrap()` directly as the `flags` prop. The context is extracted from `flags.context`, and `flags.flagStateVersion` is used when present. +> +> With `ReflagBootstrappedProvider`, `useOptInFlags()` requests a flags refresh on first use. It returns `isLoading: true` (or suspends) until that refresh settles. +> +> If you want live flag updates to continue working after bootstrapping, use a recent `@reflag/node-sdk` so `getFlagsForBootstrap()` includes `flagStateVersion`. +> +> After bootstrapping, any live flag updates are fetched directly by the browser SDK from Reflag using the browser-visible context. If your bootstrapped snapshot depends on server-only or secret context that is not available in the browser, later live refreshes may differ. In that case, keep `enableLiveFlagUpdates` disabled. +> +> Requesting opt-in flags also triggers a browser-side refresh, even when `enableLiveFlagUpdates` is disabled. + +## Hooks + +### `useFlag()` + +Returns the state of a given flag for the current context. The hook provides type-safe access to flags and their configurations. + +```tsx +import { useFlag } from "@reflag/react-sdk"; +import { Loading } from "./Loading"; + +function StartHuddleButton() { + const { + isLoading, // true while flags are being loaded + isEnabled, // boolean indicating if the flag is enabled + config: { + // flag configuration + key, // string identifier for the config variant + payload, // type-safe configuration object + }, + track, // function to track flag usage + requestFeedback, // function to request feedback for this flag + } = useFlag("huddle"); + + if (isLoading) { + return ; + } + + if (!isEnabled) { + return null; + } + + return ( + <> + + + + ); +} +``` + +#### Suspense loading + +Enable `suspense` on the provider to have `useFlag()` throw a promise while `isLoading` is true. The nearest `` boundary will render its fallback until flags are ready. + +```tsx +import { Suspense } from "react"; +import { ReflagProvider } from "@reflag/react-sdk"; + + + }> + + +; +``` + +You can also opt in for a single call with `useFlag("huddle", { suspense: true })`, or opt out inside a suspense-enabled provider with `{ suspense: false }`. + +### `useOptInFlags()` and `useSetOptIn()` + +Use these hooks to build an end-user opt-in UI for flags where opt-in is enabled in Reflag. + +```tsx +import { + type OptInFlag, + useIsLoading, + useOptInFlags, + useSetOptIn, +} from "@reflag/react-sdk"; + +function OptInList() { + const isProviderLoading = useIsLoading(); + const { flags, isLoading } = useOptInFlags(); + const setOptIn = useSetOptIn(); + + async function toggleOptIn(flag: OptInFlag) { + try { + const response = await setOptIn(flag.key, { + optedIn: !flag.userOptedIn, + }); + if (!response?.ok) { + console.error("Could not update opt-in"); + } + } catch (error) { + console.error("Could not update opt-in", error); + } + } + + if (isProviderLoading || isLoading) { + return

Loading…

; + } + + return flags.map((flag) => ( + + )); +} +``` + +By default, `useSetOptIn()` changes the opt-in for the current user, so the current context must include a `user.id`. To manage the current company's opt-in instead, pass `scope: "company"`; the context must then include a `company.id`. + +User and company opt-ins are managed independently. Setting `optedIn` to `false` removes the opt-in only for the selected scope. For example, cancelling a user's opt-in does not change the company's opt-in for the same flag. + +`setOptIn` returns a promise so you can wait for the new membership state to be synchronized. On success, it resolves after the refreshed flag state has been applied locally, the requested membership change has been confirmed, and subscribers have been notified when flags change. React may not have committed the resulting render yet. + +The promise resolves to a `Response`, or `undefined` if skipped due to invalid input, offline mode etc. Check `response?.ok` for success. + +`useOptInFlags()` returns `{ flags, isLoading }`. With `ReflagBootstrappedProvider`, it fetches opt-in metadata on first use and reports `isLoading: true` until that refresh succeeds or fails. + +If fetching opt-in metadata fails, loading ends without exposing an error. Call `client.refresh()` on the client returned by `useClient()` to retry. + +With a regular `ReflagProvider`, opt-in metadata arrives as part of the normal initial flags request, so `useOptInFlags().isLoading` remains `false`. Use the general `useIsLoading()` hook or the provider's `loadingComponent` for that initial loading state. + +`useOptInFlags()` also supports Suspense. It respects the provider-level `suspense` option, or you can enable it for only this hook with `useOptInFlags({ suspense: true })`. While required opt-in metadata is loading, the nearest `` boundary renders its fallback: + +```tsx +import { Suspense } from "react"; + + + }> + + +; +``` + +Opt-in metadata Suspense is primarily relevant with `ReflagBootstrappedProvider`. Use `useOptInFlags({ suspense: false })` to opt out for one call when Suspense is enabled on the provider. + +### `useTrack()` + +`useTrack()` lets you send custom events to Reflag. Use this whenever a user _uses_ a feature. These events can be used to analyze feature usage in Reflag. + +```tsx +import { useTrack } from "@reflag/react-sdk"; + +function StartHuddle() { + const { track } = useTrack(); +
+ +
; +} +``` + +### `useRequestFeedback()` + +`useRequestFeedback()` returns a function that lets you open up a dialog to ask for feedback on a specific feature. This is useful for collecting targeted feedback about specific features as part of roll out. See [Automated Feedback Surveys](https://docs.reflag.com/product-handbook/live-satisfaction) for how to do this automatically, without code. + +When using the `useRequestFeedback` you must pass the flag key to `requestFeedback`. +The example below shows how to use `position` to ensure the popover appears next to the "Give feedback!" button. + +```tsx +import { useRequestFeedback } from "@reflag/react-sdk"; + +function FeedbackButton() { + const requestFeedback = useRequestFeedback(); + return ( + + ); +} +``` + +See the [Feedback Documentation](https://github.com/reflagcom/javascript/blob/b4fe5b3d9386b87c6546175c323862d9878e1430/packages/browser-sdk/FEEDBACK.md#manual-feedback-collection) for more information on `requestFeedback` options. + +### `useSendFeedback()` + +Returns a function that lets you send feedback to Reflag. This is useful if you've manually collected feedback through your own UI and want to send it to Reflag. + +```tsx +import { useSendFeedback } from "@reflag/react-sdk"; + +function CustomFeedbackForm() { + const sendFeedback = useSendFeedback(); + + const handleSubmit = async (data: FormData) => { + await sendFeedback({ + flagKey: "reflag-flag-key", + score: parseInt(data.get("score") as string), + comment: data.get("comment") as string, + }); + }; + + return
...
; +} +``` + +### `useUpdateUser()`, `useUpdateCompany()` and `useUpdateOtherContext()` + +These hooks return functions that let you update the attributes for the currently set user, company, or other context. Updates to user/company are stored remotely and affect flag targeting, while "other" context updates only affect the current session. + +```tsx +import { + useUpdateUser, + useUpdateCompany, + useUpdateOtherContext, +} from "@reflag/react-sdk"; + +function FlagOptIn() { + const updateUser = useUpdateUser(); + const updateCompany = useUpdateCompany(); + const updateOtherContext = useUpdateOtherContext(); + + const handleUserUpdate = async () => { + await updateUser({ + role: "admin", + betaFlags: "enabled", + }); + }; + + const handleCompanyUpdate = async () => { + await updateCompany({ + plan: "enterprise", + employees: 500, + }); + }; + + const handleContextUpdate = async () => { + await updateOtherContext({ + currentWorkspace: "workspace-123", + theme: "dark", + }); + }; + + return ( +
+ + + +
+ ); +} +``` + +### `useClient()` + +Returns the `ReflagClient` used by the `ReflagProvider`. The client offers more functionality that +is not directly accessible thorough the other hooks. + +```tsx +import { useClient } from "@reflag/react-sdk"; + +function LoggingWrapper({ children }: { children: ReactNode }) { + const client = useClient(); + + console.log(client.getContext()); + + return children; +} +``` + +### `useIsLoading()` + +Returns the loading state of the flags in the `ReflagClient`. +Initially, the value will be `true` if no bootstrap flags have been provided and the client has not be initialized. + +```tsx +import { useIsLoading } from "@reflag/react-sdk"; +import { Spinner } from "./Spinner"; + +function LoadingWrapper({ children }: { children: ReactNode }) { + const isLoading = useIsLoading(); + + if (isLoading) { + return ; + } + + return children; +} +``` + +### `useOnEvent()` + +Attach a callback handler to client events to act on changes. It automatically disposes itself on unmount. + +```tsx +import { useOnEvent } from "@reflag/react-sdk"; + +function LoggingWrapper({ children }: { children: ReactNode }) { + useOnEvent("flagsUpdated", (newFlags) => { + console.log(newFlags); + }); + + return children; +} +``` + +## Migrating from Bucket SDK + +If you have been using the Bucket SDKs, the following list will help you migrate to Reflag SDK: + +- `Bucket*` classes, and types have been renamed to `Reflag*` (e.g. `BucketClient` is now `ReflagClient`) +- `Feature*` classes, and types have been renamed to `Flag*` (e.g. `Feature` is now `Flag`, `RawFeatures` is now `RawFlags`) +- When using strongly-typed flags, the new `Flags` interface replaced `Features` interface +- All methods that contained `feature` in the name have been renamed to use the `flag` terminology (e.g. `getFeature` is `getFlag`) +- The `fallbackFeatures` property in client constructor and configuration files has been renamed to `fallbackFlags` +- `featureKey` has been renamed to `flagKey` in all methods that accepts that argument +- The SDKs will not emit `evaluate` and `evaluate-config` events anymore +- The new cookies that are stored in the client's browser are now `reflag-*` prefixed instead of `bucket-*` +- The `featuresUpdated` hook has been renamed to `flagsUpdated` +- The `checkIsEnabled` and `checkConfig` hooks have been removed, use `check` from now on + +To ease in transition to Reflag SDK, some of the old methods have been preserved as aliases to the new methods: + +- `getFeature` method is an alias for `getFlag` +- `getFeatures` method is an alias for `getFlags` +- `useFeature` method is an alias for `useFlag` +- `featuresUpdated` hook is an alias for `flagsUpdated` + +If you are running with strict Content Security Policies active on your website, you will need change them as follows: + +- `connect-src https://front.bucket.co` to `connect-src https://front.reflag.com` + +## Content Security Policy (CSP) + +See [CSP](https://github.com/reflagcom/javascript/blob/b4fe5b3d9386b87c6546175c323862d9878e1430/packages/browser-sdk/README.md#content-security-policy-csp) for info on using Reflag React SDK with CSP + +## License + +MIT License + +Copyright (c) 2025 Bucket ApS diff --git a/legacy/v1/react-sdk/globals.md b/legacy/v1/react-sdk/globals.md new file mode 100644 index 0000000..f7bc6e3 --- /dev/null +++ b/legacy/v1/react-sdk/globals.md @@ -0,0 +1,2324 @@ +--- +layout: + visible: true +title: + visible: true +description: + visible: false +tableOfContents: + visible: true +outline: + visible: true +pagination: + visible: true +--- + +{% hint style="info" %} +**Protocol v1 — legacy.** [Current v2 documentation](../../../supported-languages/react-sdk/globals.md) · [Migration guide](../../../supported-languages/migrating-from-v1.md) +{% endhint %} + +# @reflag/react-sdk + +## Interfaces + +### CheckEvent + +Event representing checking the flag evaluation result + +#### Properties + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyTypeDescription
+ + `action` + + + +`"check-is-enabled"` \| `"check-config"` + + + +`check-is-enabled` means `isEnabled` was checked, `check-config` means `config` was checked. + +
+ + `evaluationErrors?` + + + +\{ `code`: `string`; `field`: `string`; `message`: `string`; `operator`: `string`; \}[] + + + +Non-fatal diagnostics produced while evaluating the flag. + +
+ + `key` + + + +`string` + + + +Flag key. + +
+ + ~~`missingContextFields?`~~ + + + +`string`[] + + + +Missing context fields. + +**Deprecated** + +Use `evaluationErrors` and check for `MISSING_CONTEXT_FIELD`. + +
+ + `ruleEvaluationResults?` + + + +`boolean`[] + + + +Rule evaluation results. + +
+ + `value?` + + + + \| `boolean` \| \{ `key`: `string`; `payload`: `any`; \} + + + +Result of flag or configuration evaluation. +If `action` is `check-is-enabled`, this is the result of the flag evaluation and `value` is a boolean. +If `action` is `check-config`, this is the result of the configuration evaluation. + +
+ + `version?` + + + +`number` + + + +Version of targeting rules. + +
+ +*** + +### CompanyContext + +Context is a set of key-value pairs. +This is used to determine if feature targeting matches and to track events. +Id should always be present so that it can be referenced to an existing company. + +#### Indexable + +```ts +[key: string]: ContextValue +``` + +#### Properties + + + + + + + + + + + + + + + + + + + + + +
PropertyTypeDescription
+ + `id` + + + +`undefined` \| `string` \| `number` + + + +Company id + +
+ + `name?` + + + +`string` + + + +Company name + +
+ +*** + +### Flag\ + +Describes a feature + +#### Type Parameters + + + + + + + + + + + + + + +
Type ParameterDefault type
+ +`TConfig` *extends* [`FlagType`](globals.md#flagtype)\[`"config"`\] + + + +[`EmptyFlagRemoteConfig`](globals.md#emptyflagremoteconfig) + +
+ +#### Properties + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyTypeDescription
+ + `config` + + + + \| [`EmptyFlagRemoteConfig`](globals.md#emptyflagremoteconfig) \| \{ `key`: `string`; \} & `TConfig` + + + +‐ + +
+ + `isEnabled` + + + +`boolean` + + + +If the feature is enabled. + +
+ + `isLoading` + + + +`boolean` + + + +If the feature is loading. + +
+ + `key` + + + +`string` + + + +The key of the feature. + +
+ + `requestFeedback` + + + +(`opts`: [`RequestFeedbackOptions`](globals.md#requestfeedbackoptions)) => `void` + + + +Request feedback from the user. + +
+ +#### Methods + +### track() + +```ts +track(): + | undefined + | Promise< + | undefined +| Response> +``` + +Track feature usage in Reflag. + +###### Returns + + \| `undefined` + \| [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\< + \| `undefined` + \| [`Response`](https://developer.mozilla.org/docs/Web/API/Response)\> + +*** + +### Flags + +*** + +### UserContext + +Context is a set of key-value pairs. +This is used to determine if feature targeting matches and to track events. +Id should always be present so that it can be referenced to an existing user. + +#### Indexable + +```ts +[key: string]: ContextValue +``` + +#### Properties + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyTypeDescription
+ + `email?` + + + +`string` + + + +User email + +
+ + `id` + + + +`undefined` \| `string` \| `number` + + + +User id + +
+ + `name?` + + + +`string` + + + +User name + +
+ +## Type Aliases + +### BootstrappedFlags + +```ts +type BootstrappedFlags = BootstrappedState & { + flags: RawFlags; +}; +``` + +#### Type declaration + + + + + + + + + + + + + + +
NameType
+ +`flags` + + + +[`RawFlags`](../browser-sdk/globals.md#rawflags) + +
+ +*** + +### EmptyFlagRemoteConfig + +```ts +type EmptyFlagRemoteConfig = { + key: undefined; + payload: undefined; +}; +``` + +#### Type declaration + + + + + + + + + + + + + + + + + + +
NameType
+ + `key` + + + +`undefined` + +
+ + `payload` + + + +`undefined` + +
+ +*** + +### FlagKey + +```ts +type FlagKey = keyof TypedFlags; +``` + +*** + +### FlagRemoteConfig + +```ts +type FlagRemoteConfig = + | { + key: string; + payload: any; + } + | EmptyFlagRemoteConfig; +``` + +A remotely managed configuration value for a feature. + +#### Type declaration + +\{ + `key`: `string`; + `payload`: `any`; + \} + + + + + + + + + + + + + + + + + + + + + +
NameTypeDescription
+ +`key` + + + +`string` + + + +The key of the matched configuration value. + +
+ +`payload` + + + +`any` + + + +The optional user-supplied payload data. + +
+ +[`EmptyFlagRemoteConfig`](globals.md#emptyflagremoteconfig) + +*** + +### FlagType + +```ts +type FlagType = { + config: { + payload: any; + }; +}; +``` + +#### Type declaration + + + + + + + + + + + + + + + + + + +
NameType
+ + `config`? + + + +\{ + `payload`: `any`; + \} + +
+ +`config.payload` + + + +`any` + +
+ +*** + +### OptInFlag + +```ts +type OptInFlag = Omit & { + key: FlagKey; +}; +``` + +An opt-in-enabled flag for the generated React SDK flag definitions. + +Includes all fields from [BrowserOptInFlag](../browser-sdk/globals.md#optinflag): `name`, `description`, +`isEnabled`, `userOptedIn`, `companyOptedIn`, and `isOptedIn`. +Only `key` is narrowed to the generated [FlagKey](globals.md#flagkey) type. + +#### Type declaration + + + + + + + + + + + + + + +
NameType
+ +`key` + + + +[`FlagKey`](globals.md#flagkey) + +
+ +*** + +### RawFlags + +```ts +type RawFlags = Record; +``` + +Describes a collection of evaluated raw flags. + +*** + +### ReflagBootstrappedProps + +```ts +type ReflagBootstrappedProps = ReflagPropsBase & ReflagInitOptionsBase & { + flags: BootstrappedFlags; +}; +``` + +Props for the ReflagBootstrappedProvider. + +#### Type declaration + + + + + + + + + + + + + + + + +
NameTypeDescription
+ +`flags` + + + +[`BootstrappedFlags`](globals.md#bootstrappedflags) + + + +Pre-fetched flags used for the initial render. The browser client fetches opt-in +metadata on demand when opt-in flags are requested. + +
+ +*** + +### ReflagClientProviderProps + +```ts +type ReflagClientProviderProps = Omit & { + client: ReflagClient; +}; +``` + +Props for the ReflagClientProvider. + +#### Type declaration + + + + + + + + + + + + + + +
NameType
+ +`client` + + + +[`ReflagClient`](../browser-sdk/globals.md#reflagclient) + +
+ +*** + +### ReflagInitOptionsBase + +```ts +type ReflagInitOptionsBase = Omit; +``` + +**`Internal`** + +Base init options for the ReflagProvider and ReflagBootstrappedProvider. + +*** + +### ReflagProps + +```ts +type ReflagProps = ReflagPropsBase & ReflagInitOptionsBase & { + company: CompanyContext; + context: ReflagContext; + otherContext: Record; + user: UserContext; +}; +``` + +Props for the ReflagProvider. + +#### Type declaration + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameTypeDescription
+ +`company`? + + + +[`CompanyContext`](globals.md#companycontext) + + + +Company related context. If you provide `id` Reflag will enrich the evaluation context with +company attributes on Reflag servers. + +**Deprecated** + +Use `context` instead, this property will be removed in the next major version + +
+ +`context`? + + + +[`ReflagContext`](../browser-sdk/globals.md#reflagcontext) + + + +The context to use for the ReflagClient containing user, company, and other context. + +
+ +`otherContext`? + + + +[`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, `string` \| `number` \| `undefined`\> + + + +Context which is not related to a user or a company. + +**Deprecated** + +Use `context` instead, this property will be removed in the next major version + +
+ +`user`? + + + +[`UserContext`](globals.md#usercontext) + + + +User related context. If you provide `id` Reflag will enrich the evaluation context with +user attributes on Reflag servers. + +**Deprecated** + +Use `context` instead, this property will be removed in the next major version + +
+ +*** + +### ReflagPropsBase + +```ts +type ReflagPropsBase = { + children: ReactNode; + debug: boolean; + initialLoading: boolean; + loadingComponent: ReactNode; + logger: Logger; + suspense: boolean; +}; +``` + +**`Internal`** + +Base props for the ReflagProvider and ReflagBootstrappedProvider. + +#### Type declaration + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameTypeDescription
+ + `children`? + + + +`ReactNode` + + + +The children to render after the client is initialized. + +
+ + `debug`? + + + +`boolean` + + + +Set to `true` to enable debug logging to the console, + +
+ + `initialLoading`? + + + +`boolean` + + + +Set to `true` to show the loading component while the client is initializing. + +
+ + `loadingComponent`? + + + +`ReactNode` + + + +A React component to show while the client is initializing. + +
+ + `logger`? + + + +[`Logger`](../browser-sdk/globals.md#logger) + + + +A custom logger to use for SDK logs. +Use this for advanced control or filtering of SDK logs. +If both `logger` and `debug` are provided, `logger` takes precedence. + +
+ + `suspense`? + + + +`boolean` + + + +Set to `true` to make `useFlag` and `useOptInFlags` suspend while their +required flag data is loading. Components that call either hook must be +wrapped in a React `` boundary. + +
+ +*** + +### RequestFeedbackOptions + +```ts +type RequestFeedbackOptions = Omit; +``` + +*** + +### SetOptInOptions + +```ts +type SetOptInOptions = { + optedIn: boolean; + scope?: "user" | "company"; +}; +``` + +Options for changing the current user or company's opt-in membership. + +#### Type declaration + + + + + + + + + + + + + + + + + + + + + +
NameTypeDescription
+ + `optedIn` + + + +`boolean` + + + +Whether the scoped subject has opted in. + +
+ + `scope`? + + + +`"user"` \| `"company"` + + + +Whether to update the current user or current company. Defaults to `user`. + +
+ +*** + +### StorageAdapter + +```ts +type StorageAdapter = { + getItem: Promise; + removeItem: Promise; + setItem: Promise; +}; +``` + +#### Type declaration + + + + + + + + + + + + + + + + + + + + + + +
NameType
+ + `getItem()` + + + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`null` \| `string`\> + +
+ + `removeItem()`? + + + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> + +
+ + `setItem()` + + + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> + +
+ +*** + +### TrackEvent + +```ts +type TrackEvent = { + attributes: | Record + | null; + company: CompanyContext; + eventName: string; + user: UserContext; +}; +``` + +#### Type declaration + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameType
+ + `attributes`? + + + + \| [`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, `any`\> + \| `null` + +
+ + `company`? + + + +[`CompanyContext`](globals.md#companycontext) + +
+ + `eventName` + + + +`string` + +
+ + `user` + + + +[`UserContext`](globals.md#usercontext) + +
+ +*** + +### TypedFlags + +```ts +type TypedFlags = keyof Flags extends never ? Record : { [TypedFlagKey in keyof Flags]: Flags[TypedFlagKey] extends FlagType ? Flag : Flag }; +``` + +Describes a collection of evaluated feature. + +#### Remarks + +This types falls back to a generic Record if the Flags interface +has not been extended. + +*** + +### UseFlagOptions + +```ts +type UseFlagOptions = { + suspense: boolean; +}; +``` + +#### Type declaration + + + + + + + + + + + + + + + + +
NameTypeDescription
+ + `suspense`? + + + +`boolean` + + + +Override the provider suspense setting for this `useFlag` call. +When true, `useFlag` throws a promise while flags are loading. + +
+ +*** + +### UseOptInFlagsOptions + +```ts +type UseOptInFlagsOptions = { + suspense?: boolean; +}; +``` + +#### Type declaration + + + + + + + + + + + + + + + + +
NameTypeDescription
+ + `suspense`? + + + +`boolean` + + + +Override the provider suspense setting for this `useOptInFlags` call. +When true, `useOptInFlags` throws a promise while opt-in flags are loading. + +
+ +*** + +### UseOptInFlagsResult + +```ts +type UseOptInFlagsResult = { + flags: OptInFlag[]; + isLoading: boolean; +}; +``` + +#### Type declaration + + + + + + + + + + + + + + + + + + + + + +
NameTypeDescription
+ + `flags` + + + +[`OptInFlag`](globals.md#optinflag)[] + + + +Opt-in-enabled flags for the current context. + +
+ + `isLoading` + + + +`boolean` + + + +Whether a bootstrapped provider is fetching opt-in metadata. + +
+ +## Functions + +### ReflagBootstrappedProvider() + +```ts +function ReflagBootstrappedProvider(__namedParameters: ReflagBootstrappedProps): Element +``` + +Bootstrapped Provider for the ReflagClient using pre-fetched flags. + +#### Parameters + + + + + + + + + + + + + + +
ParameterType
+ +`__namedParameters` + + + +[`ReflagBootstrappedProps`](globals.md#reflagbootstrappedprops) + +
+ +#### Returns + +`Element` + +*** + +### ReflagClientProvider() + +```ts +function ReflagClientProvider(__namedParameters: ReflagClientProviderProps): Element +``` + +#### Parameters + + + + + + + + + + + + + + +
ParameterType
+ +`__namedParameters` + + + +[`ReflagClientProviderProps`](globals.md#reflagclientproviderprops) + +
+ +#### Returns + +`Element` + +*** + +### ReflagProvider() + +```ts +function ReflagProvider(__namedParameters: ReflagProps): Element +``` + +Provider for the ReflagClient. + +#### Parameters + + + + + + + + + + + + + + +
ParameterType
+ +`__namedParameters` + + + +[`ReflagProps`](globals.md#reflagprops) + +
+ +#### Returns + +`Element` + +*** + +### useClient() + +```ts +function useClient(): ReflagClient +``` + +Returns the current `ReflagClient` used by the `ReflagProvider`. + +This is useful if you need to access the `ReflagClient` outside of the `ReflagProvider`. + +#### Returns + +[`ReflagClient`](../browser-sdk/globals.md#reflagclient) + +The `ReflagClient`. + +#### Example + +```ts +import { useClient } from '@reflag/react-sdk'; + +function App() { + const client = useClient(); + console.log(client.getContext()); +} +``` + +*** + +### ~~useFeature()~~ + +```ts +function useFeature(key: TKey, options?: UseFlagOptions): Flag +``` + +#### Type Parameters + + + + + + + + + + + + +
Type Parameter
+ +`TKey` *extends* `string` + +
+ +#### Parameters + + + + + + + + + + + + + + + + + + +
ParameterType
+ +`key` + + + +`TKey` + +
+ +`options`? + + + +[`UseFlagOptions`](globals.md#useflagoptions) + +
+ +#### Returns + +[`Flag`](globals.md#flagtconfig) + +#### Deprecated + +use `useFlag` instead + +*** + +### useFlag() + +```ts +function useFlag(key: TKey, options: UseFlagOptions): TypedFlags[TKey] +``` + +Returns the state of a given feature for the current context, e.g. + +```ts +function HuddleButton() { + const {isEnabled, config: { payload }, track} = useFlag("huddle"); + if (isEnabled) { + return ; +} +``` + +#### Type Parameters + + + + + + + + + + + + +
Type Parameter
+ +`TKey` *extends* `string` + +
+ +#### Parameters + + + + + + + + + + + + + + + + + + +
ParameterType
+ +`key` + + + +`TKey` + +
+ +`options` + + + +[`UseFlagOptions`](globals.md#useflagoptions) + +
+ +#### Returns + +[`TypedFlags`](globals.md#typedflags)\[`TKey`\] + +*** + +### useIsLoading() + +```ts +function useIsLoading(): boolean +``` + +Returns a boolean indicating if the Reflag client is loading. +You can use this to check if the Reflag client is loading at any point in your application. +Initially, the value will be true until the client is initialized. + +#### Returns + +`boolean` + +A boolean indicating if the Reflag client is loading. + +#### Example + +```ts +import { useIsLoading } from '@reflag/react-sdk'; + +const isLoading = useIsLoading(); + +console.log(isLoading); +``` + +*** + +### useOnEvent() + +```ts +function useOnEvent( + event: THookType, + handler: (arg0: HookArgs[THookType]) => void, + client?: ReflagClient): void +``` + +Attach a callback handler to client events to act on changes. It automatically disposes itself on unmount. + +#### Type Parameters + + + + + + + + + + + + +
Type Parameter
+ +`THookType` *extends* keyof [`HookArgs`](../browser-sdk/globals.md#hookargs) + +
+ +#### Parameters + + + + + + + + + + + + + + + + + + + + + + + + + + +
ParameterTypeDescription
+ +`event` + + + +`THookType` + + + +The event to listen to. + +
+ +`handler` + + + +(`arg0`: [`HookArgs`](../browser-sdk/globals.md#hookargs)\[`THookType`\]) => `void` + + + +The function to call when the event is triggered. + +
+ +`client`? + + + +[`ReflagClient`](../browser-sdk/globals.md#reflagclient) + + + +The Reflag client to listen to. If not provided, the client will be retrieved from the context. + +
+ +#### Returns + +`void` + +#### Example + +```ts +import { useOnEvent } from '@reflag/react-sdk'; + +useOnEvent("flagsUpdated", () => { + console.log("flags updated"); +}); +``` + +*** + +### useOptInFlags() + +```ts +function useOptInFlags(options?: UseOptInFlagsOptions): UseOptInFlagsResult +``` + +Returns opt-in-enabled flags and their loading state for the current context. + +The loading state is only used with `ReflagBootstrappedProvider` while +opt-in metadata is fetched on demand. Regular providers load opt-in metadata +with the initial flags; use [useIsLoading](globals.md#useisloading) for their loading state. +When suspense is enabled for the provider or this hook, it suspends instead +of returning a loading result. A Suspense boundary alone does not enable it. + +If fetching opt-in metadata fails, loading ends without exposing an error. +Call `refresh()` on the client returned by [useClient](globals.md#useclient) to retry. + +#### Parameters + + + + + + + + + + + + + + +
ParameterType
+ +`options`? + + + +[`UseOptInFlagsOptions`](globals.md#useoptinflagsoptions) + +
+ +#### Returns + +[`UseOptInFlagsResult`](globals.md#useoptinflagsresult) + +*** + +### useRequestFeedback() + +```ts +function useRequestFeedback(): (options: RequestFeedbackData) => void +``` + +Returns a function to open up the feedback form +Note: When calling `useRequestFeedback`, user/company must already be set. + +See [link](../browser-sdk/feedback.md) for more information + +```ts +const requestFeedback = useRequestFeedback(); +reflag.requestFeedback({ + flagKey: "file-uploads", + title: "How satisfied are you with file uploads?", +}); +``` + +#### Returns + +`Function` + +### Parameters + + + + + + + + + + + + + + +
ParameterType
+ +`options` + + + +[`RequestFeedbackData`](../browser-sdk/globals.md#requestfeedbackdata) + +
+ +### Returns + +`void` + +*** + +### useSendFeedback() + +```ts +function useSendFeedback(): (opts: UnassignedFeedback) => Promise< + | undefined +| Response> +``` + +Returns a function to manually send feedback collected from a user. +Note: When calling `useSendFeedback`, user/company must already be set. + +See [link](../browser-sdk/feedback.md) for more information + +```ts +const sendFeedback = useSendFeedback(); +sendFeedback({ + flagKey: "huddle"; + question: "How did you like the new huddle feature?"; + score: 5; + comment: "I loved it!"; +}); +``` + +#### Returns + +`Function` + +### Parameters + + + + + + + + + + + + + + +
ParameterType
+ +`opts` + + + +[`UnassignedFeedback`](../browser-sdk/globals.md#unassignedfeedback) + +
+ +### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\< + \| `undefined` + \| [`Response`](https://developer.mozilla.org/docs/Web/API/Response)\> + +*** + +### useSetOptIn() + +```ts +function useSetOptIn(): (key: string, options: SetOptInOptions) => Promise< + | undefined +| Response> +``` + +Returns a function to set whether the current user or company has opted into a flag. + +Check the returned Response's `ok` property and catch promise rejections. +HTTP failures return a non-OK Response; offline mode, invalid arguments, or +missing scoped context return undefined. Confirmation failures can reject +after the membership changed remotely. See [ReflagClient.setOptIn](../browser-sdk/globals.md#setoptin). + +#### Returns + +`Function` + +### Parameters + + + + + + + + + + + + + + + + + + +
ParameterType
+ +`key` + + + +`string` + +
+ +`options` + + + +[`SetOptInOptions`](globals.md#setoptinoptions) + +
+ +### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\< + \| `undefined` + \| [`Response`](https://developer.mozilla.org/docs/Web/API/Response)\> + +*** + +### useTrack() + +```ts +function useTrack(): (eventName: string, attributes?: + | null + | Record) => Promise< + | undefined +| Response> +``` + +Returns a function to send an event when a user performs an action +Note: When calling `useTrack`, user/company must already be set. + +```ts +const track = useTrack(); +track("Started Huddle", { button: "cta" }); +``` + +#### Returns + +`Function` + +### Parameters + + + + + + + + + + + + + + + + + + +
ParameterType
+ +`eventName` + + + +`string` + +
+ +`attributes`? + + + + \| `null` \| [`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, `any`\> + +
+ +### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\< + \| `undefined` + \| [`Response`](https://developer.mozilla.org/docs/Web/API/Response)\> + +*** + +### useUpdateCompany() + +```ts +function useUpdateCompany(): (opts: {}) => Promise +``` + +Returns a function to update the current company's information. +For example, if the company changed plan or opted into a beta-feature. + +The method returned is a function which returns a promise that +resolves when after the features have been updated as a result +of the company update. + +```ts +const updateCompany = useUpdateCompany(); +updateCompany({ plan: "enterprise" }).then(() => console.log("Flags updated")); +``` + +#### Returns + +`Function` + +### Parameters + + + + + + + + + + + + + + +
ParameterType
+ +`opts` + + + +\{\} + +
+ +### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> + +*** + +### useUpdateOtherContext() + +```ts +function useUpdateOtherContext(): (opts: {}) => Promise +``` + +Returns a function to update the "other" context information. +For example, if the user changed workspace, you can set the workspace id here. + +The method returned is a function which returns a promise that +resolves when after the features have been updated as a result +of the update to the "other" context. + +```ts +const updateOtherContext = useUpdateOtherContext(); +updateOtherContext({ workspaceId: newWorkspaceId }) + .then(() => console.log("Flags updated")); +``` + +#### Returns + +`Function` + +### Parameters + + + + + + + + + + + + + + +
ParameterType
+ +`opts` + + + +\{\} + +
+ +### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> + +*** + +### useUpdateUser() + +```ts +function useUpdateUser(): (opts: {}) => Promise +``` + +Returns a function to update the current user's information. +For example, if the user changed role or opted into a beta-feature. + +The method returned is a function which returns a promise that +resolves when after the features have been updated as a result +of the user update. + +```ts +const updateUser = useUpdateUser(); +updateUser({ optInHuddles: "true" }).then(() => console.log("Flags updated")); +``` + +#### Returns + +`Function` + +### Parameters + + + + + + + + + + + + + + +
ParameterType
+ +`opts` + + + +\{\} + +
+ +### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> diff --git a/legacy/v1/vue-sdk/README.md b/legacy/v1/vue-sdk/README.md new file mode 100644 index 0000000..c86cc39 --- /dev/null +++ b/legacy/v1/vue-sdk/README.md @@ -0,0 +1,710 @@ +--- +layout: + visible: true +title: + visible: true +description: + visible: false +tableOfContents: + visible: true +outline: + visible: true +pagination: + visible: true +--- + +{% hint style="info" %} +**Protocol v1 — legacy.** [Current v2 documentation](../../../supported-languages/vue-sdk/README.md) · [Migration guide](../../../supported-languages/migrating-from-v1.md) +{% endhint %} + +# Reflag Vue SDK + +Vue client side library for [Reflag.com](https://reflag.com) + +Reflag supports flag toggling, tracking flag usage, requesting feedback on features and remotely configuring flags. + +The Reflag Vue SDK comes with the same built-in toolbar as the browser SDK which appears on `localhost` by default. + +## Install + +Install via npm: + +```shell +npm i @reflag/vue-sdk@1 +``` + +## Migrating from Bucket SDK + +If you have been using the Bucket SDKs, the following list will help you migrate to Reflag SDK: + +- `Bucket*` classes, and types have been renamed to `Reflag*` (e.g. `BucketClient` is now `ReflagClient`) +- `Feature*` classes, and types have been renamed to `Feature*` (e.g. `Feature` is now `Flag`, `RawFeatures` is now `RawFlags`) +- All methods that contained `feature` in the name have been renamed to use the `flag` terminology (e.g. `getFeature` is `getFlag`) +- The `fallbackFeatures` property in client constructor and configuration files has been renamed to `fallbackFlags` +- `featureKey` has been renamed to `flagKey` in all methods that accepts that argument +- The SDKs will not emit `evaluate` and `evaluate-config` events anymore +- The new cookies that are stored in the client's browser are now `reflag-*` prefixed instead og `bucket-*` +- The `featuresUpdated` hook has been renamed to `flagsUpdated` +- The `checkIsEnabled` and `checkConfig` hooks have been removed, use `check` from now on + +To ease in transition to Reflag SDK, some of the old methods have been preserved as aliases to the new methods: + +- `getFeature` method is an alias for `getFlag` +- `getFeatures` method is an alias for `getFlags` +- `featuresUpdated` hook is an alias for `flagsUpdated` + +If you are running with strict Content Security Policies active on your website, you will need change them as follows: + +- `connect-src https://front.bucket.co` to `connect-src https://front.reflag.com` + +Finally, if you have customized the look & feel of the Feedback component, update `--bucket-feedback-*` CSS classes to `--reflag-feedback-*` + +## Get started + +### 1. Add the `ReflagProvider` context provider + +Add the `ReflagProvider` context provider to your application: + +**Example:** + +```vue + + + + + +``` + +If using Nuxt, wrap `` in ``. `` only renders client-side currently. + +### 2. Use `useFlag get flag status + +```vue + + + +``` + +See [useFlag()](#useflag) for a full example + +## Setting context + +Reflag determines which flags are active for a given `user`, `company`, or `other` context. +You can pass these to the `ReflagProvider` using the `context` prop. + +### Using the `context` prop + +```vue + + + +``` + +### Legacy individual props (deprecated) + +For backward compatibility, you can still use individual props, but these are deprecated and will be removed in the next major version: + +```vue + + + +``` + +> [!Important] +> The `user`, `company`, and `otherContext` props are deprecated. Use the `context` prop instead, which provides the same functionality in a more structured way. + +### Context requirements + +If you supply `user` or `company` objects, they must include at least the `id` property otherwise they will be ignored in their entirety. +In addition to the `id`, you must also supply anything additional that you want to be able to evaluate flag targeting rules against. +Attributes which are not properties of the `user` or `company` can be supplied using the `other` property. + +Attributes cannot be nested (multiple levels) and must be either strings, numbers or booleans. +A number of special attributes exist: + +- `name` -- display name for `user`/`company`, +- `email` -- the email of the user, +- `avatar` -- the URL for `user`/`company` avatar image. + +To retrieve flags along with their targeting information, use `useFlag(key: string)` hook (described in a section below). + +Note that accessing `isEnabled` on the object returned by `useFlag()` automatically +generates a `check` event. + +## Remote config + +Remote config is a dynamic and flexible approach to configuring flag behavior outside of your app – without needing to re-deploy it. + +Similar to `isEnabled`, each flag accessed using the `useFlag()` hook, has a `config` property. This configuration is managed from within Reflag. It is managed similar to the way access to flags is managed, but instead of the +binary `isEnabled` you can have multiple configuration values which are given to different user/companies. + +### Get started with Remote config + +```ts +const { + isEnabled, + config: { key, payload }, +} = useFlag("huddles"); + +// isEnabled: true, +// key: "gpt-3.5", +// payload: { maxTokens: 10000, model: "gpt-3.5-beta1" } +``` + +`key` is mandatory for a config, but if a flag has no config or no config value was matched against the context, the `key` will be `undefined`. Make sure to check against this case when trying to use the configuration in your application. `payload` is an optional JSON value for arbitrary configuration needs. + +Note that, similar to `isEnabled`, accessing `config` on the object returned by `useFlag()` automatically +generates a `check` event. + +## `` component + +The `` initializes the Reflag SDK, fetches flags and starts listening for automated feedback survey events. The component can be configured using a number of props: + +- `publishableKey` is used to connect the provider to an _environment_ on Reflag. Find your `publishableKey` under [environment settings](https://app.reflag.com/env-current/settings/app-environments) in Reflag, +- `context`: An object containing `user`, `company`, and `other` properties that make up the evaluation context used to determine if a flag is enabled or not. `company` and `user` contexts are automatically transmitted to Reflag servers so the Reflag app can show you which companies have access to which flags etc. +- `company`, `user` and `otherContext` (deprecated): Individual props for context. These are deprecated in favor of the `context` prop and will be removed in the next major version. + + > [!Note] + > If you specify `company` and/or `user` they must have at least the `id` property, otherwise they will be ignored in their entirety. You should also supply anything additional you want to be able to evaluate flag targeting against, + +- `timeoutMs`: Timeout in milliseconds when fetching flags from the server, +- `staleWhileRevalidate`: If set to `true`, stale flags will be returned while refetching flags in the background, +- `expireTimeMs`: If set, flags will be cached between page loads for this duration (in milliseconds), +- `staleTimeMs`: Maximum time (in milliseconds) that stale flags will be returned if `staleWhileRevalidate` is true and new flags cannot be fetched. + +- `enableTracking`: Set to `false` to stop sending tracking events and user/company updates to Reflag. Useful when you're impersonating a user (defaults to `true`), +- `apiBaseUrl`: Optional base URL for the Reflag API. This also controls the SSE origin used for live flag updates and automated feedback, +- `credentials`: Optional fetch credentials mode. Set to `"include"` when proxying through your backend and authenticating with cookies; this also enables credentials for live-update SSE connections. +- `appBaseUrl`: Optional base URL for the Reflag application. Use this to override the default app URL, + +- `debug`: Set to `true` to enable debug logging to the console. If both `logger` and `debug` are provided, `logger` takes precedence, +- `logger`: Optional custom logger implementation (`debug`, `info`, `warn`, `error`) used by the underlying client, +- `toolbar`: Optional [configuration](../browser-sdk/globals.md#toolbaroptions) for the Reflag toolbar, +- `feedback`: Optional configuration for feedback collection + +### Loading states + +ReflagProvider lets you define a template to be shown while ReflagProvider is initializing: + +```vue + +``` + +If you want more control over loading screens, `useIsLoading()` returns a `Ref` which you can use to customize the loading experience. + +## `` component + +The `` component is a specialized version of `ReflagProvider` designed for server-side rendering and preloaded flag scenarios. It uses pre-fetched flags for the initial render, resulting in faster initial page loads and better SSR compatibility. + +### Usage + +```vue + + + +``` + +### Getting bootstrapped flags + +You'll typically generate the `bootstrappedFlags` object on your server using the Node.js SDK or by fetching from the Reflag API. Pass the full object returned by `getFlagsForBootstrap()` directly to ``. It contains: + +- `context`: the evaluation context used on the server +- `flags`: the evaluated raw flags +- `flagStateVersion`: an optional version used to avoid redundant live-update refreshes immediately after bootstrapping + +If you want live flag updates to continue working after bootstrapping, use a recent `@reflag/node-sdk` so `getFlagsForBootstrap()` includes `flagStateVersion`. + +With `ReflagBootstrappedProvider`, `useOptInFlags()` requests a flags refresh on first use. It reports `isLoading: true` until that refresh settles. + +Here's an example using the Node.js SDK: + +```js +// server.js (Node.js/SSR) +import { ReflagClient } from "@reflag/node-sdk"; + +const client = new ReflagClient({ + secretKey: "your-secret-key", // Use secret key on server +}); +await client.initialize(); + +// Fetch flags for specific context +const context = { + user: { id: "user123", name: "John Doe", email: "john@acme.com" }, + company: { id: "company456", name: "Acme Inc", plan: "enterprise" }, +}; + +const bootstrappedFlags = client.getFlagsForBootstrap(context); + +// Pass to your Vue app +``` + +### ReflagBootstrappedProvider Props + +`ReflagBootstrappedProvider` accepts all the same props as `ReflagProvider` except: + +- `flags`: The pre-fetched bootstrapped state object containing `context`, evaluated `flags`, and an optional `flagStateVersion` +- All other props available in `ReflagProvider` are supported except `context`, `user`, `company`, and `otherContext` (which are extracted from `flags.context`) + +If the `flags` prop is not provided or is undefined, the provider will not initialize the client and will render in a non-loading state. + +{% hint style="info" %} +After bootstrapping, any live flag updates are fetched directly by the browser SDK from Reflag using the browser-visible context. If your bootstrapped snapshot depends on server-only or secret context that is not available in the browser, later live refreshes may differ. In that case, keep `enableLiveFlagUpdates` disabled. + +Requesting opt-in flags also triggers a browser-side refresh, even when `enableLiveFlagUpdates` is disabled. +{% endhint %} + +## `` component + +The `` is a lower-level component that accepts a pre-initialized `ReflagClient` instance. This is useful for advanced use cases where you need full control over client initialization or want to share a client instance across multiple parts of your application. + +### ReflagClientProvider Usage + +```vue + + + +``` + +### ReflagClientProvider Props + +The `ReflagClientProvider` accepts the following props: + +- `client`: A pre-initialized `ReflagClient` instance + +### Slots + +- `loading`: Optional slot to show while the client is initializing (same as `ReflagProvider`) + +> [!Note] +> Most applications should use `ReflagProvider` or `ReflagBootstrappedProvider` instead of `ReflagClientProvider`. Only use this component when you need the advanced control it provides. + +## Hooks + +### `useFlag()` + +Returns the state of a given flag for the current context. The composable provides access to flags and their configurations. + +`useFlag()` returns an object with this shape: + +```ts +{ + isEnabled: boolean, // is the flag enabled + track: () => void, // send a track event when the flag is used + requestFeedback: (...) => void // open up a feedback dialog + config: {key: string, payload: any}, // remote configuration for this flag + isLoading: boolean // if you want to manage loading state at the flag level +} +``` + +Example: + +```vue + + + +``` + +See the reference docs for details. + +### `useOptInFlags()` and `useSetOptIn()` + +Use these composables to build an end-user opt-in UI for flags where opt-in is enabled in Reflag. + +```vue + + + +``` + +By default, `useSetOptIn()` changes the opt-in for the current user, so the current context must include a `user.id`. To manage the current company's opt-in instead, pass `scope: "company"`; the context must then include a `company.id`. + +User and company opt-ins are managed independently. Setting `optedIn` to `false` removes the opt-in only for the selected scope. For example, cancelling a user's opt-in does not change the company's opt-in for the same flag. + +`setOptIn` returns a promise so you can wait for the new membership state to be synchronized. On success, it resolves after the refreshed flag state has been applied locally, the requested membership change has been confirmed, and subscribers have been notified when flags change. Vue may not have committed the resulting render yet. + +The promise resolves to a `Response`, or `undefined` if skipped due to invalid input, offline mode etc. Check `response?.ok` for success. + +`useOptInFlags()` returns `{ flags, isLoading }`, where both values are computed refs. With `ReflagBootstrappedProvider`, it fetches opt-in metadata on first use and reports `isLoading: true` until that refresh succeeds or fails. + +If fetching opt-in metadata fails, loading ends without exposing an error. Call `client.refresh()` on the client returned by `useClient()` to retry. + +With a regular `ReflagProvider`, opt-in metadata arrives as part of the normal initial flags request, so `useOptInFlags().isLoading` remains `false`. Use the general `useIsLoading()` composable or the provider's loading slot for that initial loading state. + +### `useTrack()` + +`useTrack()` returns a function which lets you send custom events to Reflag. It takes a string argument with the event name and optionally an object with properties to attach the event. + +Using `track` returned from `useFlag()` calls this track function with the flag key as the event name. + +```vue + + + +``` + +### `useRequestFeedback()` + +Returns a function that lets you open up a dialog to ask for feedback on a specific feature. This is useful for collecting targeted feedback about specific features. + +See [Automated Feedback Surveys](https://docs.reflag.com/product-handbook/live-satisfaction) for how to do this automatically, without code. + +When using the `useRequestFeedback` you must pass the flag key to `requestFeedback`. +The example below shows how to use `position` to ensure the popover appears next to the "Give feedback!" button. + +```vue + + + +``` + +See the [Feedback Documentation](https://github.com/reflagcom/javascript/blob/b4fe5b3d9386b87c6546175c323862d9878e1430/packages/browser-sdk/FEEDBACK.md#manual-feedback-collection) for more information on `requestFeedback` options. + +### `useSendFeedback()` + +Returns a function that lets you send feedback to Reflag. This is useful if you've manually collected feedback through your own UI and want to send it to Reflag. + +```vue + + + +``` + +### `useUpdateUser()`, `useUpdateCompany()` and `useUpdateOtherContext()` + +These composables return functions that let you update the attributes for the currently set user, company, or other context. Updates to user/company are stored remotely and affect flag targeting, while "other" context updates only affect the current session. + +```vue + + + +``` + +Note: To change the `user.id` or `company.id`, you need to update the props passed to `ReflagProvider` instead of using these composables. + +### `useClient()` + +Returns the `ReflagClient` used by the `ReflagProvider`. The client offers more functionality that +is not directly accessible through the other composables. + +```vue + + + +``` + +### `useIsLoading()` + +Returns a `Ref` to indicate if Reflag has finished loading. +Initially, the value will be `true` if no bootstrap flags have been provided and the client has not be initialized. + +```vue + + + +``` + +### `useOnEvent()` + +Vue composable for listening to Reflag client events. This composable automatically handles mounting and unmounting of event listeners. + +Available events include: + +- `flagsUpdated`: Triggered when flags are updated +- `track`: Triggered when tracking events are sent +- `feedback`: Triggered when feedback is sent + +```vue + + + +``` + +You can also provide a specific client instance if needed: + +```vue + + + +``` + +## Content Security Policy (CSP) + +See [CSP](https://github.com/reflagcom/javascript/blob/b4fe5b3d9386b87c6546175c323862d9878e1430/packages/browser-sdk/README.md#content-security-policy-csp) for info on using Reflag React SDK with CSP + +## License + +MIT License + +Copyright (c) 2025 Bucket ApS diff --git a/legacy/v1/vue-sdk/globals.md b/legacy/v1/vue-sdk/globals.md new file mode 100644 index 0000000..a58808a --- /dev/null +++ b/legacy/v1/vue-sdk/globals.md @@ -0,0 +1,1897 @@ +--- +layout: + visible: true +title: + visible: true +description: + visible: false +tableOfContents: + visible: true +outline: + visible: true +pagination: + visible: true +--- + +{% hint style="info" %} +**Protocol v1 — legacy.** [Current v2 documentation](../../../supported-languages/vue-sdk/globals.md) · [Migration guide](../../../supported-languages/migrating-from-v1.md) +{% endhint %} + +# @reflag/vue-sdk + +## Interfaces + +### CheckEvent + +Event representing checking the flag evaluation result + +#### Properties + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyTypeDescription
+ + `action` + + + +`"check-is-enabled"` \| `"check-config"` + + + +`check-is-enabled` means `isEnabled` was checked, `check-config` means `config` was checked. + +
+ + `evaluationErrors?` + + + +\{ `code`: `string`; `field`: `string`; `message`: `string`; `operator`: `string`; \}[] + + + +Non-fatal diagnostics produced while evaluating the flag. + +
+ + `key` + + + +`string` + + + +Flag key. + +
+ + ~~`missingContextFields?`~~ + + + +`string`[] + + + +Missing context fields. + +**Deprecated** + +Use `evaluationErrors` and check for `MISSING_CONTEXT_FIELD`. + +
+ + `ruleEvaluationResults?` + + + +`boolean`[] + + + +Rule evaluation results. + +
+ + `value?` + + + + \| `boolean` \| \{ `key`: `string`; `payload`: `any`; \} + + + +Result of flag or configuration evaluation. +If `action` is `check-is-enabled`, this is the result of the flag evaluation and `value` is a boolean. +If `action` is `check-config`, this is the result of the configuration evaluation. + +
+ + `version?` + + + +`number` + + + +Version of targeting rules. + +
+ +*** + +### CompanyContext + +Context is a set of key-value pairs. +This is used to determine if feature targeting matches and to track events. +Id should always be present so that it can be referenced to an existing company. + +#### Indexable + +```ts +[key: string]: ContextValue +``` + +#### Properties + + + + + + + + + + + + + + + + + + + + + +
PropertyTypeDescription
+ + `id` + + + +`undefined` \| `string` \| `number` + + + +Company id + +
+ + `name?` + + + +`string` + + + +Company name + +
+ +*** + +### Flag\ + +#### Type Parameters + + + + + + + + + + + + + + +
Type ParameterDefault type
+ +`TConfig` *extends* [`FlagType`](globals.md#flagtype)\[`"config"`\] + + + +[`EmptyFlagRemoteConfig`](globals.md#emptyflagremoteconfig) + +
+ +#### Properties + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyType
+ + `config` + + + +`Ref`\< \| [`EmptyFlagRemoteConfig`](globals.md#emptyflagremoteconfig) \| \{ `key`: `string`; \} & `TConfig`, \| [`EmptyFlagRemoteConfig`](globals.md#emptyflagremoteconfig) \| \{ `key`: `string`; \} & `TConfig`\> + +
+ + `isEnabled` + + + +`Ref`\<`boolean`, `boolean`\> + +
+ + `isLoading` + + + +`Ref`\<`boolean`, `boolean`\> + +
+ + `key` + + + +`string` + +
+ + `requestFeedback` + + + +(`opts`: [`RequestFlagFeedbackOptions`](globals.md#requestflagfeedbackoptions)) => `void` + +
+ +#### Methods + +### track() + +```ts +track(): + | undefined + | Promise< + | undefined +| Response> +``` + +###### Returns + + \| `undefined` + \| [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\< + \| `undefined` + \| [`Response`](https://developer.mozilla.org/docs/Web/API/Response)\> + +*** + +### Flags + +*** + +### UserContext + +Context is a set of key-value pairs. +This is used to determine if feature targeting matches and to track events. +Id should always be present so that it can be referenced to an existing user. + +#### Indexable + +```ts +[key: string]: ContextValue +``` + +#### Properties + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyTypeDescription
+ + `email?` + + + +`string` + + + +User email + +
+ + `id` + + + +`undefined` \| `string` \| `number` + + + +User id + +
+ + `name?` + + + +`string` + + + +User name + +
+ +## Type Aliases + +### BootstrappedFlags + +```ts +type BootstrappedFlags = BootstrappedState & { + flags: RawFlags; +}; +``` + +#### Type declaration + + + + + + + + + + + + + + +
NameType
+ +`flags` + + + +[`RawFlags`](../browser-sdk/globals.md#rawflags) + +
+ +*** + +### EmptyFlagRemoteConfig + +```ts +type EmptyFlagRemoteConfig = { + key: undefined; + payload: undefined; +}; +``` + +#### Type declaration + + + + + + + + + + + + + + + + + + +
NameType
+ + `key` + + + +`undefined` + +
+ + `payload` + + + +`undefined` + +
+ +*** + +### FlagKey + +```ts +type FlagKey = keyof TypedFlags; +``` + +*** + +### FlagType + +```ts +type FlagType = { + config: { + payload: any; + }; +}; +``` + +#### Type declaration + + + + + + + + + + + + + + + + + + +
NameType
+ + `config`? + + + +\{ + `payload`: `any`; + \} + +
+ +`config.payload` + + + +`any` + +
+ +*** + +### OptInFlag + +```ts +type OptInFlag = Omit & { + key: FlagKey; +}; +``` + +An opt-in-enabled flag for the generated Vue SDK flag definitions. + +Includes all fields from [BrowserOptInFlag](../browser-sdk/globals.md#optinflag): `name`, `description`, +`isEnabled`, `userOptedIn`, `companyOptedIn`, and `isOptedIn`. +Only `key` is narrowed to the generated [FlagKey](globals.md#flagkey) type. + +#### Type declaration + + + + + + + + + + + + + + +
NameType
+ +`key` + + + +[`FlagKey`](globals.md#flagkey) + +
+ +*** + +### ReflagBaseProps + +```ts +type ReflagBaseProps = { + debug: boolean; + initialLoading: boolean; + logger: Logger; +}; +``` + +**`Internal`** + +Base props for the ReflagProvider and ReflagBootstrappedProvider. + +#### Type declaration + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameTypeDescription
+ + `debug`? + + + +`boolean` + + + +Set to `true` to enable debug logging to the console. + +
+ + `initialLoading`? + + + +`boolean` + + + +Set to `true` to show the loading component while the client is initializing. + +
+ + `logger`? + + + +[`Logger`](../browser-sdk/globals.md#logger) + + + +A custom logger to use for SDK logs. +Use this for advanced control or filtering of SDK logs. +If both `logger` and `debug` are provided, `logger` takes precedence. + +
+ +*** + +### ReflagBootstrappedProps + +```ts +type ReflagBootstrappedProps = ReflagInitOptionsBase & ReflagBaseProps & { + flags: BootstrappedFlags; +}; +``` + +Props for the ReflagBootstrappedProvider. + +#### Type declaration + + + + + + + + + + + + + + + + +
NameTypeDescription
+ +`flags` + + + +[`BootstrappedFlags`](globals.md#bootstrappedflags) + + + +Pre-fetched flags used for the initial render. The browser client fetches opt-in +metadata on demand when opt-in flags are requested. + +
+ +*** + +### ReflagClientProviderProps + +```ts +type ReflagClientProviderProps = Omit & { + client: ReflagClient; +}; +``` + +Props for the ReflagClientProvider. + +#### Type declaration + + + + + + + + + + + + + + + + +
NameTypeDescription
+ +`client` + + + +[`ReflagClient`](../browser-sdk/globals.md#reflagclient) + + + +A pre-initialized ReflagClient to use. + +
+ +*** + +### ReflagInitOptionsBase + +```ts +type ReflagInitOptionsBase = Omit; +``` + +**`Internal`** + +Base init options for the ReflagProvider and ReflagBootstrappedProvider. + +*** + +### ReflagProps + +```ts +type ReflagProps = ReflagInitOptionsBase & ReflagBaseProps & { + company: CompanyContext; + context: ReflagContext; + otherContext: Record; + user: UserContext; +}; +``` + +Props for the ReflagProvider. + +#### Type declaration + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameTypeDescription
+ +`company`? + + + +[`CompanyContext`](globals.md#companycontext) + + + +Company related context. If you provide `id` Reflag will enrich the evaluation context with +company attributes on Reflag servers. + +**Deprecated** + +Use `context` instead, this property will be removed in the next major version + +
+ +`context`? + + + +[`ReflagContext`](../browser-sdk/globals.md#reflagcontext) + + + +The context to use for the ReflagClient containing user, company, and other context. + +
+ +`otherContext`? + + + +[`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, `string` \| `number` \| `undefined`\> + + + +Context which is not related to a user or a company. + +**Deprecated** + +Use `context` instead, this property will be removed in the next major version + +
+ +`user`? + + + +[`UserContext`](globals.md#usercontext) + + + +User related context. If you provide `id` Reflag will enrich the evaluation context with +user attributes on Reflag servers. + +**Deprecated** + +Use `context` instead, this property will be removed in the next major version + +
+ +*** + +### RequestFlagFeedbackOptions + +```ts +type RequestFlagFeedbackOptions = Omit; +``` + +*** + +### SetOptInOptions + +```ts +type SetOptInOptions = { + optedIn: boolean; + scope?: "user" | "company"; +}; +``` + +Options for changing the current user or company's opt-in membership. + +#### Type declaration + + + + + + + + + + + + + + + + + + + + + +
NameTypeDescription
+ + `optedIn` + + + +`boolean` + + + +Whether the scoped subject has opted in. + +
+ + `scope`? + + + +`"user"` \| `"company"` + + + +Whether to update the current user or current company. Defaults to `user`. + +
+ +*** + +### TrackEvent + +```ts +type TrackEvent = { + attributes: | Record + | null; + company: CompanyContext; + eventName: string; + user: UserContext; +}; +``` + +#### Type declaration + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameType
+ + `attributes`? + + + + \| [`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, `any`\> + \| `null` + +
+ + `company`? + + + +[`CompanyContext`](globals.md#companycontext) + +
+ + `eventName` + + + +`string` + +
+ + `user` + + + +[`UserContext`](globals.md#usercontext) + +
+ +*** + +### TypedFlags + +```ts +type TypedFlags = keyof Flags extends never ? Record : { [TypedFlagKey in keyof Flags]: Flags[TypedFlagKey] extends FlagType ? Flag : Flag }; +``` + +*** + +### UseOptInFlagsResult + +```ts +type UseOptInFlagsResult = { + flags: ComputedRef; + isLoading: ComputedRef; +}; +``` + +#### Type declaration + + + + + + + + + + + + + + + + + + +
NameType
+ + `flags` + + + +`ComputedRef`\<[`OptInFlag`](globals.md#optinflag)[]\> + +
+ + `isLoading` + + + +`ComputedRef`\<`boolean`\> + +
+ +## Variables + +### default + +```ts +default: { + install: void; +}; +``` + +#### Type declaration + + + + + + + + + + + + + + +
NameType
+ + `install()` + + + +`void` + +
+ +*** + +### ReflagBootstrappedProvider + +```ts +const ReflagBootstrappedProvider: DefineComponent, Record, unknown>; +``` + +## Functions + +### useClient() + +```ts +function useClient(): ReflagClient +``` + +Vue composable for getting the Reflag client. + +This composable returns the Reflag client. You can use this to get the Reflag +client at any point in your application. + +#### Returns + +[`ReflagClient`](../browser-sdk/globals.md#reflagclient) + +The Reflag client. + +#### Example + +```ts +import { useClient } from '@reflag/vue-sdk'; + +const client = useClient(); + +console.log(client.getContext()); +``` + +*** + +### useFlag() + +```ts +function useFlag(key: TKey): TypedFlags[TKey] +``` + +Vue composable for getting the state of a given flag for the current context. + +This composable returns an object with the state of the flag for the current context. + +#### Type Parameters + + + + + + + + + + + + +
Type Parameter
+ +`TKey` *extends* `string` + +
+ +#### Parameters + + + + + + + + + + + + + + + + +
ParameterTypeDescription
+ +`key` + + + +`TKey` + + + +The key of the flag to get the state of. + +
+ +#### Returns + +[`TypedFlags`](globals.md#typedflags)\[`TKey`\] + +An object with the state of the flag. + +#### Example + +```ts +import { useFlag } from '@reflag/vue-sdk'; + +const { isEnabled, config, track, requestFeedback } = useFlag("huddles"); + +function StartHuddlesButton() { + const { isEnabled, config: { payload }, track } = useFlag("huddles"); + if (isEnabled) { + return ; +} +``` + +*** + +### useIsLoading() + +```ts +function useIsLoading(): Ref +``` + +Vue composable for checking if the Reflag client is loading. + +This composable returns a boolean value that indicates whether the Reflag client is loading. +You can use this to check if the Reflag client is loading at any point in your application. +Initially, the value will be true until the client is initialized. + +#### Returns + +`Ref`\<`boolean`, `boolean`\> + +#### Example + +```ts +import { useIsLoading } from '@reflag/vue-sdk'; + +const isLoading = useIsLoading(); + +console.log(isLoading); +``` + +*** + +### useOnEvent() + +```ts +function useOnEvent( + event: THookType, + handler: (arg0: HookArgs[THookType]) => void, + client?: ReflagClient): void +``` + +Vue composable for listening to Reflag client events. + +#### Type Parameters + + + + + + + + + + + + +
Type Parameter
+ +`THookType` *extends* keyof [`HookArgs`](../browser-sdk/globals.md#hookargs) + +
+ +#### Parameters + + + + + + + + + + + + + + + + + + + + + + + + + + +
ParameterTypeDescription
+ +`event` + + + +`THookType` + + + +The event to listen to. + +
+ +`handler` + + + +(`arg0`: [`HookArgs`](../browser-sdk/globals.md#hookargs)\[`THookType`\]) => `void` + + + +The function to call when the event is triggered. + +
+ +`client`? + + + +[`ReflagClient`](../browser-sdk/globals.md#reflagclient) + + + +The Reflag client to listen to. If not provided, the client will be retrieved from the context. + +
+ +#### Returns + +`void` + +#### Example + +```ts +import { useOnEvent } from '@reflag/vue-sdk'; + +useOnEvent("flagsUpdated", () => { + console.log("flags updated"); +}); +``` + +*** + +### useOptInFlags() + +```ts +function useOptInFlags(): UseOptInFlagsResult +``` + +Vue composable for getting opt-in-enabled flags and their loading state for +the current context. + +The loading state is only used with `ReflagBootstrappedProvider` while +opt-in metadata is fetched on demand. Regular providers load opt-in metadata +with the initial flags; use [useIsLoading](globals.md#useisloading) for their loading state. + +If fetching opt-in metadata fails, loading ends without exposing an error. +Call `refresh()` on the client returned by [useClient](globals.md#useclient) to retry. + +#### Returns + +[`UseOptInFlagsResult`](globals.md#useoptinflagsresult) + +*** + +### useRequestFeedback() + +```ts +function useRequestFeedback(): (options: RequestFeedbackData) => void +``` + +Vue composable for requesting user feedback. + +This composable returns a function that can be used to trigger the feedback +collection flow with the Reflag SDK. You can use this to prompt users for +feedback at any point in your application. + +#### Returns + +`Function` + +A function that requests feedback from the user. The function accepts: + - `options`: An object containing feedback request options. + +### Parameters + + + + + + + + + + + + + + +
ParameterType
+ +`options` + + + +[`RequestFeedbackData`](../browser-sdk/globals.md#requestfeedbackdata) + +
+ +### Returns + +`void` + +#### Example + +```ts +import { useRequestFeedback } from '@reflag/vue-sdk'; + +const requestFeedback = useRequestFeedback(); + +// Request feedback from the user +requestFeedback({ + prompt: "How was your experience?", + metadata: { page: "dashboard" } +}); +``` + +*** + +### useSendFeedback() + +```ts +function useSendFeedback(): (opts: UnassignedFeedback) => Promise< + | undefined +| Response> +``` + +Vue composable for sending feedback. + +This composable returns a function that can be used to send feedback to the +Reflag SDK. You can use this to send feedback from your application. + +#### Returns + +`Function` + +A function that sends feedback to the Reflag SDK. The function accepts: + - `options`: An object containing feedback options. + +### Parameters + + + + + + + + + + + + + + +
ParameterType
+ +`opts` + + + +[`UnassignedFeedback`](../browser-sdk/globals.md#unassignedfeedback) + +
+ +### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\< + \| `undefined` + \| [`Response`](https://developer.mozilla.org/docs/Web/API/Response)\> + +#### Example + +```ts +import { useSendFeedback } from '@reflag/vue-sdk'; + +const sendFeedback = useSendFeedback(); + +// Send feedback from the user +sendFeedback({ + feedback: "I love this flag!", + metadata: { page: "dashboard" } +}); +``` + +*** + +### useSetOptIn() + +```ts +function useSetOptIn(): (key: string, options: SetOptInOptions) => Promise< + | undefined +| Response> +``` + +Vue composable for setting whether the current user or company has opted into a flag. + +Check the returned Response's `ok` property and catch promise rejections. +HTTP failures return a non-OK Response; offline mode, invalid arguments, or +missing scoped context return undefined. Confirmation failures can reject +after the membership changed remotely. See [ReflagClient.setOptIn](../browser-sdk/globals.md#setoptin). + +#### Returns + +`Function` + +### Parameters + + + + + + + + + + + + + + + + + + +
ParameterType
+ +`key` + + + +`string` + +
+ +`options` + + + +[`SetOptInOptions`](globals.md#setoptinoptions) + +
+ +### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\< + \| `undefined` + \| [`Response`](https://developer.mozilla.org/docs/Web/API/Response)\> + +*** + +### useTrack() + +```ts +function useTrack(): (eventName: string, attributes?: + | null + | Record) => Promise< + | undefined +| Response> +``` + +Vue composable for tracking custom events. + +This composable returns a function that can be used to track custom events +with the Reflag SDK. + +#### Returns + +`Function` + +A function that tracks an event. The function accepts: + - `eventName`: The name of the event to track. + - `attributes`: (Optional) Additional attributes to associate with the event. + +### Parameters + + + + + + + + + + + + + + + + + + +
ParameterType
+ +`eventName` + + + +`string` + +
+ +`attributes`? + + + + \| `null` \| [`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, `any`\> + +
+ +### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\< + \| `undefined` + \| [`Response`](https://developer.mozilla.org/docs/Web/API/Response)\> + +#### Example + +```ts +import { useTrack } from '@reflag/vue-sdk'; + +const track = useTrack(); + +// Track a custom event +track('button_clicked', { buttonName: 'Start Huddles' }); +``` + +*** + +### useUpdateCompany() + +```ts +function useUpdateCompany(): (opts: {}) => Promise +``` + +Vue composable for updating the company context. + +This composable returns a function that can be used to update the company +context with the Reflag SDK. You can use this to update the company context +at any point in your application. + +#### Returns + +`Function` + +A function that updates the company context. The function accepts: + - `opts`: An object containing the company context to update. + +### Parameters + + + + + + + + + + + + + + +
ParameterType
+ +`opts` + + + +\{\} + +
+ +### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> + +#### Example + +```ts +import { useUpdateCompany } from '@reflag/vue-sdk'; + +const updateCompany = useUpdateCompany(); + +// Update the company context +updateCompany({ id: "123", name: "Acme Inc." }); +``` + +*** + +### useUpdateOtherContext() + +```ts +function useUpdateOtherContext(): (opts: {}) => Promise +``` + +Vue composable for updating the other context. + +This composable returns a function that can be used to update the other +context with the Reflag SDK. You can use this to update the other context +at any point in your application. + +#### Returns + +`Function` + +A function that updates the other context. The function accepts: + - `opts`: An object containing the other context to update. + +### Parameters + + + + + + + + + + + + + + +
ParameterType
+ +`opts` + + + +\{\} + +
+ +### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> + +#### Example + +```ts +import { useUpdateOtherContext } from '@reflag/vue-sdk'; + +const updateOtherContext = useUpdateOtherContext(); + +// Update the other context +updateOtherContext({ id: "123", name: "Acme Inc." }); +``` + +*** + +### useUpdateUser() + +```ts +function useUpdateUser(): (opts: {}) => Promise +``` + +Vue composable for updating the user context. + +This composable returns a function that can be used to update the user context +with the Reflag SDK. You can use this to update the user context at any point +in your application. + +#### Returns + +`Function` + +A function that updates the user context. The function accepts: + - `opts`: An object containing the user context to update. + +### Parameters + + + + + + + + + + + + + + +
ParameterType
+ +`opts` + + + +\{\} + +
+ +### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> + +#### Example + +```ts +import { useUpdateUser } from '@reflag/vue-sdk'; + +const updateUser = useUpdateUser(); + +// Update the user context +updateUser({ id: "123", name: "John Doe" }); +``` + +## References + +### ReflagClientProvider + +Renames and re-exports [ReflagBootstrappedProvider](globals.md#reflagbootstrappedprovider) + +### ReflagProvider + +Renames and re-exports [ReflagBootstrappedProvider](globals.md#reflagbootstrappedprovider) diff --git a/product-handbook/anonymous-users.md b/product-handbook/anonymous-users.md index e09532f..52af8c7 100644 --- a/product-handbook/anonymous-users.md +++ b/product-handbook/anonymous-users.md @@ -1,80 +1,85 @@ --- -description: How to use Reflag with anonymous users +description: Use Reflag with anonymous users and optional company context. --- # Anonymous users -Reflag is designed for SaaS applications in which users are authenticated and belong to a company group. However, you can still use Reflag for certain use cases where users aren't authenticated. +Reflag supports contexts without a user, including public pages and company-branded applications. Omit unknown identities rather than supplying empty-string IDs. Rules that require an omitted identity or attribute cannot match it. -Example use cases: +## How to toggle features for anonymous users -* Toggle features on/off for all anonymous users on marketing pages or docs. -* For anonymous users that belong to companies, for example for a white-label solution for ordering food online: roll out features to anonymous users belonging to certain restaurants or roll it users belonging to a percentage of restaurants (companies). - -### How to toggle features for anonymnous users - -First, create a new flag, use it on the respective feature and ship it. - -On the Access tab, you can now use "No-one" or "Everyone" to toggle the feature off and on. "Some" is not supported for anonymous users. - -For anonymous users you supply an empty user ID and empty company ID. +For a global Boolean flag, use Everyone/No-one access and an empty context. Initialize the Node client before reading: {% tabs %} {% tab title="Node.js" %} ```typescript import { ReflagClient } from "@reflag/node-sdk"; -const client = new ReflagClient(...) -// using an empty context for anonymous users -const { isEnabled } = client.bindClient({}).getFlag("export-to-csv") +const client = new ReflagClient({ secretKey: process.env.REFLAG_SECRET_KEY ?? "" }); +await client.initialize(); +const enabled = client.getFlag({}, "export-to-csv"); +console.log(enabled); ``` {% endtab %} - {% tab title="React" %} ```tsx -import { ReflagProvider } from "@reflag/react-sdk"; +import { ReflagProvider, useFlag } from "@reflag/react-sdk"; + +function ExportButton() { + const enabled = useFlag("export-to-csv"); + return enabled ? : null; +} -function App() { +export function App() { return ( - // no user/company provided - + + ); } - ``` {% endtab %} {% endtabs %} -### How to toggle features for anonymous users where you know their company +Without a default, `getFlag()` and `useFlag()` return a Boolean. Pass a default to read a Multivariate flag's value. + +## How to toggle features for anonymous users where you know their company -If the user is anonymous but you do know the company entity, you can simply supply the given company ID and an empty user ID. This lets you control features for anonymous users beloning to the given company. +Provide only the company when your application has a trustworthy company identity. Company targeting can then apply without inventing a user. {% tabs %} {% tab title="Node.js" %} ```typescript import { ReflagClient } from "@reflag/node-sdk"; -const client = new ReflagClient(...) - -// supply only the company ID if the users is anonymous but belongs to a company -const { isEnabled } = client.bindClient({company: {id: "petes-burgers"}).getFlag("export-to-csv") +const client = new ReflagClient({ secretKey: process.env.REFLAG_SECRET_KEY ?? "" }); +await client.initialize(); +const companyClient = client.bindClient({ company: { id: "petes-burgers" } }); +const enabled = companyClient.getFlag("export-to-csv"); +console.log(enabled); ``` {% endtab %} - {% tab title="React" %} ```tsx -import { ReflagProvider } from "@reflag/react-sdk"; +import { ReflagProvider, useFlag } from "@reflag/react-sdk"; -function App() { +function ExportButton() { + const enabled = useFlag("export-to-csv"); + return enabled ? : null; +} + +export function App() { return ( - // company provided - + + ); } - ``` {% endtab %} {% endtabs %} +Anyone can change the company ID their browser sends, so check access to sensitive features on your server too. See the [Node.js SDK](../supported-languages/node-sdk/README.md) and [React SDK](../supported-languages/react-sdk/README.md) for complete setup. diff --git a/product-handbook/feature-clean-up-and-archival-beta/ai-code-clean-up-beta.md b/product-handbook/feature-clean-up-and-archival-beta/ai-code-clean-up-beta.md index cf56199..942a84d 100644 --- a/product-handbook/feature-clean-up-and-archival-beta/ai-code-clean-up-beta.md +++ b/product-handbook/feature-clean-up-and-archival-beta/ai-code-clean-up-beta.md @@ -3,11 +3,11 @@ When the [GitHub integration](../../integrations/github.md) is enabled, Reflag can automatically clean up your code after flags turn stale. The Reflag bot submits a pull request to your GitHub repository that removes flag code once a flag turns stale. {% hint style="warning" %} -This automation **keeps the codepath that grants access (`isEnabled == true`)** when cleaning up and archiving a flag. In practice, it releases the flag to everyone by removing the flagging code. +This automation **keeps the codepath that grants access (the Boolean flag value is `true`)** when cleaning up and archiving a flag. In practice, it releases the flag to everyone by removing the flagging code. {% endhint %} {% hint style="info" %} -Note: This works best when using the [React SDK](../../supported-languages/browser-sdk/), but stay tuned for improved Node.js support +Note: This works best when using the [React SDK](../../supported-languages/react-sdk/README.md), but stay tuned for improved Node.js support {% endhint %}
@@ -101,25 +101,31 @@ When the AI clean-up bot runs, it searches for usage of the Reflag SDK in your c For React, this usually corresponds to the `useFlag` hook, like in this contrived example: -```javascript +```tsx +import { useFlag, useTrack } from "@reflag/react-sdk"; + function StartHuddleButton() { - const { isEnabled } = useFlag("huddle"); - if (!isEnabled) { + const enabled = useFlag("huddle"); + const track = useTrack(); + if (!enabled) { return null; } - return ; + return ; } ``` -When the bot cleans up the file, it removes the hook and only retains the `isEnabled` codepath: +When the bot cleans up the file, it removes the hook and only retains the enabled codepath: + +```tsx +import { useTrack } from "@reflag/react-sdk"; -```javascript function StartHuddleButton() { - return ; + const track = useTrack(); + return ; } ``` **Limitations**: -* Only `isEnabled` is removed, whereas `track`, `config`, and `requestFeedback` are untouched. +* Review the generated PR carefully. The cleanup removes the flag check only; keep any usage tracking, feedback or configuration you still need. For Multivariate flags, decide yourself which value to keep. * Works best with the React SDK while in beta. diff --git a/product-handbook/feature-entitlements/README.md b/product-handbook/feature-entitlements/README.md index 81e5295..b5de507 100644 --- a/product-handbook/feature-entitlements/README.md +++ b/product-handbook/feature-entitlements/README.md @@ -24,24 +24,25 @@ Reflag is purpose-built for B2B, with native support for gating flags at the com ### Step 1: Initialize Reflag -Choose [an SDK](https://app.gitbook.com/s/pgXAy2Cgsm5pON9oJ06m/supported-languages) to get started, if you haven't already.\ +Choose [an SDK](../../supported-languages/overview.md) to get started, if you haven't already.\ \ Reflag needs to know who the authenticated user is and which company they belong to. We attach attribute metadata such as the company's subscription plan. ```tsx -// identify user -reflag.user(userId1356, { - name: “Rasmus Makwarth”, -}); - -// associate user with company -reflag.company(companyId51, { - name: “Acme Inc.”, - plan: “business”, -}); +import { ReflagProvider } from "@reflag/react-sdk"; + + + {/* your application */} +; ``` -Reflag now understands that Rasmus works for Acme Inc. and Acme Inc. is on the Business subscription plan. +Reflag can now target the company's Business subscription plan. Users can change what their browser sends, so also check sensitive entitlements on your server, using the plan from your own billing data. {% hint style="info" %} You can send company attributes as part of the user sign-in event, via a nightly job, or use `updateCompany()` when the attribute value changes. @@ -74,12 +75,12 @@ Each flag comes with a [flag key](../concepts/feature.md#flag-key), such as `exp In React, it’d look like this: ```tsx -const { isEnabled } = useFlag("export-to-csv"); - -if(isEnabled) { - - // access to csv export! +import { useFlag } from "@reflag/react-sdk"; +function ExportButton() { + const enabled = useFlag("export-to-csv"); + if (!enabled) return null; + return ; } ``` @@ -119,10 +120,9 @@ Send usage metrics to Reflag using company attributes. For example, you can send the company's current usage metrics to Reflag at an hourly or daily interval. -```tsx -reflag.companyUpdate(companyId51, { - apiRequestsCurrentMonth: 793 -}); +```ts +// On an initialized Browser SDK client: +await reflag.updateCompany({ apiRequestsCurrentMonth: 793 }); ``` ### Step 2: Gate using usage attribute diff --git a/product-handbook/feature-entitlements/simple-role-based-entitlements.md b/product-handbook/feature-entitlements/simple-role-based-entitlements.md index 9ab45ed..bb7f35d 100644 --- a/product-handbook/feature-entitlements/simple-role-based-entitlements.md +++ b/product-handbook/feature-entitlements/simple-role-based-entitlements.md @@ -20,7 +20,7 @@ If you zoom out, this is what controlling feature access at the customer subscri
-To add simple user role controls to the mix, you can choose to hard code the user role check within the `isEnabled` check. +To add simple user role controls to the mix, you can choose to hard code the user role check alongside the Boolean value returned by `useFlag()` or `getFlag()`.
diff --git a/product-handbook/launch-monitor/README.md b/product-handbook/launch-monitor/README.md index d7793ac..f37aa02 100644 --- a/product-handbook/launch-monitor/README.md +++ b/product-handbook/launch-monitor/README.md @@ -12,24 +12,21 @@ The Exposed chart shows the distinct count of companies that have been exposed t The Tracked chart shows the distinct count of companies that have interacted with the flagged workflow. Interactions are tracked with the `track` method. -```typescript -import { useFlag } from "@reflag/react-sdk"; +```tsx +import { useFlag, useTrack } from "@reflag/react-sdk"; function StartHuddleButton() { - const { isLoading, isEnabled, track } = useFlag("huddle"); - - if (isLoading) { - return ; - } + const enabled = useFlag("huddle"); + const track = useTrack(); - if (!isEnabled) { + if (!enabled) { return null; } return (
Huddles - +
); } @@ -41,19 +38,18 @@ You can collect end-user feedback on new flag rollouts to catch and fix issues f ### Static feedback button -Here's a brief example using the [Reflag React SDK](../../supported-languages/browser-sdk/) to collect feedback: +Configure the flag's adoption rules to match the event name you track. Reading a flag records a check automatically; call `track()` when someone actually uses the feature. + +Here's a brief example using the [Reflag React SDK](../../supported-languages/react-sdk/README.md) to collect feedback: ```tsx -import { useFlag } from "@reflag/react-sdk"; +import { useFlag, useRequestFeedback } from "@reflag/react-sdk"; function StartHuddleButton() { - const { isLoading, isEnabled, requestFeedback } = useFlag("my-flag"); - - if (isLoading) { - return ; - } + const enabled = useFlag("my-flag"); + const requestFeedback = useRequestFeedback(); - if (!isEnabled) { + if (!enabled) { return null; } @@ -61,7 +57,7 @@ function StartHuddleButton() { <> diff --git a/product-handbook/launch-monitor/give-feedback-button.md b/product-handbook/launch-monitor/give-feedback-button.md index 79373fa..53298d7 100644 --- a/product-handbook/launch-monitor/give-feedback-button.md +++ b/product-handbook/launch-monitor/give-feedback-button.md @@ -1,36 +1,33 @@ --- -description: Adding a feedback button using Reflag SDKs in a few lines of code. +description: Add a feedback button with the React SDK feedback hook. --- # Give feedback button -Collecting feedback through a "Give feedback" button is a great way to collect feedback from users. - -Here's a brief example using the [Reflag React SDK](../../supported-languages/browser-sdk/): +Use the `useRequestFeedback()` hook to open a feedback form from your own button: ```tsx -import { useFlag } from "@reflag/react-sdk"; - -function StartHuddleButton() { - const { isLoading, isEnabled, track, requestFeedback } = useFlag("huddle"); +import { useFlag, useRequestFeedback, useTrack } from "@reflag/react-sdk"; - if (isLoading) { - return ; - } +export function StartHuddleButton() { + const enabled = useFlag("huddle"); + const track = useTrack(); + const requestFeedback = useRequestFeedback(); - if (!isEnabled) { - return null; - } + if (!enabled) return null; return ( <> - - + ); } ``` + +Render this component inside a [React SDK provider](../../supported-languages/react-sdk/README.md) with the appropriate user/company context. Configure adoption rules to match the event you track. For widget positioning, translations, styling, or your own UI, see [Browser feedback](../../supported-languages/browser-sdk/feedback.md). diff --git a/product-handbook/multivariate-flags.md b/product-handbook/multivariate-flags.md new file mode 100644 index 0000000..3222b50 --- /dev/null +++ b/product-handbook/multivariate-flags.md @@ -0,0 +1,117 @@ +--- +description: Serve different configuration values to different users and companies. +--- + +# Multivariate flags + +## What are Multivariate flags? + +A **Multivariate flag** lets you serve different configuration values to different users or companies. Each variant has a name and a JSON value. Your application reads the value of the selected variant. + +A variant's value can be text, a number, an object, an array, a Boolean, or `null`. + +For example, configure `assistant-settings` with variants containing different model settings, then read it with the React SDK: + +```tsx +import { useFlag } from "@reflag/react-sdk"; + +export function AssistantSettings() { + const settings = useFlag("assistant-settings", { + model: "quick", + maxTokens: 512, + includeCitations: false, + }); + + return ( +

+ Model: {settings.model}; token limit: {settings.maxTokens}; citations:{" "} + {settings.includeCitations ? "on" : "off"} +

+ ); +} +``` + +The second argument supplies a default while flags load or if the flag is unavailable. In this example, the default is the `quick` model with a 512-token limit and citations turned off. Pass a default when reading a Multivariate flag; without one, `useFlag()` expects a Boolean value. + +## Variants and values + +For each environment, configure: + +- **Variants:** the named values your application can receive. +- **Specific targets:** users or companies that should receive a particular variant. +- **Rules:** conditions for choosing a variant, or splitting traffic between variants by percentage. +- **Default variant:** the variant to use when no assignment or rule selects one. + +Configure each environment separately. Changing a variant or rule in one environment doesn't update the others. + +The **default variant** is a choice you make in Reflag. The **SDK default** is the fallback value you pass in code, used while flags load or when a value can't be read. + +{% hint style="danger" %} +Don't put API keys, passwords, or other secrets in flag values. Values sent to a browser are visible to its users. Store secrets in a secret manager instead. +{% endhint %} + +## How a variant is chosen + +Reflag chooses a variant in this order: + +1. An assignment for the specific user. +2. An assignment for the user's company. +3. Targeting rules, from top to bottom. +4. The default variant, if nothing else selects a variant. + +Rules can match user or company attributes, segments, and other context. They can also split traffic between variants by percentage. + +## Usage scenarios + +### Start simple + +Start with one variant and make it the default. Add more variants and targeting rules when different audiences need different settings. + +For structured settings, use consistent fields across variants. [Type safety](type-safety.md) adds autocomplete and type checks in your editor. + +### Model selection + +For a simple model selector, use strings as the variant values, such as `"quick"` and `"reasoner"`: + +```tsx +import { useFlag } from "@reflag/react-sdk"; + +export function AssistantModel() { + const model = useFlag("assistant-model", "quick"); + return

Selected model: {model}

; +} +``` + +### Entitlements + +Use Multivariate flags for plan-specific settings, such as usage limits or available models. Target a company's plan to choose the settings for each subscription tier. See [Feature entitlements](feature-entitlements/README.md) for examples. + +If access and configuration are separate decisions, use a Boolean flag such as `assistant-enabled` for the on/off switch and a Multivariate flag for the settings. + +## Start using Multivariate flags + +1. Create a **Multivariate** flag. +2. Open its **Variants** tab and configure variants, specific targets, rules, and the default for the selected environment. +3. Save, then configure and verify any other environments separately. +4. Read the value with a [Reflag SDK](../supported-languages/overview.md), passing a default. + +## Migrating from Remote config + +Legacy Remote config and Multivariate flags are separate features. Existing remote configs aren't converted automatically. + +### Using an AI agent + +An agent connected to [Reflag MCP](../api/mcp.md) can read your existing Remote configs and help migrate them to Multivariate flags. + +Start by asking for a migration plan, rather than an immediate bulk migration: + +> Review this app's legacy Remote configs through Reflag MCP. Before recommending migration, check the codebase and any available usage data to identify which configs are still used. Propose migration to Multivariate flags only for configs in use, and flag uncertain cases for confirmation. Preserve values, defaults, and targeting in each environment, and keep existing Boolean access checks. Identify any clients still using SDK v1. Show the proposed flag keys and code changes. Ask for my approval before creating flags or changing configuration. Don't remove the old configs. + +### Manual migration + +1. **Review the existing config.** Record its keys and JSON payloads, along with the assignments, rules, and default in each environment. Check whether your application reads `config.payload`, `config.key`, or both. +2. **Create a Multivariate flag with a new key**, such as `assistant-settings`. Keep the original Release flag and its access rules in place while you migrate. +3. **Copy the values your application uses.** If it reads `config.payload`, use that JSON as the variant value. If it reads `config.key`, use the old key as a string value. If it needs both, include both in an object and update your code to read that object. +4. **Recreate targeting in each environment.** Copy user/company assignments, rules, and the default. Preserve the original evaluation order when rules overlap. Unlike legacy Remote config, Multivariate variants and values are configured separately in each environment. +5. **Update and test your application.** [Upgrade to SDK v2](../supported-languages/migrating-from-v1.md) and read the new flag's value directly, rather than through `.config`. Keep any existing Boolean access checks. Compare the old and new results for representative users and companies in each environment. +6. **Retire the old config once clients no longer use it.** Leave it available for any clients still on SDK v1. Don't delete a Release flag that's still used for access checks. diff --git a/product-handbook/remote-config.md b/product-handbook/remote-config.md index bcc3c28..0e7558c 100644 --- a/product-handbook/remote-config.md +++ b/product-handbook/remote-config.md @@ -1,106 +1,3 @@ ---- -description: Learn more about remote config in Reflag ---- - # Remote config -## What is remote config? - -Remote config is a dynamic way to configure flags for different audiences. A flag's remote config consists of a set of **config values**. Each config value is a **key** — **payload** pair where the key is unique and the value is any valid JSON value. Both are supplied by you. - -Config values have **environment-specific targeting rules** used by Reflag to match them against your users and companies. - -Remote config reduces the need for code changes. It lets you test and adjust flag behavior without redeploying your application. - -This is what remote config looks like in React: - -{% code fullWidth="false" %} -```tsx -function AISummarizerRemotelyConfigured({copy}: {copy: string}) { - const { config: { payload } } = useFlag('my-ai-flag'); - - return -} -``` -{% endcode %} - -{% hint style="info" %} -Remote config works independently from [access rules](feature-rollouts/feature-targeting-rules.md). In other words, remote config is not affected by whether the user has access to the flag. -{% endhint %} - -## Config values - -Config values consist of: - -* A mandatory unique string **key**, supplied by you. The key is unique per flag. If you just need a string configuration, you can use the key by itself. -* An optional JSON **payload**, that can be any valid JSON value: `null`, `string`, `number`, `array` or `object` -* Targeting rules which are environment-specific, allowing you to target different config values to different users/companies in different environments -* Default setting, which tells Reflag which config value to use as fallback if no targeting set matches the given user/company context - -{% hint style="danger" %} -Do not store sensitive data in the key or the payload of the config value even if the flag is marked as **secret.** - -Sensitive data, like API keys or passwords should be managed with proper care outside of Reflag -{% endhint %} - -The config values are shared across all environments. Any new value that you add in one environment is automatically added to other environments, but without targeting rules, making it disabled there by default. - -

Remote config with three values in the Production environment

- -In the image above, a flag is set up with three config values. This example configures LLM settings for an AI workflow. The `gpt-4o` value is the default and is served with requests that do not match a more specific rule. The `claude-3-7-sonnet` value is served to users in `Apex` and `Blaze`. The `gpt-5` value is served to `Adrian Borer` and the `Logix` and `Hightrix` companies. - -{% hint style="info" %} -We recommend that you choose simple text values for config value keys. Avoid spaces and special characters unless you plan to use the key as display text in your application. -{% endhint %} - -## Matching algorithm - -* Users, companies and segments can appear only once in the targeting rules for each environment. This means that you cannot configure two distinct config values in the same environment to target the same entity explicitly -* Matches are not evaluated in the order of their appearance, but in order of their **specificity**: - * Directly specified users match first - * Then, directly specified companies match - * Then, going top to bottom in order of appearance of the config values, segments specified are matched against the company - * Finally, if no rule is matched, the default one is used -* **`Other context`** is not taken into account when evaluating config value targeting rules -* _Percentage rollout_ is not supported for remote config - -## Usage scenarios - -In addition to the AI model configuration example above, this section shows some other scenarios that can be solved by using remote config. - -### Basic flag configuration - -Sometimes it is useful to store flag-specific config that your application can use. This is true even if you do not plan to target different config values to different users. You can create a single config value, set it as **default**, and store any JSON payload in it. In that case, the key can be any value you choose. - -On the application side, you can check if the user has access to the flag, and use the accompanying config when needed. - -{% hint style="info" %} -Since config values are evaluated independently from access, your application can still use remote config even if the flag is disabled for the user. For example, the payload can explain why the flag is unavailable or offer an alternative path. -{% endhint %} - -### Multivariate flags - -The **multivariate flag** is a classic remote config use case. To create one: - -1. Create a flag and define its access rules, if any. -2. Create the "_variants_" by using config values. Each config value has its key representing the variant name. -3. Adjust the targeting rules on each config value. -4. Payloads can be be ignored if additional configuration is not required for each variant. - -### Entitlements - -Remote config is a strong fit for [entitlements scenarios](feature-entitlements/). For each flag you create, you can add config values that target different **companies** or **company segments**. Each config value can then define a different access tier or usage limit. - -

Example of AI model variations by subscription tier

- -The image above shows a flag called "_AI Transcripts_" that serves four customer categories: "_Not customers_", "_Beta_", "_Business Plan_", and "_Enterprise Plan_". Each category receives a different tier. - -## Start using remote config - -First, [create your first flag](https://app.reflag.com/env-current/flags/new), if you have not already. Then open your flag and click the "_Remote config_" tab. - -

Click "Create config value" to start

- -Once you have set up your flag and config values, configure the targeting rules in your other environments as well. - -Finally, use [any of our SDKs](../supported-languages/overview.md) to access the flag and its config in your application. +Use a [Multivariate flag](multivariate-flags.md) for remote configuration. Define your configuration values as variants, then use targeting rules to choose which value each user or company receives. diff --git a/product-handbook/service-resiliency.md b/product-handbook/service-resiliency.md index 821c2e2..4d55a4d 100644 --- a/product-handbook/service-resiliency.md +++ b/product-handbook/service-resiliency.md @@ -57,9 +57,9 @@ flowchart LR ## Recommended production setup -1. Evaluate flags on the server with a local-evaluation SDK, such as the [Node.js SDK](../supported-languages/node-sdk/) or [OpenFeature Node.js provider](../supported-languages/openfeature.md). -2. Configure a [`flagsFallbackProvider`](../supported-languages/node-sdk/#fallback-provider) so fresh server processes can initialize from saved flag definitions when Reflag cannot be reached. -3. Use [`getFlagsForBootstrap()`](../supported-languages/node-sdk/#bootstrapping-client-side-applications) on the server and a bootstrapped client provider in React, React Native, Vue, or the Browser SDK. +1. Evaluate flags on the server with the [Node.js SDK](../supported-languages/node-sdk/README.md). +2. Configure a [`flagsFallbackProvider`](../supported-languages/node-sdk/README.md#fallback-providers) so fresh server processes can initialize from saved flag definitions when Reflag cannot be reached. +3. Use [`getFlagsForBootstrap()`](../supported-languages/node-sdk/README.md#bootstrap-the-browser) on the server and a bootstrapped client provider in React, Vue, or the Browser SDK. 4. If your client SDK supports caching, tune it based on how long your app can tolerate stale flags. 5. Test the disruption path in staging: block access to Reflag, start a fresh server process, and confirm it initializes from fallback storage and the client renders from bootstrapped flags. @@ -90,18 +90,19 @@ Use the file provider for single-server deployments only when the disk persists Choose fallback storage based on where your application runs. The storage should be reachable whenever your application is reachable, so prefer storage in the same cloud provider, region, or network as the application deployment that will use it. If an outage affects Reflag's infrastructure but your application is still running elsewhere, your application can still load the saved snapshot. If the same provider or region outage also takes down your application, fallback storage cannot help until your application environment is available again. -For all built-in providers and custom provider examples, see the [fallback provider docs](../supported-languages/node-sdk/#fallback-provider). +See the [fallback provider docs](../supported-languages/node-sdk/README.md#fallback-providers) for the built-in storage options. ## Bootstrapped flags Bootstrapping lets your server evaluate flags and pass the server-evaluated state to your client-side application. The client can render immediately from that state instead of depending on an initial request to Reflag. -Use [`getFlagsForBootstrap()`](../supported-languages/node-sdk/#bootstrapping-client-side-applications) in the Node.js SDK together with the bootstrapping APIs in your client SDK: +Use [`getFlagsForBootstrap()`](../supported-languages/node-sdk/README.md#bootstrap-the-browser) in the Node.js SDK together with your client SDK's bootstrapping API: -* [React SDK](../supported-languages/react-sdk/#server-side-rendering-and-bootstrapping): `ReflagBootstrappedProvider` -* [React Native SDK](../supported-languages/react-native-sdk/#bootstrapping): `ReflagBootstrappedProvider` -* [Vue SDK](../supported-languages/vue-sdk/#reflagbootstrappedprovider-component): `ReflagBootstrappedProvider` -* [Browser SDK](../supported-languages/browser-sdk/#using-bootstrappedstate): `bootstrappedState` +* [React SDK](../supported-languages/react-sdk/README.md#bootstrap-from-the-server): `ReflagBootstrappedProvider` +* [Vue SDK](../supported-languages/vue-sdk/README.md#bootstrap-from-the-server): `ReflagBootstrappedProvider` +* [Browser SDK](../supported-languages/browser-sdk/README.md#bootstrap-from-the-server): `bootstrappedState` + +Pass the whole object returned by `getFlagsForBootstrap()`. React Native and OpenFeature have their own compatibility requirements; follow their SDK documentation. Bootstrapping is the recommended client setup for high-availability applications because the first render depends on your application server response, not on the client's ability to reach Reflag. Combined with server-side local evaluation and `flagsFallbackProvider`, it lets end users continue receiving evaluated flags during a Reflag service disruption. diff --git a/product-handbook/type-safety.md b/product-handbook/type-safety.md index be54a80..bbfcf70 100644 --- a/product-handbook/type-safety.md +++ b/product-handbook/type-safety.md @@ -1,54 +1,88 @@ --- -description: Reflag offers type safety which reduces errors and frustation +description: Register flag keys and schemas with the Reflag SDKs and CLI. --- # Type safety -{% embed url="https://www.youtube.com/watch?v=2ay2sc9g6Oc" %} +The Reflag SDKs infer a flag's type from the default you pass, so you get useful types without any setup. Registering your flags also catches misspelled keys and defaults that don't match your flag's values. -Type safety in Reflag ensures that flag key typos become build errors. This guarantees that if you try to use a non-existent flag key, you'll receive a type error, preventing potential runtime errors and improving code reliability. For remote config, it also ensures that the shape of the payload defined on Reflag matches what your code expects. +```tsx +import { useFlag } from "@reflag/react-sdk"; -Use the Reflag CLI to generate flag types from their definition in Reflag. Once flag types have been generated they are automatically picked up by TypeScript. +export function TokenLimit() { + const settings = useFlag("assistant-settings", { maxTokens: 512 }); + return {settings.maxTokens}; +} +``` -It's recommended that you do not check in the flag types, but instead generate them in your build process and on your local development machines. +Here the default `512` gives `maxTokens` the type `number`. Without a default, you get a Boolean; with `null`, you get any JSON value. ## Set up type safety for flags -1. Install the Reflag CLI and set up your repository +Install the Reflag CLI and generate declarations for your flags: - ``` - npm install --save-dev @reflag/cli - npx reflag init - ``` -2. Generate the types locally +```sh +npm install --save-dev @reflag/cli +npx reflag init +npx reflag flags types +``` - ``` - npx reflag types generate - ``` -3. Add the generated files to `.gitignore` +`reflag init` asks which SDK you use. To choose the format explicitly: - ``` - echo "gen/flags.d.ts" >> .gitignore - ``` -4. Retrieve an [API Key](http://app.reflag.com/env-current/settings/org-api-access) for your build system -5. Set up your build system to run the Reflag CLI to generate types (use the `--api-key` option or specify the API key in the `REFLAG_API_KEY` environment variable) +```sh +npx reflag flags types --format react --out gen/flags.d.ts +npx reflag flags types --format node --out gen/flags.d.ts +``` - ``` - npx reflag apps list --api-key $REFLAG_API_KEY - ``` +Make sure TypeScript includes the output file. -Example CI workflow: +Types are generated from the variant values in your production environment. Regenerate them when your flags change, and let generation errors fail your build so the types don't silently go stale. -```yaml -# GitHub Actions example -- name: Generate types - run: npx reflag flags types --api-key ${{ secrets.REFLAG_API_KEY }} +You can commit the generated file, or ignore it and generate it on local setup and in CI. If you ignore it: + +```sh +echo "gen/flags.d.ts" >> .gitignore +``` + +## Check defaults against your flags + +A React registration looks like this (the CLI writes the appropriate augmentation for you): + +```tsx +import { useFlag } from "@reflag/react-sdk"; -# GitHub Actions example (using environment): -- name: Generate types (environment) +declare module "@reflag/react-sdk" { + interface Flags { + "assistant-settings": { maxTokens: number; model: "quick" | "reasoner" }; + } +} + +export function RegisteredSettings() { + const settings = useFlag("assistant-settings", { + maxTokens: 512, + model: "quick", + }); + return ( + + {settings.model}: {settings.maxTokens} + + ); +} +``` + +With a registered flag, TypeScript checks that the default you pass matches the flag's type, including nested fields. + +These checks happen at compile time only. See your SDK's guide for what it checks at runtime. + +## Using in CI/CD pipelines + +Store a [Management API key](../api/api-access.md) as a secret in your CI system. + +```yaml +- name: Generate flag types run: npx reflag flags types env: REFLAG_API_KEY: ${{ secrets.REFLAG_CI_API_KEY }} ``` -There's further guidance and examples of using [Reflag CLI in CI/CD pipelines](https://docs.reflag.com/api/cli#using-in-ci-cd-pipelines-beta). +Install your project's dependencies before this step, so it uses the CLI version from your lockfile. diff --git a/sdk/@reflag/browser-sdk/README.md b/sdk/@reflag/browser-sdk/README.md index d1b8990..bb7dbdd 100644 --- a/sdk/@reflag/browser-sdk/README.md +++ b/sdk/@reflag/browser-sdk/README.md @@ -13,597 +13,183 @@ pagination: visible: true --- -# Reflag Browser SDK +# Reflag Browser SDK -Basic client for [Reflag.com](https://reflag.com). If you're using React, you'll be better off with the Reflag React SDK. +Feature flags, remote configuration, usage tracking and feedback for browser applications. -Reflag supports flag toggling, tracking flag usage, [collecting feedback](#qualitative-feedback-on-beta-flags) on flags, and [remotely configuring flags](#remote-config). +This page covers SDK v2. -## Install +## Get started -First find your `publishableKey` under [environment settings](https://app.reflag.com/env-current/settings/app-environments) in Reflag. +### 1. Create a client -The package can be imported or used directly in a HTML script tag: +Install the SDK: -A. Import module: - -```typescript -import { ReflagClient } from "@reflag/browser-sdk"; - -const user = { - id: 42, - role: "manager", -}; - -const company = { - id: 99, - plan: "enterprise", -}; - -const reflagClient = new ReflagClient({ publishableKey, user, company }); - -await reflagClient.initialize(); - -const { - isEnabled, - config: { payload: question }, - track, - requestFeedback, -} = reflagClient.getFlag("huddle"); - -if (isEnabled) { - // Show flag. When retrieving `isEnabled` the client automatically - // sends a "check" event for the "huddle" flag which is shown in the - // Reflag UI. - - // On usage, call `track` to let Reflag know that a user interacted with the flag - track(); - - // The `payload` is a user-supplied JSON in Reflag that is dynamically picked - // out depending on the user/company. - const question = payload?.question ?? "Tell us what you think of Huddles"; - - // Use `requestFeedback` to create "Send feedback" buttons easily for specific - // flags. This is not related to `track` and you can call them individually. - requestFeedback({ title: question }); -} - -// `track` just calls `reflagClient.track()` to send an event using the same flag key -// You can also use `track` on the client directly to send any custom event. -reflagClient.track("huddle"); - -// similarly, `requestFeedback` just calls `reflagClient.requestFeedback({flagKey: })` -// which you can also call directly: -reflagClient.requestFeedback({ flagKey: "huddle" }); -``` - -B. Script tag (client-side directly in html) - -See [example/browser.html](https://github.com/reflagcom/javascript/tree/main/packages/browser-sdk/example/browser.html) for a working example: - -```html - - -Loading... - +```sh +npm install @reflag/browser-sdk ``` -### Init options - -Supply these to the constructor call: - -```typescript -type Configuration = { - logger: console; // by default only logs warn/error, by passing `console` you'll log everything - apiBaseUrl?: "https://front.reflag.com"; - credentials?: "include" | "same-origin" | "omit"; // forwarded to fetch requests; "include" also enables credentials for the default EventSource transport - feedback?: undefined; // See FEEDBACK.md - enableTracking?: true; // set to `false` to stop sending track events and user/company updates to Reflag servers. Useful when you're impersonating a user - enableLiveFlagUpdates?: false; // Set to `true` to keep flags up to date over SSE (browser SDK default: false) - eventSourceFactory?: (url: string) => { - // Advanced: provide a custom EventSource-compatible transport - addEventListener: (type: string, cb: (event: any) => void) => void; - close: () => void; - }; - fallbackFlags?: - | string[] - | Record; // Enable these flags if unable to contact reflag.com. Can be a list of flag keys or a record with configuration values - timeoutMs?: number; // Timeout for fetching flags (default: 5000ms) - staleWhileRevalidate?: boolean; // Revalidate in the background when cached flags turn stale to avoid latency in the UI (default: false) - staleTimeMs?: number; // at initialization time flags are loaded from the cache unless they have gone stale. Defaults to 0 which means the cache is disabled. Increase this in the case of a non-SPA - expireTimeMs?: number; // In case we're unable to fetch flags from Reflag, cached/stale flags will be used instead until they expire after `expireTimeMs`. Default is 30 days - offline?: boolean; // Use the SDK in offline mode. Offline mode is useful during testing and local development -}; -``` - -## Migrating from Bucket SDK - -If you have been using the Bucket SDKs, the following list will help you migrate to Reflag SDK: - -- `Bucket*` classes, and types have been renamed to `Reflag*` (e.g. `BucketClient` is now `ReflagClient`) -- `Feature*` classes, and types have been renamed to `Feature*` (e.g. `Feature` is now `Flag`, `RawFeatures` is now `RawFlags`) -- All methods that contained `feature` in the name have been renamed to use the `flag` terminology (e.g. `getFeature` is `getFlag`) -- The `fallbackFeatures` property in client constructor and configuration files has been renamed to `fallbackFlags` -- `featureKey` has been renamed to `flagKey` in all methods that accepts that argument -- The new cookies that are stored in the client's browser are now `reflag-*` prefixed instead og `bucket-*` -- The `featuresUpdated` hook has been renamed to `flagsUpdated` -- The `checkIsEnabled` and `checkConfig` hooks have been removed, use `check` from now on - -To ease in transition to Reflag SDK, some of the old methods have been preserved as aliases to the new methods: - -- `getFeature` method is an alias for `getFlag` -- `getFeatures` method is an alias for `getFlags` -- `featuresUpdated` hook is an alias for `flagsUpdated` - -If you are running with strict Content Security Policies active on your website, you will need change them as follows: - -- `connect-src https://front.bucket.co` to `connect-src https://front.reflag.com` - -Finally, if you have customized the look & feel of the Feedback component, update `--bucket-feedback-*` CSS classes to `--reflag-feedback-*` - -## Flag toggles - -Reflag determines which flags are active for a given user/company. The user/company is given in the ReflagClient constructor. - -If you supply `user` or `company` objects, they must include at least the `id` property otherwise they will be ignored in their entirety. -In addition to the `id`, you must also supply anything additional that you want to be able to evaluate flag targeting rules against. - -Attributes cannot be nested (multiple levels) and must be either strings, integers or booleans. -Some attributes are special and used in Reflag UI: - -- `name` -- display name for `user`/`company`, -- `email` -- is accepted for `user`s and will be highlighted in the Reflag UI if available, -- `avatar` -- can be provided for both `user` and `company` and should be an URL to an image. +Create a client with your **publishable** key and the signed-in user's context: ```ts -const reflagClient = new ReflagClient({ - publishableKey, - user: { - id: "user_123", - name: "John Doe", - email: "john@acme.com" - avatar: "https://example.com/images/udsy6363" - }, - company: { - id: "company_123", - name: "Acme, Inc", - avatar: "https://example.com/images/31232ds" - }, -}); -``` - -To retrieve flags along with their targeting information, use `getFlag(key: string)`: - -```ts -const huddle = reflagClient.getFlag("huddle"); -// { -// isEnabled: true, -// config: { key: "zoom", payload: { ... } }, -// track: () => Promise -// requestFeedback: (options: RequestFeedbackData) => void -// } -``` - -You can use `getFlags()` to retrieve all enabled flags currently. +import { ReflagClient } from "@reflag/browser-sdk"; -```ts -const flags = reflagClient.getFlags(); -// { -// huddle: { -// isEnabled: true, -// targetingVersion: 42, -// config: ... -// } -// } +const reflag = new ReflagClient({ + publishableKey: "your-publishable-key", + user: { id: "alice", role: "manager" }, + company: { id: "acme", plan: "enterprise" }, +}); +await reflag.initialize(); ``` -`getFlags()` is meant to be more low-level than `getFlag()` and it typically used -by down-stream clients, like the React SDK. +Publishable keys are safe to ship to the browser. Keep secret keys on your server. -Note that accessing `isEnabled` on the object returned by `getFlags` does not automatically -generate a `check` event, contrary to the `isEnabled` property on the object returned by `getFlag`. +### 2. Create a flag -## End-user opt-in +Create a flag with the key `huddles` in the Reflag app. -If a flag has end-user opt-in enabled in Reflag, you can list the opt-in options for the current context and set or cancel opt-in for the current user or company. +### 3. Read the flag ```ts -const optInFlags = reflagClient.getOptInFlags(); -// [{ key, name, description, isEnabled, userOptedIn, companyOptedIn, isOptedIn }] - -try { - const response = await reflagClient.setOptIn("huddle", { - optedIn: true, // Use false to cancel this scope's opt-in. - scope: "user", // Use "company" to change the current company's opt-in. - }); - if (!response?.ok) { - console.error("Could not update opt-in"); - } -} catch (error) { - console.error("Could not update opt-in", error); +if (reflag.getFlag("huddles")) { + await reflag.track("Started huddle"); } ``` -By default, `setOptIn()` changes the opt-in for the current user, so the current context must include a `user.id`. To manage the current company's opt-in instead, pass `scope: "company"`; the context must then include a `company.id`. - -User and company opt-ins are managed independently. Setting `optedIn` to `false` removes the opt-in only for the selected scope. For example, cancelling a user's opt-in does not change the company's opt-in for the same flag. - -`setOptIn` returns a promise so you can wait for the new membership state to be synchronized. On success, it resolves after the refreshed flag state has been applied locally, the requested membership change has been confirmed, and `flagsUpdated` listeners have been notified when flags change. - -The promise resolves to a `Response`, or `undefined` if skipped due to invalid input, offline mode etc. Check `response?.ok` for success. - -The `description` comes from the dedicated SDK-facing opt-in description configured in Reflag. - -When using bootstrapped flags, the first `getOptInFlags()` or `getIsLoadingOptInFlags()` call requests a flags refresh. The list call returns the currently available list synchronously, and the loading getter returns `true` until that refresh succeeds or fails. Normal initialization also exposes loading through the client's state. - -Listen for `optInFlagsLoadingUpdated` to update UI when this loading state changes. `flagsUpdated` is emitted when a successful refresh updates the list. +## Read flags -If fetching opt-in metadata fails, loading ends without exposing an error. Call `reflagClient.refresh()` to retry. - -## Remote config - -Remote config is a dynamic and flexible approach to configuring flag behavior outside of your app – without needing to re-deploy it. - -Similar to `isEnabled`, each flag has a `config` property. This configuration is managed from within Reflag. -It is managed similar to the way access to flags is managed, but instead of the binary `isEnabled` you can have -multiple configuration values which are given to different user/companies. +Pass a flag key to check whether the flag is enabled: ```ts -const flags = reflagClient.getFlags(); -// { -// huddle: { -// isEnabled: true, -// targetingVersion: 42, -// config: { -// key: "gpt-3.5", -// payload: { maxTokens: 10000, model: "gpt-3.5-beta1" } -// } -// } -// } +const enabled = reflag.getFlag("huddles"); // true or false ``` -`key` is mandatory for a config, but if a flag has no config or no config value was matched against the context, the `key` will be `undefined`. Make sure to check against this case when trying to use the configuration in your application. `payload` is an optional JSON value for arbitrary configuration needs. - -Just as `isEnabled`, accessing `config` on the object returned by `getFlags` does not automatically -generate a `check` event, contrary to the `config` property on the object returned by `getFlag`. - -## Server-side rendering and bootstrapping - -For server-side rendered applications, you can render immediately with pre-fetched flag data by bootstrapping the client. - -### Init options bootstrapped - -```typescript -type Configuration = { - logger: console; // by default only logs warn/error, by passing `console` you'll log everything - apiBaseUrl?: "https://front.reflag.com"; - credentials?: "include" | "same-origin" | "omit"; // forwarded to fetch requests; "include" also enables credentials for the default EventSource transport - feedback?: undefined; // See FEEDBACK.md - enableTracking?: true; // set to `false` to stop sending track events and user/company updates to Reflag servers. Useful when you're impersonating a user - offline?: boolean; // Use the SDK in offline mode. Offline mode is useful during testing and local development - bootstrappedState?: { - context: ReflagContext; - flags: FetchedFlags; - flagStateVersion?: number; - }; // Pre-fetched evaluated state from server-side (see Server-side rendering section) - bootstrappedFlags?: FetchedFlags; // Deprecated: use `bootstrappedState` instead -}; -``` - -### Using `bootstrappedState` - -Use the Node SDK's `getFlagsForBootstrap()` method to pre-fetch evaluated state server-side, then pass the returned object directly to the browser client: - -```typescript -// Server-side: Get bootstrapped state using Node SDK -import { ReflagClient as ReflagNodeClient } from "@reflag/node-sdk"; - -const serverClient = new ReflagNodeClient({ secretKey: "your-secret-key" }); -await serverClient.initialize(); - -const bootstrappedState = serverClient.getFlagsForBootstrap({ - user: { id: "user123", name: "John Doe", email: "john@acme.com" }, - company: { id: "company456", name: "Acme Inc", plan: "enterprise" }, -}); - -// Pass the bootstrapped state to the client using your framework's preferred method -app.get("/", (req, res) => { - res.set("Content-Type", "text/html"); - res.send( - Buffer.from( - ` -
`, - ), - ); -}); - -// Client-side: Initialize with pre-fetched evaluated state -import { ReflagClient } from "@reflag/browser-sdk"; - -const reflagClient = new ReflagClient({ - publishableKey: "your-publishable-key", - bootstrappedState, // Contains context, flags, and optional flagStateVersion -}); +To read a configuration value, pass a default as the second argument. You get back a value of the same type as the default: -await reflagClient.initialize(); -const { isEnabled } = reflagClient.getFlag("huddle"); +```ts +const model = reflag.getFlag("model", "quick"); // string +const settings = reflag.getFlag("assistant-settings", { model: "quick" }); // { model: string } ``` -The `bootstrappedState` object contains: +If the flag doesn't exist, or its value has a different type, you get `false`, or your default if you passed one. Pass `null` as the default to accept any JSON value and narrow it yourself. -- `context`: the evaluation context used on the server -- `flags`: the evaluated raw flags -- `flagStateVersion`: an optional version used to avoid redundant live-update refreshes immediately after bootstrapping +The SDK checks only the top-level type of a value. If your application depends on nested fields, validate them. -If you want live flag updates to continue working after bootstrapping, use a recent `@reflag/node-sdk` so `getFlagsForBootstrap()` includes `flagStateVersion`. +`getFlags()` returns all flag values as a record. -If a bootstrapped application requests opt-in flags, the browser SDK performs one flags refresh. Applications that do not request opt-in data do not make this request. +Each read records a check, which Reflag uses for launch monitoring. -If you previously used `bootstrappedFlags`, migrate like this: +## Track usage and feedback -```typescript -// Before -const { flags } = serverClient.getFlagsForBootstrap(context); -const client = new ReflagClient({ - publishableKey, - user: context.user, - company: context.company, - other: context.other, - bootstrappedFlags: flags, -}); - -// After -const bootstrappedState = serverClient.getFlagsForBootstrap(context); -const client = new ReflagClient({ - publishableKey, - bootstrappedState, -}); +```ts +await reflag.track("Started huddle", { button: "cta" }); +reflag.requestFeedback({ flagKey: "huddles", title: "How did it go?" }); +await reflag.feedback({ flagKey: "huddles", score: 5 }); ``` -{% hint style="info" %} -After bootstrapping, any live flag updates are fetched directly by the browser SDK from Reflag using the browser-visible context. If your bootstrapped snapshot depends on server-only or secret context that is not available in the browser, later live refreshes may differ. In that case, keep `enableLiveFlagUpdates` disabled. - -Requesting opt-in flags also triggers a browser-side refresh, even when `enableLiveFlagUpdates` is disabled. -{% endhint %} +`requestFeedback()` opens the feedback form. `feedback()` sends feedback you collected yourself. -This eliminates loading states and removes the initial render's dependency on the flags API. +Configure your flag's adoption rules to match the event names you send. See [FEEDBACK.md](../../../supported-languages/browser-sdk/feedback.md) to configure feedback prompts and the feedback UI. -## Context management - -### Updating user/company/other context - -Attributes given for the user/company/other context in the ReflagClient constructor can be updated for use in flag targeting evaluation with the `updateUser()`, `updateCompany()` and `updateOtherContext()` methods. -They return a promise which resolves once the flags have been re-evaluated follow the update of the attributes. - -{% hint style="info" %} -{% endhint %} - -### setContext() - -The `setContext()` method allows you to replace the entire context (user, company, and other attributes) at once. This method is useful when you need to completely change the context, such as when a user logs in or switches between different accounts. +## Update context ```ts -await reflagClient.setContext({ - user: { - id: "new-user-123", - name: "Jane Doe", - email: "jane@example.com", - role: "admin", - }, - company: { - id: "company-456", - name: "New Company Inc", - plan: "enterprise", - }, - other: { - feature: "beta", - locale: "en-US", - }, +await reflag.updateUser({ role: "admin" }); +await reflag.updateCompany({ plan: "enterprise" }); +await reflag.updateOtherContext({ region: "eu" }); + +// Replace the whole context, for example after the user switches company: +await reflag.setContext({ + user: { id: "bob" }, + company: { id: "other-company" }, }); ``` -The method will: - -- Replace the entire context with the new values -- Re-evaluate all flags based on the new context -- Update the user and company information on Reflag servers -- Return a promise that resolves once the flags have been re-evaluated +The update methods merge into their section of the context, while `setContext()` replaces all of it. User and company sections need an `id`. Flag values are refetched for the new context. -### getContext() +## Bootstrap from the server -The `getContext()` method returns the current context being used for flag evaluation. This is useful for debugging or when you need to inspect the current user, company, and other attributes. +To render flags immediately, without waiting for a network request, evaluate them on your server with the **Node.js SDK** and pass the result to the browser: ```ts -const currentContext = reflagClient.getContext(); -console.log(currentContext); -// { -// user: { id: "user-123", name: "John Doe", email: "john@example.com" }, -// company: { id: "company-456", name: "Acme Inc", plan: "enterprise" }, -// other: { locale: "en-US", feature: "beta" } -// } -``` - -The returned context object contains: - -- `user`: Current user attributes (if any) -- `company`: Current company attributes (if any) -- `other`: Additional context attributes not related to user or company - -## Toolbar - -The Reflag Toolbar is great for toggling flags on/off for yourself to ensure that everything works both when a flag is on and when it's off. - -Toolbar screenshot - -The toolbar will automatically appear on `localhost`. However, it can also be incredibly useful in production. -You have full control over when it appears through the `toolbar` configuration option passed to the `ReflagClient`. - -You can pass a simple boolean to force the toolbar to appear/disappear: - -```typescript -const client = new ReflagClient({ - // show the toolbar even in production if the user is an internal/admin user - toolbar: user?.isInternal, - ... -}); -``` - -You can also configure the position of the toolbar on the screen: - -```typescript -const client = new ReflagClient({ - toolbar: { - show: true; - position: { - placement: "bottom-left", - offset: {x: "1rem", y: "1rem"} - } - } - ... -}) +// On the server +const bootstrappedState = serverClient.getFlagsForBootstrap(context); ``` -See [the reference](https://docs.reflag.com/supported-languages/browser-sdk/globals#toolbaroptions) for details. - -## Qualitative feedback on beta flags - -Reflag can collect qualitative feedback from your users in the form of a [Customer Satisfaction Score](https://en.wikipedia.org/wiki/Customer_satisfaction) and a comment. - -### Automated feedback collection - -The Reflag Browser SDK comes with automated feedback collection mode enabled by default, which lets the Reflag service ask your users for feedback for relevant flags just after they've used them. - -{% hint style="info" %} -To get started with automatic feedback collection, make sure you've set `user` in the `ReflagClient` constructor. -{% endhint %} - -Automated feedback surveys work even if you're not using the SDK to send events to Reflag. -It works because the Reflag Browser SDK maintains a live connection to Reflag's servers and can automatically show a feedback prompt whenever the Reflag servers determines that an event should trigger a prompt - regardless of how this event is sent to Reflag. - -You can find all the options to make changes to the default behavior in the [Reflag feedback documentation](../../documents/browser-sdk/FEEDBACK.md). - -### Reflag feedback UI - -Reflag can assist you with collecting your user's feedback by offering a pre-built UI, allowing you to get started with minimal code and effort. - -[Read the Reflag feedback UI documentation](../../documents/browser-sdk/FEEDBACK.md) - -### Reflag feedback SDK - -Feedback can be submitted to Reflag using the SDK: - ```ts -reflagClient.feedback({ - flagKey: "my-flag-key", // String (required), copy from Flag feedback tab - score: 5, // Number: 1-5 (optional) - comment: "Absolutely stellar work!", // String (optional) -}); +// In the browser +const reflag = new ReflagClient({ publishableKey, bootstrappedState }); +await reflag.initialize(); ``` -### Reflag feedback API - -If you are not using the Reflag Browser SDK, you can still submit feedback using the HTTP API. +Pass the whole object returned by `getFlagsForBootstrap()`, serialized with your framework's usual mechanism. Leave secrets and server-only attributes out of the context you bootstrap, because the browser can read it. -See details in [Feedback HTTP API](https://docs.reflag.com/api/http-api#post-feedback) +Later refreshes evaluate flags using the browser's context. If values that depend on server-only attributes must not change, leave `enableLiveFlagUpdates` off (the default). -## Tracking flag usage - -The `track` function lets you send events to Reflag to denote flag usage. -By default Reflag expects event names to align with the flag keys, but -you can customize it as you wish. +## Let users opt in to flags ```ts -reflagClient.track("huddle", { voiceHuddle: true }); +const optInFlags = reflag.getOptInFlags(); +await reflag.setOptIn("huddles", { optedIn: true }); +await reflag.setOptIn("huddles", { optedIn: false, scope: "company" }); ``` -## Event listeners - -Event listeners allow for capturing various events occurring in the `ReflagClient`. This is useful to build integrations with other system or for various debugging purposes. The available events are: +Each entry includes the flag's `key`, `name`, `description` and whether the user or company has opted in. User and company opt-ins are independent. Use `getIsLoadingOptInFlags()` and the `optInFlagsLoadingUpdated` event to show a loading state. -- `check`: Your code used `isEnabled` or `config` for a flag -- `flagsUpdated`: Flags were updated. Either because they were loaded as part of initialization or because the user/company updated -- `optInFlagsLoadingUpdated`: The opt-in flag loading state changed -- `user`: User information updated (similar to the `identify` call used in tracking terminology) -- `company`: Company information updated (sometimes to the `group` call used in tracking terminology) -- `track`: Track event occurred. +## Overrides and toolbar -Use the `on()` method to add an event listener to respond to certain events. See the API reference for details on each hook. +Override flags locally while developing or testing: ```ts -import { ReflagClient, CheckEvent, RawFlags } from "@reflag/browser-sdk"; - -const client = new ReflagClient({ - // options -}); - -// or add the hooks after construction: -const unsub = client.on("check", (check: CheckEvent) => - console.log(`Check event ${check}`), -); -// use the returned function to unsubscribe, or call `off()` with the same arguments again -unsub(); +reflag.setFlagOverride("huddles", true); +reflag.setFlagOverride("assistant-settings", { model: "local" }); +reflag.setFlagOverride("huddles", undefined); // remove the override ``` -## Zero PII - -The Reflag Browser SDK doesn't collect any metadata and HTTP IP addresses are _not_ being stored. - -For tracking individual users, we recommend using something like database ID as userId, as it's unique and doesn't include any PII (personal identifiable information). If, however, you're using e.g. email address as userId, but prefer not to send any PII to Reflag, you can hash the sensitive data before sending it to Reflag: +The toolbar shows on `localhost` by default and lets you toggle Boolean flags for yourself. Use the `toolbar` option to show it elsewhere, for example to internal users in production: ```ts -import reflag from "@reflag/browser-sdk"; -import { sha256 } from "crypto-hash"; - -reflag.user(await sha256("john_doe")); +const reflag = new ReflagClient({ + publishableKey, + toolbar: user.isInternal, // show the toolbar to internal users +}); ``` -## Use of cookies - -The Reflag Browser SDK uses a couple of cookies to support automated feedback surveys. These cookies are not used for tracking purposes and thus should not need to appear in cookie consent forms. - -The two cookies are: - -- `reflag-prompt-${userId}`: store the last automated feedback prompt message ID received to avoid repeating surveys -- `reflag-token-${userId}`: caching a token used to connect to Reflag's live messaging infrastructure that is used to deliver automated feedback surveys in real time. +## Events -## TypeScript +`on(event, handler)` subscribes to client events and returns an unsubscribe function. Events include `stateUpdated`, `flagsUpdated`, `check`, `track`, `user`, `company` and `optInFlagsLoadingUpdated`. -Types are bundled together with the library and exposed automatically when importing through a package manager. +## Configuration -## Content Security Policy (CSP) +| Option | Description | +| -------------------------- | --------------------------------------------------------------- | +| `fallbackFlags` | Values to use if flags can't be fetched | +| `enableLiveFlagUpdates` | Update flags when they change in Reflag; default `false` | +| `staleTimeMs` | How long cached flags count as fresh; default `0` | +| `staleWhileRevalidate` | Use stale cached flags while fetching new ones; default `false` | +| `expireTimeMs` | How long cached flags are kept; default 30 days | +| `timeoutMs` | Flag request timeout; default 5,000 ms | +| `enableTracking` | Set to `false` to stop sending checks and usage events | +| `offline` | Make no network requests, for example in tests | +| `toolbar`, `feedback` | Toolbar and feedback UI options | +| `logger` | Custom logger | +| `apiBaseUrl`, `appBaseUrl` | Override the API and app URLs | +| `credentials` | Fetch credentials mode | +| `storage` | Custom async storage for the flag cache | +| `eventSourceFactory` | Custom EventSource implementation for runtimes without one | +| `trackingQueue` | Event batching: `flushDelayMs` and `maxSize` | -If you are running with strict Content Security Policies active on your website, you will need to enable these directives in order to use the SDK: +## Shut down -| Directive | Values | Reason | -| ----------- | ---------------------------------------------------- | ------------------------------------------------------------------------------------------------------- | -| connect-src | [https://front.reflag.com](https://front.reflag.com) | API requests plus Server-Sent Events for live flag updates and automated feedback surveys. | -| style-src | 'unsafe-inline' | The feedback UI is styled with inline styles. Not having this directive results unstyled HTML elements. | +Call `await reflag.stop()` to send buffered events and close the client, for example when the user signs out. -If you are including the Reflag tracking SDK with a ` - - - -``` - -If using Nuxt, wrap `` in ``. `` only renders client-side currently. - -### 2. Use `useFlag get flag status - -```vue - - - -``` - -See [useFlag()](#useflag) for a full example - -## Setting context - -Reflag determines which flags are active for a given `user`, `company`, or `other` context. -You can pass these to the `ReflagProvider` using the `context` prop. - -### Using the `context` prop - -```vue - - - -``` - -### Legacy individual props (deprecated) - -For backward compatibility, you can still use individual props, but these are deprecated and will be removed in the next major version: - -```vue - - - -``` - -> [!Important] -> The `user`, `company`, and `otherContext` props are deprecated. Use the `context` prop instead, which provides the same functionality in a more structured way. - -### Context requirements - -If you supply `user` or `company` objects, they must include at least the `id` property otherwise they will be ignored in their entirety. -In addition to the `id`, you must also supply anything additional that you want to be able to evaluate flag targeting rules against. -Attributes which are not properties of the `user` or `company` can be supplied using the `other` property. - -Attributes cannot be nested (multiple levels) and must be either strings, numbers or booleans. -A number of special attributes exist: - -- `name` -- display name for `user`/`company`, -- `email` -- the email of the user, -- `avatar` -- the URL for `user`/`company` avatar image. - -To retrieve flags along with their targeting information, use `useFlag(key: string)` hook (described in a section below). - -Note that accessing `isEnabled` on the object returned by `useFlag()` automatically -generates a `check` event. - -## Remote config - -Remote config is a dynamic and flexible approach to configuring flag behavior outside of your app – without needing to re-deploy it. - -Similar to `isEnabled`, each flag accessed using the `useFlag()` hook, has a `config` property. This configuration is managed from within Reflag. It is managed similar to the way access to flags is managed, but instead of the -binary `isEnabled` you can have multiple configuration values which are given to different user/companies. - -### Get started with Remote config - -```ts -const { - isEnabled, - config: { key, payload }, -} = useFlag("huddles"); - -// isEnabled: true, -// key: "gpt-3.5", -// payload: { maxTokens: 10000, model: "gpt-3.5-beta1" } -``` - -`key` is mandatory for a config, but if a flag has no config or no config value was matched against the context, the `key` will be `undefined`. Make sure to check against this case when trying to use the configuration in your application. `payload` is an optional JSON value for arbitrary configuration needs. - -Note that, similar to `isEnabled`, accessing `config` on the object returned by `useFlag()` automatically -generates a `check` event. - -## `` component - -The `` initializes the Reflag SDK, fetches flags and starts listening for automated feedback survey events. The component can be configured using a number of props: - -- `publishableKey` is used to connect the provider to an _environment_ on Reflag. Find your `publishableKey` under [environment settings](https://app.reflag.com/env-current/settings/app-environments) in Reflag, -- `context`: An object containing `user`, `company`, and `other` properties that make up the evaluation context used to determine if a flag is enabled or not. `company` and `user` contexts are automatically transmitted to Reflag servers so the Reflag app can show you which companies have access to which flags etc. -- `company`, `user` and `otherContext` (deprecated): Individual props for context. These are deprecated in favor of the `context` prop and will be removed in the next major version. - - > [!Note] - > If you specify `company` and/or `user` they must have at least the `id` property, otherwise they will be ignored in their entirety. You should also supply anything additional you want to be able to evaluate flag targeting against, - -- `timeoutMs`: Timeout in milliseconds when fetching flags from the server, -- `staleWhileRevalidate`: If set to `true`, stale flags will be returned while refetching flags in the background, -- `expireTimeMs`: If set, flags will be cached between page loads for this duration (in milliseconds), -- `staleTimeMs`: Maximum time (in milliseconds) that stale flags will be returned if `staleWhileRevalidate` is true and new flags cannot be fetched. - -- `enableTracking`: Set to `false` to stop sending tracking events and user/company updates to Reflag. Useful when you're impersonating a user (defaults to `true`), -- `apiBaseUrl`: Optional base URL for the Reflag API. This also controls the SSE origin used for live flag updates and automated feedback, -- `credentials`: Optional fetch credentials mode. Set to `"include"` when proxying through your backend and authenticating with cookies; this also enables credentials for live-update SSE connections. -- `appBaseUrl`: Optional base URL for the Reflag application. Use this to override the default app URL, - -- `debug`: Set to `true` to enable debug logging to the console. If both `logger` and `debug` are provided, `logger` takes precedence, -- `logger`: Optional custom logger implementation (`debug`, `info`, `warn`, `error`) used by the underlying client, -- `toolbar`: Optional [configuration](https://docs.reflag.com/supported-languages/browser-sdk/globals#toolbaroptions) for the Reflag toolbar, -- `feedback`: Optional configuration for feedback collection - -### Loading states - -ReflagProvider lets you define a template to be shown while ReflagProvider is initializing: - -```vue ``` -If you want more control over loading screens, `useIsLoading()` returns a `Ref` which you can use to customize the loading experience. +In Nuxt, wrap the provider in ``. -## `` component +### 2. Create a flag -The `` component is a specialized version of `ReflagProvider` designed for server-side rendering and preloaded flag scenarios. It uses pre-fetched flags for the initial render, resulting in faster initial page loads and better SSR compatibility. +Create a flag with the key `huddles` in the Reflag app. -### Usage +### 3. Read the flag -```vue - - - -``` - -### Getting bootstrapped flags - -You'll typically generate the `bootstrappedFlags` object on your server using the Node.js SDK or by fetching from the Reflag API. Pass the full object returned by `getFlagsForBootstrap()` directly to ``. It contains: - -- `context`: the evaluation context used on the server -- `flags`: the evaluated raw flags -- `flagStateVersion`: an optional version used to avoid redundant live-update refreshes immediately after bootstrapping - -If you want live flag updates to continue working after bootstrapping, use a recent `@reflag/node-sdk` so `getFlagsForBootstrap()` includes `flagStateVersion`. - -With `ReflagBootstrappedProvider`, `useOptInFlags()` requests a flags refresh on first use. It reports `isLoading: true` until that refresh settles. - -Here's an example using the Node.js SDK: - -```js -// server.js (Node.js/SSR) -import { ReflagClient } from "@reflag/node-sdk"; - -const client = new ReflagClient({ - secretKey: "your-secret-key", // Use secret key on server -}); -await client.initialize(); - -// Fetch flags for specific context -const context = { - user: { id: "user123", name: "John Doe", email: "john@acme.com" }, - company: { id: "company456", name: "Acme Inc", plan: "enterprise" }, -}; - -const bootstrappedFlags = client.getFlagsForBootstrap(context); - -// Pass to your Vue app -``` - -### ReflagBootstrappedProvider Props - -`ReflagBootstrappedProvider` accepts all the same props as `ReflagProvider` except: - -- `flags`: The pre-fetched bootstrapped state object containing `context`, evaluated `flags`, and an optional `flagStateVersion` -- All other props available in `ReflagProvider` are supported except `context`, `user`, `company`, and `otherContext` (which are extracted from `flags.context`) - -If the `flags` prop is not provided or is undefined, the provider will not initialize the client and will render in a non-loading state. - -{% hint style="info" %} -After bootstrapping, any live flag updates are fetched directly by the browser SDK from Reflag using the browser-visible context. If your bootstrapped snapshot depends on server-only or secret context that is not available in the browser, later live refreshes may differ. In that case, keep `enableLiveFlagUpdates` disabled. - -Requesting opt-in flags also triggers a browser-side refresh, even when `enableLiveFlagUpdates` is disabled. -{% endhint %} - -## `` component - -The `` is a lower-level component that accepts a pre-initialized `ReflagClient` instance. This is useful for advanced use cases where you need full control over client initialization or want to share a client instance across multiple parts of your application. - -### ReflagClientProvider Usage +Use `useFlag()` in any component: ```vue ``` -### ReflagClientProvider Props - -The `ReflagClientProvider` accepts the following props: +## Read flags -- `client`: A pre-initialized `ReflagClient` instance +`useFlag()` returns a ref that updates when the flag changes. Vue unwraps refs in templates; use `.value` in script. -### Slots - -- `loading`: Optional slot to show while the client is initializing (same as `ReflagProvider`) - -> [!Note] -> Most applications should use `ReflagProvider` or `ReflagBootstrappedProvider` instead of `ReflagClientProvider`. Only use this component when you need the advanced control it provides. - -## Hooks - -### `useFlag()` - -Returns the state of a given flag for the current context. The composable provides access to flags and their configurations. - -`useFlag()` returns an object with this shape: +Pass a flag key to check whether the flag is enabled: ```ts -{ - isEnabled: boolean, // is the flag enabled - track: () => void, // send a track event when the flag is used - requestFeedback: (...) => void // open up a feedback dialog - config: {key: string, payload: any}, // remote configuration for this flag - isLoading: boolean // if you want to manage loading state at the flag level -} -``` - -Example: - -```vue - - - +const enabled = useFlag("huddles"); // ref of true or false ``` -See the reference docs for details. - -### `useOptInFlags()` and `useSetOptIn()` +To read a configuration value, pass a default as the second argument. The ref holds a value of the same type as the default: -Use these composables to build an end-user opt-in UI for flags where opt-in is enabled in Reflag. - -```vue - - - +```ts +const model = useFlag("model", "quick"); // ref of string +const settings = useFlag("huddle-settings", { maxParticipants: 10 }); // ref of { maxParticipants: number } ``` -By default, `useSetOptIn()` changes the opt-in for the current user, so the current context must include a `user.id`. To manage the current company's opt-in instead, pass `scope: "company"`; the context must then include a `company.id`. - -User and company opt-ins are managed independently. Setting `optedIn` to `false` removes the opt-in only for the selected scope. For example, cancelling a user's opt-in does not change the company's opt-in for the same flag. - -`setOptIn` returns a promise so you can wait for the new membership state to be synchronized. On success, it resolves after the refreshed flag state has been applied locally, the requested membership change has been confirmed, and subscribers have been notified when flags change. Vue may not have committed the resulting render yet. - -The promise resolves to a `Response`, or `undefined` if skipped due to invalid input, offline mode etc. Check `response?.ok` for success. +While flags are loading, if the flag doesn't exist, or if its value has a different type, the ref holds `false`, or your default if you passed one. Pass `null` as the default to accept any JSON value and narrow it yourself. -`useOptInFlags()` returns `{ flags, isLoading }`, where both values are computed refs. With `ReflagBootstrappedProvider`, it fetches opt-in metadata on first use and reports `isLoading: true` until that refresh succeeds or fails. +The SDK checks only the top-level type of a value. If your application depends on nested fields, validate them. -If fetching opt-in metadata fails, loading ends without exposing an error. Call `client.refresh()` on the client returned by `useClient()` to retry. +Each read records a check, which Reflag uses for launch monitoring. -With a regular `ReflagProvider`, opt-in metadata arrives as part of the normal initial flags request, so `useOptInFlags().isLoading` remains `false`. Use the general `useIsLoading()` composable or the provider's loading slot for that initial loading state. +## Loading states -### `useTrack()` +`useIsLoading()` returns a Boolean ref that is `true` while the provider loads flags. You can also put loading content in the provider's `#loading` slot, as in the example above. -`useTrack()` returns a function which lets you send custom events to Reflag. It takes a string argument with the event name and optionally an object with properties to attach the event. - -Using `track` returned from `useFlag()` calls this track function with the flag key as the event name. - -```vue - - - -``` - -### `useRequestFeedback()` - -Returns a function that lets you open up a dialog to ask for feedback on a specific feature. This is useful for collecting targeted feedback about specific features. - -See [Automated Feedback Surveys](https://docs.reflag.com/product-handbook/live-satisfaction) for how to do this automatically, without code. - -When using the `useRequestFeedback` you must pass the flag key to `requestFeedback`. -The example below shows how to use `position` to ensure the popover appears next to the "Give feedback!" button. - -```vue - - - -``` - -See the [Feedback Documentation](https://github.com/reflagcom/javascript/blob/main/packages/browser-sdk/FEEDBACK.md#manual-feedback-collection) for more information on `requestFeedback` options. - -### `useSendFeedback()` - -Returns a function that lets you send feedback to Reflag. This is useful if you've manually collected feedback through your own UI and want to send it to Reflag. - -```vue - - - +await sendFeedback({ flagKey: "huddles", score: 5 }); ``` -### `useUpdateUser()`, `useUpdateCompany()` and `useUpdateOtherContext()` +Configure your flag's adoption rules to match the event names you send. See the [Browser feedback documentation](../../../supported-languages/browser-sdk/feedback.md) to configure feedback prompts and the feedback UI. -These composables return functions that let you update the attributes for the currently set user, company, or other context. Updates to user/company are stored remotely and affect flag targeting, while "other" context updates only affect the current session. +## Update context -```vue - +`useUpdateUser()`, `useUpdateCompany()` and `useUpdateOtherContext()` return functions that merge new attributes into the current context. To replace the whole context, call `useClient().setContext(context)`. Flag values are refetched for the new context. - -``` +## Bootstrap from the server -Note: To change the `user.id` or `company.id`, you need to update the props passed to `ReflagProvider` instead of using these composables. +To render flags immediately, without waiting for a network request, evaluate them on your server with the **Node.js SDK**: -### `useClient()` +```ts +const flags = serverClient.getFlagsForBootstrap(context); +``` -Returns the `ReflagClient` used by the `ReflagProvider`. The client offers more functionality that -is not directly accessible through the other composables. +Then pass the whole result to `ReflagBootstrappedProvider`, serialized with your framework's usual mechanism: ```vue - - - + + + ``` -### `useIsLoading()` - -Returns a `Ref` to indicate if Reflag has finished loading. -Initially, the value will be `true` if no bootstrap flags have been provided and the client has not be initialized. +Leave secrets and server-only attributes out of the context you bootstrap, because the browser can read it. Later refreshes evaluate flags using the browser's context. If values that depend on server-only attributes must not change, set `:enable-live-flag-updates="false"`. -```vue - +```ts +const { flags, isLoading } = useOptInFlags(); +const setOptIn = useSetOptIn(); - +await setOptIn("huddles", { optedIn: true }); +await setOptIn("huddles", { optedIn: false, scope: "company" }); ``` -### `useOnEvent()` - -Vue composable for listening to Reflag client events. This composable automatically handles mounting and unmounting of event listeners. +Each entry includes the flag's `key`, `name`, `description` and whether the user or company has opted in. User and company opt-ins are independent. Check `isLoading` before rendering an empty state. -Available events include: +## Overrides and toolbar -- `flagsUpdated`: Triggered when flags are updated -- `track`: Triggered when tracking events are sent -- `feedback`: Triggered when feedback is sent +The toolbar shows on `localhost` by default and lets you toggle Boolean flags for yourself. Use the `toolbar` prop to show it elsewhere, for example to internal users in production: ```vue - - - + + + ``` -You can also provide a specific client instance if needed: - -```vue - +`useClient()` returns the underlying Browser SDK client. If you already create a Browser SDK client yourself, pass it to `ReflagClientProvider`; your application is then responsible for initializing and stopping it. - -``` +## Events -## Content Security Policy (CSP) +`useOnEvent(type, handler)` subscribes to [client events](../../../supported-languages/browser-sdk/README.md) and unsubscribes when the component unmounts. -See [CSP](https://github.com/reflagcom/javascript/blob/main/packages/browser-sdk/README.md#content-security-policy-csp) for info on using Reflag React SDK with CSP +## Configuration -## License +The provider accepts the Browser SDK's configuration options, such as `fallbackFlags`, `enableTracking`, `offline`, `feedback` and `logger`, as props. Live updates are on by default in Vue; set `:enable-live-flag-updates="false"` to turn them off. Set `debug` to log to the console. -MIT License +For Content Security Policy requirements and the full list of options, see the [Browser SDK](../../../supported-languages/browser-sdk/README.md). -Copyright (c) 2025 Bucket ApS +Using v1? [Legacy docs](../../../legacy/v1/vue-sdk/README.md) · [Upgrade guide](../../../supported-languages/migrating-from-v1.md). diff --git a/sdk/@reflag/vue-sdk/globals.md b/sdk/@reflag/vue-sdk/globals.md index 0ae59b1..366e091 100644 --- a/sdk/@reflag/vue-sdk/globals.md +++ b/sdk/@reflag/vue-sdk/globals.md @@ -13,22 +13,23 @@ pagination: visible: true --- -# @reflag/vue-sdk +# @reflag/vue-sdk -## Interfaces +This page covers SDK v2. -### CheckEvent +## Interfaces -Event representing checking the flag evaluation result +### CheckEvent -#### Properties +A root read records selection identity, never its JSON payload. + +#### Properties - @@ -40,53 +41,38 @@ Event representing checking the flag evaluation result - - - + + + - + + - - + + @@ -162,19 +146,19 @@ Version of targeting rules. *** -### CompanyContext +### CompanyContext Context is a set of key-value pairs. This is used to determine if feature targeting matches and to track events. Id should always be present so that it can be referenced to an existing company. -#### Indexable +#### Indexable ```ts [key: string]: ContextValue ``` -#### Properties +#### Properties
Property TypeDescription
-`"check-is-enabled"` \| `"check-config"` - - - -`check-is-enabled` means `isEnabled` was checked, `check-config` means `config` was checked. +`"check"`
- `evaluationErrors?` + `evalContext?` -\{ `code`: `string`; `field`: `string`; `message`: `string`; `operator`: `string`; \}[] - - - -Non-fatal diagnostics produced while evaluating the flag. +[`ReflagContext`](../../../supported-languages/browser-sdk/globals.md#reflagcontext)
- `key` + `evalErrors?` -`string` - - - -Flag key. +[`EvaluationError`](../../../supported-languages/browser-sdk/globals.md#evaluationerror)[]
- ~~`missingContextFields?`~~ + `evalMissingFields?` @@ -94,66 +80,64 @@ Flag key. `string`[]
-Missing context fields. + `evalResult?` -**Deprecated** + -Use `evaluationErrors` and check for `MISSING_CONTEXT_FIELD`. +`string`
- `ruleEvaluationResults?` + `evalRuleResults?` `boolean`[] - - -Rule evaluation results. -
- `value?` + `flagStateVersion?` - \| `boolean` \| \{ `key`: `string`; `payload`: `any`; \} +`number`
-Result of flag or configuration evaluation. -If `action` is `check-is-enabled`, this is the result of the flag evaluation and `value` is a boolean. -If `action` is `check-config`, this is the result of the configuration evaluation. + `key`
- `version?` +`string`
-`number` + `sourceVersionId?` -Version of targeting rules. +`string`
@@ -224,144 +208,23 @@ Company name *** -### Flag\ - -#### Type Parameters - -
- - - - - - - - - - - - -
Type ParameterDefault type
- -`TConfig` *extends* [`FlagType`](globals.md#flagtype)\[`"config"`\] - - - -[`EmptyFlagRemoteConfig`](globals.md#emptyflagremoteconfig) - -
- -#### Properties - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
PropertyType
- - `config` - - - -`Ref`\< \| [`EmptyFlagRemoteConfig`](globals.md#emptyflagremoteconfig) \| \{ `key`: `string`; \} & `TConfig`, \| [`EmptyFlagRemoteConfig`](globals.md#emptyflagremoteconfig) \| \{ `key`: `string`; \} & `TConfig`\> - -
- - `isEnabled` - - - -`Ref`\<`boolean`, `boolean`\> - -
- - `isLoading` - - - -`Ref`\<`boolean`, `boolean`\> - -
- - `key` - - - -`string` - -
- - `requestFeedback` - - - -(`opts`: [`RequestFlagFeedbackOptions`](globals.md#requestflagfeedbackoptions)) => `void` - -
- -#### Methods - -##### track() - -```ts -track(): - | undefined - | Promise< - | undefined -| Response> -``` - -###### Returns - - \| `undefined` - \| [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\< - \| `undefined` - \| [`Response`](https://developer.mozilla.org/docs/Web/API/Response)\> - -*** - -### Flags +### Flags *** -### UserContext +### UserContext Context is a set of key-value pairs. This is used to determine if feature targeting matches and to track events. Id should always be present so that it can be referenced to an existing user. -#### Indexable +#### Indexable ```ts [key: string]: ContextValue ``` -#### Properties +#### Properties @@ -426,142 +289,73 @@ User name
-## Type Aliases +## Type Aliases -### BootstrappedFlags +### BootstrappedFlags ```ts -type BootstrappedFlags = BootstrappedState & { - flags: RawFlags; -}; +type BootstrappedFlags = BootstrappedState; ``` -#### Type declaration - - - - - - - - - - - - - - -
NameType
- -`flags` - - - -[`RawFlags`](../browser-sdk/globals.md#rawflags) - -
- *** -### EmptyFlagRemoteConfig +### FlagDefaultValue ```ts -type EmptyFlagRemoteConfig = { - key: undefined; - payload: undefined; -}; +type FlagDefaultValue = + | null + | boolean + | number + | string + | readonly FlagDefaultValue[] +| {}; ``` -#### Type declaration - - - - - - - - - - - - - - - - - - -
NameType
- - `key` - - - -`undefined` - -
- - `payload` - - +*** -`undefined` +### FlagKey -
+```ts +type FlagKey = keyof Flags extends never ? string : Extract; +``` *** -### FlagKey +### FlagValue ```ts -type FlagKey = keyof TypedFlags; +type FlagValue = + | null + | boolean + | number + | string + | FlagValue[] +| {}; ``` *** -### FlagType +### FlagValueFromDefault\ ```ts -type FlagType = { - config: { - payload: any; - }; -}; +type FlagValueFromDefault = T extends null ? FlagValue : T extends boolean ? boolean : T extends number ? number : T extends string ? string : T extends readonly infer Element[] ? [Element] extends [never] ? FlagValue[] : FlagValueFromDefault[] : T extends object ? { -readonly [Key in keyof T]: FlagValueFromDefault } : never; ``` -#### Type declaration +Widen literals and return mutable copies. Null requests arbitrary JSON. + +#### Type Parameters - - + - - - - - @@ -570,7 +364,7 @@ type FlagType = { *** -### OptInFlag +### OptInFlag ```ts type OptInFlag = Omit & { @@ -578,13 +372,7 @@ type OptInFlag = Omit & { }; ``` -An opt-in-enabled flag for the generated Vue SDK flag definitions. - -Includes all fields from [BrowserOptInFlag](../browser-sdk/globals.md#optinflag): `name`, `description`, -`isEnabled`, `userOptedIn`, `companyOptedIn`, and `isOptedIn`. -Only `key` is narrowed to the generated [FlagKey](globals.md#flagkey) type. - -#### Type declaration +#### Type declaration
NameTypeType Parameter
- `config`? - - - -\{ - `payload`: `any`; - \} - -
- -`config.payload` - - - -`any` +`T`
@@ -602,7 +390,7 @@ Only `key` is narrowed to the generated [FlagKey](globals.md#flagkey) type. @@ -611,7 +399,7 @@ Only `key` is narrowed to the generated [FlagKey](globals.md#flagkey) type. *** -### ReflagBaseProps +### ReflagBaseProps ```ts type ReflagBaseProps = { @@ -625,7 +413,7 @@ type ReflagBaseProps = { Base props for the ReflagProvider and ReflagBootstrappedProvider. -#### Type declaration +#### Type declaration
-[`FlagKey`](globals.md#flagkey) +[`FlagKey`](../../../supported-languages/vue-sdk/globals.md#flagkey)
@@ -678,7 +466,7 @@ Set to `true` to show the loading component while the client is initializing.
-[`Logger`](../browser-sdk/globals.md#logger-1) +[`Logger`](../../../supported-languages/browser-sdk/globals.md#logger) @@ -694,7 +482,7 @@ If both `logger` and `debug` are provided, `logger` takes precedence. *** -### ReflagBootstrappedProps +### ReflagBootstrappedProps ```ts type ReflagBootstrappedProps = ReflagInitOptionsBase & ReflagBaseProps & { @@ -704,7 +492,7 @@ type ReflagBootstrappedProps = ReflagInitOptionsBase & ReflagBaseProps & { Props for the ReflagBootstrappedProvider. -#### Type declaration +#### Type declaration @@ -723,7 +511,7 @@ Props for the ReflagBootstrappedProvider.
-[`BootstrappedFlags`](globals.md#bootstrappedflags) +[`BootstrappedFlags`](../../../supported-languages/vue-sdk/globals.md#bootstrappedflags) @@ -738,7 +526,7 @@ metadata on demand when opt-in flags are requested. *** -### ReflagClientProviderProps +### ReflagClientProviderProps ```ts type ReflagClientProviderProps = Omit & { @@ -748,7 +536,7 @@ type ReflagClientProviderProps = Omit & { Props for the ReflagClientProvider. -#### Type declaration +#### Type declaration @@ -767,7 +555,7 @@ Props for the ReflagClientProvider. - - - - - - - -
-[`ReflagClient`](../browser-sdk/globals.md#reflagclient) +[`ReflagClient`](../../../supported-languages/browser-sdk/globals.md#reflagclient) @@ -781,10 +569,10 @@ A pre-initialized ReflagClient to use. *** -### ReflagInitOptionsBase +### ReflagInitOptionsBase ```ts -type ReflagInitOptionsBase = Omit ```ts type ReflagProps = ReflagInitOptionsBase & ReflagBaseProps & { @@ -813,7 +601,7 @@ type ReflagProps = ReflagInitOptionsBase & ReflagBaseProps & { Props for the ReflagProvider. -#### Type declaration +#### Type declaration @@ -832,7 +620,7 @@ Props for the ReflagProvider. + + + + +
-[`CompanyContext`](globals.md#companycontext) +[`CompanyContext`](../../../supported-languages/vue-sdk/globals.md#companycontext) @@ -854,7 +642,7 @@ Use `context` instead, this property will be removed in the next major version -[`ReflagContext`](../browser-sdk/globals.md#reflagcontext) +[`ReflagContext`](../../../supported-languages/browser-sdk/globals.md#reflagcontext) @@ -892,7 +680,7 @@ Use `context` instead, this property will be removed in the next major version -[`UserContext`](globals.md#usercontext) +[`UserContext`](../../../supported-languages/vue-sdk/globals.md#usercontext) @@ -911,7 +699,7 @@ Use `context` instead, this property will be removed in the next major version *** -### RequestFlagFeedbackOptions +### RequestFlagFeedbackOptions ```ts type RequestFlagFeedbackOptions = Omit; @@ -919,7 +707,7 @@ type RequestFlagFeedbackOptions = Omit ```ts type SetOptInOptions = { @@ -928,9 +716,9 @@ type SetOptInOptions = { }; ``` -Options for changing the current user or company's opt-in membership. +Represents a flag. -#### Type declaration +#### Type declaration @@ -980,7 +768,7 @@ Whether to update the current user or current company. Defaults to `user`. *** -### TrackEvent +### TrackEvent ```ts type TrackEvent = { @@ -992,7 +780,7 @@ type TrackEvent = { }; ``` -#### Type declaration +#### Type declaration
@@ -1023,7 +811,7 @@ type TrackEvent = { @@ -1047,7 +835,7 @@ type TrackEvent = { @@ -1056,15 +844,15 @@ type TrackEvent = { *** -### TypedFlags +### TypedFlags ```ts -type TypedFlags = keyof Flags extends never ? Record : { [TypedFlagKey in keyof Flags]: Flags[TypedFlagKey] extends FlagType ? Flag : Flag }; +type TypedFlags = keyof Flags extends never ? Record : { [Key in keyof Flags]: Flags[Key] | undefined }; ``` *** -### UseOptInFlagsResult +### UseOptInFlagsResult ```ts type UseOptInFlagsResult = { @@ -1073,7 +861,7 @@ type UseOptInFlagsResult = { }; ``` -#### Type declaration +#### Type declaration
-[`CompanyContext`](globals.md#companycontext) +[`CompanyContext`](../../../supported-languages/vue-sdk/globals.md#companycontext)
-[`UserContext`](globals.md#usercontext) +[`UserContext`](../../../supported-languages/vue-sdk/globals.md#usercontext)
@@ -1091,14 +879,14 @@ type UseOptInFlagsResult = {
-`ComputedRef`\<[`OptInFlag`](globals.md#optinflag)[]\> +`ComputedRef`\<[`OptInFlag`](../../../supported-languages/vue-sdk/globals.md#optinflag)[]\>
- `isLoading` + `isLoading` @@ -1110,9 +898,9 @@ type UseOptInFlagsResult = {
-## Variables +## Variables -### default +### default ```ts default: { @@ -1120,7 +908,7 @@ default: { }; ``` -#### Type declaration +#### Type declaration @@ -1147,15 +935,15 @@ default: { *** -### ReflagBootstrappedProvider +### ReflagBootstrappedProvider ```ts const ReflagBootstrappedProvider: DefineComponent, Record, unknown>; ``` -## Functions +## Functions -### useClient() +### useClient() ```ts function useClient(): ReflagClient @@ -1166,13 +954,13 @@ Vue composable for getting the Reflag client. This composable returns the Reflag client. You can use this to get the Reflag client at any point in your application. -#### Returns +#### Returns -[`ReflagClient`](../browser-sdk/globals.md#reflagclient) +[`ReflagClient`](../../../supported-languages/browser-sdk/globals.md#reflagclient) The Reflag client. -#### Example +#### Example ```ts import { useClient } from '@reflag/vue-sdk'; @@ -1184,17 +972,66 @@ console.log(client.getContext()); *** -### useFlag() +### useFlag() + +#### Call Signature ```ts -function useFlag(key: TKey): TypedFlags[TKey] +function useFlag(key: string, defaultValue?: undefined): ShallowRef ``` -Vue composable for getting the state of a given flag for the current context. +Reactive direct values: Boolean/false by default, or infer a positional JSON default. + +### Parameters + +
+ + + + + + + + + + + + + + + + +
ParameterType
+ +`key` + + + +`string` + +
+ +`defaultValue`? + + + +`undefined` -This composable returns an object with the state of the flag for the current context. +
-#### Type Parameters +### Returns + +`ShallowRef`\<`boolean`\> + +#### Call Signature + +```ts +function useFlag(key: Key, defaultValue: Default): ShallowRef> +``` + +Reactive direct values: Boolean/false by default, or infer a positional JSON default. + +### Type Parameters @@ -1206,21 +1043,27 @@ This composable returns an object with the state of the flag for the current con + + +
-`TKey` *extends* `string` +`Key` *extends* `string` + +
+ +`Default` *extends* `object` \| [`FlagDefaultValue`](../../../supported-languages/vue-sdk/globals.md#flagdefaultvalue)
-#### Parameters +### Parameters - @@ -1232,41 +1075,100 @@ This composable returns an object with the state of the flag for the current con + + +
Parameter TypeDescription
-`TKey` +`Key` + +
+ +`defaultValue` -The key of the flag to get the state of. +`Default`
-#### Returns - -[`TypedFlags`](globals.md#typedflags)\[`TKey`\] +### Returns -An object with the state of the flag. +`ShallowRef`\<[`FlagValueFromDefault`](../../../supported-languages/vue-sdk/globals.md#flagvaluefromdefaultt)\<`Default`\>\> -#### Example +#### Call Signature ```ts -import { useFlag } from '@reflag/vue-sdk'; +function useFlag(key: string, defaultValue: Default): ShallowRef> +``` -const { isEnabled, config, track, requestFeedback } = useFlag("huddles"); +Reactive direct values: Boolean/false by default, or infer a positional JSON default. -function StartHuddlesButton() { - const { isEnabled, config: { payload }, track } = useFlag("huddles"); - if (isEnabled) { - return ; -} -``` +### Type Parameters + + + + + + + + + + + + +
Type Parameter
+ +`Default` *extends* `object` \| [`FlagDefaultValue`](../../../supported-languages/vue-sdk/globals.md#flagdefaultvalue) + +
+ +### Parameters + + + + + + + + + + + + + + + + + + +
ParameterType
+ +`key` + + + +`string` + +
+ +`defaultValue` + + + +`Default` + +
+ +### Returns + +`ShallowRef`\<[`FlagValueFromDefault`](../../../supported-languages/vue-sdk/globals.md#flagvaluefromdefaultt)\<`Default`\>\> *** -### useIsLoading() +### useIsLoading() ```ts function useIsLoading(): Ref @@ -1278,11 +1180,11 @@ This composable returns a boolean value that indicates whether the Reflag client You can use this to check if the Reflag client is loading at any point in your application. Initially, the value will be true until the client is initialized. -#### Returns +#### Returns `Ref`\<`boolean`, `boolean`\> -#### Example +#### Example ```ts import { useIsLoading } from '@reflag/vue-sdk'; @@ -1294,18 +1196,18 @@ console.log(isLoading); *** -### useOnEvent() +### useOnEvent() ```ts function useOnEvent( - event: THookType, - handler: (arg0: HookArgs[THookType]) => void, + event: THookType, + handler: (arg0: HookArgs[THookType]) => void, client?: ReflagClient): void ``` Vue composable for listening to Reflag client events. -#### Type Parameters +#### Type Parameters @@ -1317,14 +1219,14 @@ Vue composable for listening to Reflag client events.
-`THookType` *extends* keyof [`HookArgs`](../browser-sdk/globals.md#hookargs) +`THookType` *extends* keyof [`HookArgs`](../../../supported-languages/browser-sdk/globals.md#hookargs)
-#### Parameters +#### Parameters @@ -1360,7 +1262,7 @@ The event to listen to.
-(`arg0`: [`HookArgs`](../browser-sdk/globals.md#hookargs)\[`THookType`\]) => `void` +(`arg0`: [`HookArgs`](../../../supported-languages/browser-sdk/globals.md#hookargs)\[`THookType`\]) => `void` @@ -1377,7 +1279,7 @@ The function to call when the event is triggered. -[`ReflagClient`](../browser-sdk/globals.md#reflagclient) +[`ReflagClient`](../../../supported-languages/browser-sdk/globals.md#reflagclient) @@ -1389,11 +1291,11 @@ The Reflag client to listen to. If not provided, the client will be retrieved fr
-#### Returns +#### Returns `void` -#### Example +#### Example ```ts import { useOnEvent } from '@reflag/vue-sdk'; @@ -1405,7 +1307,7 @@ useOnEvent("flagsUpdated", () => { *** -### useOptInFlags() +### useOptInFlags() ```ts function useOptInFlags(): UseOptInFlagsResult @@ -1416,18 +1318,15 @@ the current context. The loading state is only used with `ReflagBootstrappedProvider` while opt-in metadata is fetched on demand. Regular providers load opt-in metadata -with the initial flags; use [useIsLoading](globals.md#useisloading) for their loading state. - -If fetching opt-in metadata fails, loading ends without exposing an error. -Call `refresh()` on the client returned by [useClient](globals.md#useclient) to retry. +with the initial flags. -#### Returns +#### Returns -[`UseOptInFlagsResult`](globals.md#useoptinflagsresult) +[`UseOptInFlagsResult`](../../../supported-languages/vue-sdk/globals.md#useoptinflagsresult) *** -### useRequestFeedback() +### useRequestFeedback() ```ts function useRequestFeedback(): (options: RequestFeedbackData) => void @@ -1439,14 +1338,14 @@ This composable returns a function that can be used to trigger the feedback collection flow with the Reflag SDK. You can use this to prompt users for feedback at any point in your application. -#### Returns +#### Returns `Function` A function that requests feedback from the user. The function accepts: - `options`: An object containing feedback request options. -##### Parameters +### Parameters @@ -1464,18 +1363,18 @@ A function that requests feedback from the user. The function accepts:
-[`RequestFeedbackData`](../browser-sdk/globals.md#requestfeedbackdata) +[`RequestFeedbackData`](../../../supported-languages/browser-sdk/globals.md#requestfeedbackdata)
-##### Returns +### Returns `void` -#### Example +#### Example ```ts import { useRequestFeedback } from '@reflag/vue-sdk'; @@ -1491,7 +1390,7 @@ requestFeedback({ *** -### useSendFeedback() +### useSendFeedback() ```ts function useSendFeedback(): (opts: UnassignedFeedback) => Promise< @@ -1504,14 +1403,14 @@ Vue composable for sending feedback. This composable returns a function that can be used to send feedback to the Reflag SDK. You can use this to send feedback from your application. -#### Returns +#### Returns `Function` A function that sends feedback to the Reflag SDK. The function accepts: - `options`: An object containing feedback options. -##### Parameters +### Parameters @@ -1529,20 +1428,20 @@ A function that sends feedback to the Reflag SDK. The function accepts:
-[`UnassignedFeedback`](../browser-sdk/globals.md#unassignedfeedback) +[`UnassignedFeedback`](../../../supported-languages/browser-sdk/globals.md#unassignedfeedback)
-##### Returns +### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\< \| `undefined` \| [`Response`](https://developer.mozilla.org/docs/Web/API/Response)\> -#### Example +#### Example ```ts import { useSendFeedback } from '@reflag/vue-sdk'; @@ -1558,7 +1457,7 @@ sendFeedback({ *** -### useSetOptIn() +### useSetOptIn() ```ts function useSetOptIn(): (key: string, options: SetOptInOptions) => Promise< @@ -1568,16 +1467,11 @@ function useSetOptIn(): (key: string, options: SetOptInOptions) => Promise< Vue composable for setting whether the current user or company has opted into a flag. -Check the returned Response's `ok` property and catch promise rejections. -HTTP failures return a non-OK Response; offline mode, invalid arguments, or -missing scoped context return undefined. Confirmation failures can reject -after the membership changed remotely. See [ReflagClient.setOptIn](../browser-sdk/globals.md#setoptin). - -#### Returns +#### Returns `Function` -##### Parameters +### Parameters @@ -1607,14 +1501,14 @@ after the membership changed remotely. See [ReflagClient.setOptIn](../browser-sd
-[`SetOptInOptions`](globals.md#setoptinoptions) +[`SetOptInOptions`](../../../supported-languages/vue-sdk/globals.md#setoptinoptions)
-##### Returns +### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\< \| `undefined` @@ -1622,10 +1516,10 @@ after the membership changed remotely. See [ReflagClient.setOptIn](../browser-sd *** -### useTrack() +### useTrack() ```ts -function useTrack(): (eventName: string, attributes?: +function useTrack(): (eventName: string, attributes?: | null | Record) => Promise< | undefined @@ -1637,7 +1531,7 @@ Vue composable for tracking custom events. This composable returns a function that can be used to track custom events with the Reflag SDK. -#### Returns +#### Returns `Function` @@ -1645,7 +1539,7 @@ A function that tracks an event. The function accepts: - `eventName`: The name of the event to track. - `attributes`: (Optional) Additional attributes to associate with the event. -##### Parameters +### Parameters @@ -1682,13 +1576,13 @@ A function that tracks an event. The function accepts:
-##### Returns +### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\< \| `undefined` \| [`Response`](https://developer.mozilla.org/docs/Web/API/Response)\> -#### Example +#### Example ```ts import { useTrack } from '@reflag/vue-sdk'; @@ -1701,7 +1595,7 @@ track('button_clicked', { buttonName: 'Start Huddles' }); *** -### useUpdateCompany() +### useUpdateCompany() ```ts function useUpdateCompany(): (opts: {}) => Promise @@ -1713,14 +1607,14 @@ This composable returns a function that can be used to update the company context with the Reflag SDK. You can use this to update the company context at any point in your application. -#### Returns +#### Returns `Function` A function that updates the company context. The function accepts: - `opts`: An object containing the company context to update. -##### Parameters +### Parameters @@ -1745,11 +1639,11 @@ A function that updates the company context. The function accepts:
-##### Returns +### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> -#### Example +#### Example ```ts import { useUpdateCompany } from '@reflag/vue-sdk'; @@ -1762,7 +1656,7 @@ updateCompany({ id: "123", name: "Acme Inc." }); *** -### useUpdateOtherContext() +### useUpdateOtherContext() ```ts function useUpdateOtherContext(): (opts: {}) => Promise @@ -1774,14 +1668,14 @@ This composable returns a function that can be used to update the other context with the Reflag SDK. You can use this to update the other context at any point in your application. -#### Returns +#### Returns `Function` A function that updates the other context. The function accepts: - `opts`: An object containing the other context to update. -##### Parameters +### Parameters @@ -1806,11 +1700,11 @@ A function that updates the other context. The function accepts:
-##### Returns +### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> -#### Example +#### Example ```ts import { useUpdateOtherContext } from '@reflag/vue-sdk'; @@ -1823,7 +1717,7 @@ updateOtherContext({ id: "123", name: "Acme Inc." }); *** -### useUpdateUser() +### useUpdateUser() ```ts function useUpdateUser(): (opts: {}) => Promise @@ -1835,14 +1729,14 @@ This composable returns a function that can be used to update the user context with the Reflag SDK. You can use this to update the user context at any point in your application. -#### Returns +#### Returns `Function` A function that updates the user context. The function accepts: - `opts`: An object containing the user context to update. -##### Parameters +### Parameters @@ -1867,11 +1761,11 @@ A function that updates the user context. The function accepts:
-##### Returns +### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> -#### Example +#### Example ```ts import { useUpdateUser } from '@reflag/vue-sdk'; @@ -1882,12 +1776,14 @@ const updateUser = useUpdateUser(); updateUser({ id: "123", name: "John Doe" }); ``` -## References +## References + +### ReflagClientProvider -### ReflagClientProvider +Renames and re-exports [ReflagBootstrappedProvider](../../../supported-languages/vue-sdk/globals.md#reflagbootstrappedprovider) -Renames and re-exports [ReflagBootstrappedProvider](globals.md#reflagbootstrappedprovider) +### ReflagProvider -### ReflagProvider +Renames and re-exports [ReflagBootstrappedProvider](../../../supported-languages/vue-sdk/globals.md#reflagbootstrappedprovider) -Renames and re-exports [ReflagBootstrappedProvider](globals.md#reflagbootstrappedprovider) +Using v1? [Legacy docs](../../../legacy/v1/vue-sdk/globals.md) · [Upgrade guide](../../../supported-languages/migrating-from-v1.md). diff --git a/sdk/documents/browser-sdk/FEEDBACK.md b/sdk/documents/browser-sdk/FEEDBACK.md index 25ea4a0..880cd72 100644 --- a/sdk/documents/browser-sdk/FEEDBACK.md +++ b/sdk/documents/browser-sdk/FEEDBACK.md @@ -13,14 +13,16 @@ pagination: visible: true --- -# Reflag Feedback UI +# Reflag Feedback UI The Reflag Browser SDK includes a UI you can use to collect feedback from user about particular flags. ![image](https://github.com/reflagcom/javascript/assets/34348/c387bac1-f2e2-4efd-9dda-5030d76f9532) -## Global feedback configuration +This page covers SDK v2. + +## Global feedback configuration The Reflag Browser SDK feedback UI is configured with reasonable defaults, positioning itself as a [dialog](#dialog) in the lower right-hand corner of @@ -58,7 +60,7 @@ See also: - [Static language configuration](#static-language-configuration) if you want to translate the feedback UI, - [Automated feedback surveys](#automated-feedback-surveys) to override default configuration. -## Automated feedback surveys +## Automated feedback surveys Automated feedback surveys are enabled by default. @@ -72,7 +74,7 @@ browser, but you can intercept the request and override this behavior. The live connection for automated feedback is established when the `ReflagClient` is initialized. -### Disabling automated feedback surveys +### Disabling automated feedback surveys You can disable automated collection in the `ReflagClient` constructor: @@ -86,7 +88,7 @@ const reflag = new ReflagClient({ }); ``` -### Overriding prompt event defaults +### Overriding prompt event defaults If you are not satisfied with the default UI behavior when an automated prompt event arrives, you can can [override the global defaults](#global-feedback-configuration) @@ -127,7 +129,7 @@ See also: - [Use your own UI to collect feedback](#using-your-own-ui-to-collect-feedback) if the feedback UI doesn't match your design. -## Manual feedback collection +## Manual feedback collection To open up the feedback collection UI, call `reflagClient.requestFeedback(options)` with the appropriate options. This approach is particularly beneficial if you wish @@ -139,7 +141,7 @@ Examples of this could be if you want the click of a `give us feedback`-button or the end of a specific user flow, to trigger a pop-up displaying the feedback user interface. -### reflagClient.requestFeedback() options +### reflagClient.requestFeedback() options Minimal usage with defaults: @@ -180,13 +182,13 @@ See also: - [Runtime language configuration](#runtime-language-configuration) if you want to translate the feedback UI. -## Positioning and behavior +## Positioning and behavior The feedback UI can be configured to be placed and behave in 3 different ways: -### Positioning configuration +### Positioning configuration -#### Modal +#### Modal A modal overlay with a backdrop that blocks interaction with the underlying page. It can be dismissed with the keyboard shortcut `` or the dedicated @@ -206,7 +208,7 @@ position: { } ``` -#### Dialog +### Dialog A dialog that appears in a specified corner of the viewport, without limiting the user's interaction with the rest of the page. It can be dismissed with the dedicated @@ -236,7 +238,7 @@ position: { } ``` -#### Popover +#### Popover A popover that is anchored relative to a DOM-element (typically a button). It can be dismissed by clicking outside the popover or by pressing the dedicated close button. @@ -272,7 +274,7 @@ Popover feedback button example: ``` -## Internationalization (i18n) +## Internationalization (i18n) By default, the feedback UI is written in English. However, you can supply your own translations by passing an object in the options to either or both of the @@ -282,10 +284,10 @@ See examples below. ![image](https://github.com/reflagcom/javascript/assets/331790/68805b38-e9f6-4de5-9f55-188216983e3c) -See [default English localization keys](https://github.com/reflagcom/javascript/tree/main/packages/browser-sdk/src/feedback/ui/config/defaultTranslations.tsx) +See [default English localization keys](https://github.com/reflagcom/javascript/tree/ed0e7725719756855c20e939265713914e956b8b/packages/browser-sdk/src/feedback/ui/config/defaultTranslations.tsx) for a reference of what translation keys can be supplied. -### Static language configuration +### Static language configuration If you know the language at page load, you can configure your translation keys while initializing the Reflag Browser SDK: @@ -316,7 +318,7 @@ new ReflagClient({ }); ``` -### Runtime language configuration +### Runtime language configuration If you only know the user's language after the page has loaded, you can provide translations to either the `reflagClient.requestFeedback(options)` call or @@ -332,7 +334,7 @@ reflagClient.requestFeedback({ }) ``` -### Translations +### Translations When you are collecting feedback through the Reflag automation, you can intercept the default prompt handling and override the defaults. @@ -359,7 +361,7 @@ new ReflagClient({ }); ``` -## Custom styling +## Custom styling You can adapt parts of the look of the Reflag feedback UI by applying CSS custom properties to your page in your CSS `:root`-scope. @@ -396,9 +398,9 @@ For example, a dark mode theme might look like this: } ``` -Other examples of custom styling can be found in our [development example style-sheet](https://github.com/reflagcom/javascript/tree/main/packages/browser-sdk/src/feedback/ui/index.css). +Other examples of custom styling can be found in our [development example style-sheet](https://github.com/reflagcom/javascript/tree/ed0e7725719756855c20e939265713914e956b8b/packages/browser-sdk/src/feedback/ui/index.css). -## Using your own UI to collect feedback +## Using your own UI to collect feedback You may have very strict design guidelines for your app and maybe the Reflag feedback UI doesn't quite work for you. In this case, you can implement your own feedback @@ -418,10 +420,10 @@ type DataToCollect = { Either `score` or `comment` must be defined in order to pass validation in the Reflag API. -### Manual feedback collection with custom UI +### Manual feedback collection with custom UI Examples of a HTML-form that collects the relevant data can be found -in [feedback.html](https://github.com/reflagcom/javascript/tree/main/packages/browser-sdk/example/feedback/feedback.html) and [feedback.jsx](https://github.com/reflagcom/javascript/tree/main/packages/browser-sdk/example/feedback/Feedback.jsx). +in [feedback.html](https://github.com/reflagcom/javascript/tree/ed0e7725719756855c20e939265713914e956b8b/packages/browser-sdk/example/feedback/feedback.html) and [feedback.jsx](https://github.com/reflagcom/javascript/tree/ed0e7725719756855c20e939265713914e956b8b/packages/browser-sdk/example/feedback/Feedback.jsx). Once you have collected the feedback data, pass it along to `reflagClient.feedback()`: @@ -434,7 +436,7 @@ reflagClient.feedback({ }); ``` -### Intercepting automated feedback survey events +### Intercepting automated feedback survey events When using automated feedback surveys, the Reflag service will, when specified, send a feedback prompt message to your user's instance of the Reflag Browser SDK. @@ -471,3 +473,5 @@ new ReflagClient({ }, }); ``` + +Using v1? [Legacy docs](../../../legacy/v1/browser-sdk/feedback.md) · [Upgrade guide](../../../supported-languages/migrating-from-v1.md). diff --git a/sdk/documents/react-native-sdk/README.md b/sdk/documents/react-native-sdk/README.md index 16195f6..eba9bb0 100644 --- a/sdk/documents/react-native-sdk/README.md +++ b/sdk/documents/react-native-sdk/README.md @@ -13,23 +13,27 @@ pagination: visible: true --- -# Reflag React Native SDK +{% hint style="info" %} +**Independent SDK compatibility.** This React Native release uses React/Browser protocol v1. Follow the [matching React documentation](../../../legacy/v1/react-sdk/README.md) and use a [matching Node SDK](../../../legacy/v1/node-sdk/README.md) for bootstrap. Do not pass protocol-v2 bootstrap into a v1 consumer. +{% endhint %} + +# Reflag React Native SDK A thin React Native wrapper around `@reflag/react-sdk`. -For more usage details, see the [React SDK README](../react-sdk/README.md). +For more usage details, see the [React SDK README](../../../legacy/v1/react-sdk/README.md). -An Expo example app lives in [packages/react-native-sdk/dev/expo](https://github.com/reflagcom/javascript/tree/main/packages/react-native-sdk/dev/expo). +An Expo example app lives in [packages/react-native-sdk/dev/expo](https://github.com/reflagcom/javascript/tree/b4fe5b3d9386b87c6546175c323862d9878e1430/packages/react-native-sdk/dev/expo). -## Get started +## Get started -### Install +### Install ```shell npm i @reflag/react-native-sdk ``` -### 1. Add the ReflagProvider +### 1. Add the ReflagProvider Wrap your app with the provider from `@reflag/react-native-sdk`: @@ -47,7 +51,7 @@ import { ReflagProvider } from "@reflag/react-native-sdk"; ; ``` -### 2. Use `useFlag()` +### 2. Use `useFlag()` ```tsx import { useFlag } from "@reflag/react-native-sdk"; @@ -61,24 +65,24 @@ function StartHuddleButton() { } ``` -See the [React SDK README](../react-sdk/README.md) for more details. +See the [React SDK README](../../../legacy/v1/react-sdk/README.md) for more details. -## React Native differences +## React Native differences - The Reflag toolbar is web-only and is not available in React Native. - Built-in feedback UI is web-only. In React Native, use your own UI and call `useSendFeedback` or `client.feedback` when you're ready to send feedback. - Live flag updates work out of the box. The React Native SDK bundles an SSE transport via `react-native-sse`, so no global `EventSource` shim is required. - If you need custom SSE behavior, you can still override the transport by passing `eventSourceFactory` to `ReflagProvider` or `ReflagBootstrappedProvider`. -## Reference +## Reference The React Native SDK shares its API with the React SDK. Use the React SDK reference for full types and details: -[React SDK Reference](../react-sdk/README.md) +[React SDK Reference](../../../legacy/v1/react-sdk/README.md) -## Cookbook +## Cookbook -### Refresh flags when the app returns to the foreground +### Refresh flags when the app returns to the foreground Flags are updated if the context passed to `` changes, but you might also want to update them when the app comes to the foreground. See this snippet: @@ -119,7 +123,7 @@ export function App() { } ``` -## Suspense loading +## Suspense loading Enable `` support by setting the `suspense` prop on the provider and wrap components that call `useFlag` in a Suspense boundary: @@ -137,7 +141,7 @@ import { ReflagProvider } from "@reflag/react-native-sdk"; You can also override the behavior for one call with `useFlag("huddle", { suspense: true })`. -## Bootstrapping +## Bootstrapping You can use `` in React Native when you already have pre-fetched flags and want to avoid an initial fetch. Pass the full object returned by the Node SDK's `getFlagsForBootstrap()` directly as the provider's `flags` prop; it includes `context`, evaluated `flags`, and an optional `flagStateVersion`. @@ -146,4 +150,4 @@ If you want live flag updates to continue working after bootstrapping, use a rec After bootstrapping, any live flag updates are fetched directly by the client SDK from Reflag using the client-visible context. If your bootstrapped snapshot depends on server-only or secret context that is not available in the app, later live refreshes may differ. In that case, keep `enableLiveFlagUpdates` disabled. -For bootstrap usage patterns and options, see the [React SDK bootstrapping docs](../react-sdk/README.md). +For bootstrap usage patterns and options, see the [React SDK bootstrapping docs](../../../legacy/v1/react-sdk/README.md). diff --git a/sdk/documents/react-sdk/README.md b/sdk/documents/react-sdk/README.md index f9d2c2a..9678be2 100644 --- a/sdk/documents/react-sdk/README.md +++ b/sdk/documents/react-sdk/README.md @@ -13,966 +13,211 @@ pagination: visible: true --- -# Reflag React SDK +# Reflag React SDK -React client side library for [Reflag.com](https://reflag.com) +Feature flags, remote configuration, usage tracking and feedback for React applications. Built on the [Browser SDK](../../../supported-languages/browser-sdk/README.md). -Reflag supports flag toggling, tracking flag usage, [requesting feedback](#userequestfeedback) on features, and [remotely configuring flags](#remote-config). +This page covers SDK v2. -The Reflag React SDK comes with a [built-in toolbar](https://docs.reflag.com/supported-languages/browser-sdk#toolbar) which appears on `localhost` by default. +## Get started -## Install +### 1. Add the provider -Install via npm: +Install the SDK: -```shell -npm i @reflag/react-sdk +```sh +npm install @reflag/react-sdk ``` -## Get started - -### 1. Add the `ReflagProvider` context provider - -Add the `ReflagProvider` context provider to your application: - -**Example:** +Wrap your application in `ReflagProvider` with your **publishable** key and the signed-in user's context: ```tsx import { ReflagProvider } from "@reflag/react-sdk"; } > - {/* children here are shown when loading finishes or immediately if no `loadingComponent` is given */} + ; ``` -### 2. Create a new flag and set up type safety +### 2. Create a flag -Install the Reflag CLI: +Install the Reflag CLI and create a flag: -```shell -npm i --save-dev @reflag/cli +```sh +npm install --save-dev @reflag/cli +npx reflag new ``` -Run `npx reflag new` to create your first flag! -On the first run, it will sign into Reflag and set up type generation for your project: - -```shell -❯ npx reflag new -Opened web browser to facilitate login: https://app.reflag.com/api/oauth/cli/authorize - -Welcome to ◪ Reflag! - -? Where should we generate the types? gen/flags.d.ts -? What is the output format? react -✔ Configuration created at reflag.config.json. - -Creating flag for app Slick app. -? New flag name: Huddle -? New flag key: huddle -✔ Created flag Huddle with key huddle (https://app.reflag.com/features/huddles) -✔ Generated react types in gen/flags.d.ts. -``` +The first time you run it, it signs you in to Reflag, saves its settings in `reflag.config.json` and generates types for your flags in `gen/flags.d.ts`. Choose `react` when asked for the output format, and make sure your `tsconfig.json` includes the generated file. You can also create flags in the Reflag app. -> [!Note] -> By default, types will be generated in `gen/flags.d.ts`. -> The default `tsconfig.json` file `include`s this file by default, but if your `tsconfig.json` is different, make sure the file is covered in the `include` property. +### 3. Read the flag -### 3. Use `useFlag()` to get flag status - -Using the `useFlag` hook from your components lets you toggle flags on/off and track flag usage: - -**Example:** +Use `useFlag()` in any component: ```tsx -function StartHuddleButton() { - const { - isEnabled, // boolean indicating if the flag is enabled - track, // track usage of the flag - } = useFlag("huddle"); - - if (!isEnabled) { - return null; - } +import { useFlag, useTrack } from "@reflag/react-sdk"; - return ; +function Huddles() { + const enabled = useFlag("huddles"); + const track = useTrack(); + if (!enabled) return null; + return ; } ``` -`useFlag` can help you do much more. See a full example for `useFlag` [see below](#useflag). - -## Setting context +## Read flags -Reflag determines which flags are active for a given `user`, `company`, or `other` context. -You can pass these to the `ReflagProvider` using the `context` prop. - -### Using the `context` prop +Pass a flag key to check whether the flag is enabled: ```tsx - - - {/* children here are shown when loading finishes */} - - -``` - -### Legacy individual props (deprecated) - -For backward compatibility, you can still use individual props, but these are deprecated and will be removed in the next major version: - -```tsx - - - {/* children here are shown when loading finishes */} - - -``` - -> [!Important] -> The `user`, `company`, and `otherContext` props are deprecated. Use the `context` prop instead, which provides the same functionality in a more structured way. - -### Context requirements - -If you supply `user` or `company` objects, they must include at least the `id` property otherwise they will be ignored in their entirety. -In addition to the `id`, you must also supply anything additional that you want to be able to evaluate flag targeting rules against. -Attributes which are not properties of the `user` or `company` can be supplied using the `other` property. - -Attributes cannot be nested (multiple levels) and must be either strings, numbers or booleans. -A number of special attributes exist: - -- `name` -- display name for `user`/`company`, -- `email` -- the email of the user, -- `avatar` -- the URL for `user`/`company` avatar image. - -To retrieve flags along with their targeting information, use `useFlag(key: string)` hook (described in a section below). - -Note that accessing `isEnabled` on the object returned by `useFlag()` automatically -generates a `check` event. - -## React Native - -For React Native, use `@reflag/react-native-sdk`, which is a thin wrapper around -`@reflag/react-sdk` and wires up AsyncStorage by default. - -An Expo example app lives at `packages/react-native-sdk/dev/expo`. - -## Remote config - -Remote config is a dynamic and flexible approach to configuring flag behavior outside of your app – without needing to re-deploy it. - -Similar to `isEnabled`, each flag accessed using the `useFlag()` hook, has a `config` property. This configuration is managed from within Reflag. It is managed similar to the way access to flags is managed, but instead of the -binary `isEnabled` you can have multiple configuration values which are given to different user/companies. - -### Get started with Remote config - -1. Update your flag definitions: - -```typescript -import "@reflag/react-sdk"; - -// Define your flags by extending the `Flags` interface in @reflag/react-sdk -declare module "@reflag/react-sdk" { - interface Flags { - huddle: { - // change from `boolean` to an object which sets - // a type for the remote config for `questionnaire` - maxTokens: number; - model: string; - }; - } -} -``` - -```ts -const { - isEnabled, - config: { key, payload }, -} = useFlag("huddles"); - -// isEnabled: true, -// key: "gpt-3.5", -// payload: { maxTokens: 10000, model: "gpt-3.5-beta1" } -``` - -`key` is mandatory for a config, but if a flag has no config or no config value was matched against the context, the `key` will be `undefined`. Make sure to check against this case when trying to use the configuration in your application. `payload` is an optional JSON value for arbitrary configuration needs. - -Note that, similar to `isEnabled`, accessing `config` on the object returned by `useFlag()` automatically -generates a `check` event. - -## Toolbar - -The Reflag Toolbar is great for toggling flags on/off for yourself to ensure that everything works both when a flag is on and when it's off. - -Toolbar - -The toolbar will automatically appear on `localhost`. However, it can also be incredibly useful in production. You have full control over when it appears through the `toolbar` configuration option passed to the ReflagProvider. - -You can pass a simple boolean to force the toolbar to appear/disappear: - -```ts -` component is a specialized version of `ReflagProvider` designed for server-side rendering, preloaded flag scenarios, and high-reliability setups. It uses pre-fetched evaluated state for the initial render, resulting in faster initial page loads, better SSR compatibility, and a more resilient startup path for React applications. +To read a configuration value, pass a default as the second argument. You get back a value of the same type as the default: ```tsx -import { useState, useEffect } from "react"; -import { BootstrappedFlags } from "@reflag/react-sdk"; - -interface BootstrapData { - user: User; - flags: BootstrappedFlags; -} - -function useBootstrap() { - const [data, setData] = useState(null); - - useEffect(() => { - fetch("/bootstrap") - .then((res) => res.json()) - .then(setData); - }, []); - - return data; -} - -// Usage in your app -function App() { - const { user, flags } = useBootstrap(); - - return ( - - - - - - ); -} -``` - -### Server-side endpoint setup - -Create an endpoint that provides bootstrap data to your client application: - -```typescript -// server.js or your Express app -import { ReflagClient as ReflagNodeClient } from "@reflag/node-sdk"; - -const reflagClient = new ReflagNodeClient({ - secretKey: process.env.REFLAG_SECRET_KEY, -}); -await reflagClient.initialize(); - -app.get("/bootstrap", (req, res) => { - const user = getUser(req); // Get user from your auth system - const company = getCompany(req); // Get company from your auth system - - const flags = reflagClient.getFlagsForBootstrap({ - user: { id: "user123", name: "John Doe", email: "john@acme.com" }, - company: { id: "company456", name: "Acme Inc", plan: "enterprise" }, - other: { source: "web" }, - }); - - res.status(200).json({ - user, - flags, - }); -}); -``` - -The `flags` object returned by `getFlagsForBootstrap()` contains the full bootstrapped state package: - -- `context`: the evaluation context used on the server -- `flags`: the evaluated raw flags -- `flagStateVersion`: an optional version used to avoid redundant live-update refreshes immediately after bootstrapping - -If you want live flag updates to continue working after bootstrapping, use a recent `@reflag/node-sdk` so `getFlagsForBootstrap()` includes `flagStateVersion`. - -### Next.js Page Router SSR example - -For Next.js applications using server-side rendering, you can pre-fetch flags in `getServerSideProps`: - -```typescript -// pages/index.tsx -import { GetServerSideProps } from "next"; -import { ReflagClient as ReflagNodeClient } from "@reflag/node-sdk"; -import { ReflagBootstrappedProvider, BootstrappedFlags, useFlag } from "@reflag/react-sdk"; - -interface PageProps { - bootstrapData: BootstrappedFlags; -} - -export const getServerSideProps: GetServerSideProps = async (context) => { - const serverClient = new ReflagNodeClient({ - secretKey: process.env.REFLAG_SECRET_KEY - }); - await serverClient.initialize(); - - const user = await getUserFromSession(context.req); - const company = await getCompanyFromUser(user); - - const bootstrapData = serverClient.getFlagsForBootstrap({ - user: { id: "user123", name: "John Doe", email: "john@acme.com" }, - company: { id: "company456", name: "Acme Inc", plan: "enterprise" }, - other: { page: "homepage" } - }); - - return { props: { bootstrapData } }; -}; - -export default function HomePage({ bootstrapData }: PageProps) { - return ( - - - - ); -} - -function HuddleFeature() { - const { isEnabled, track, config } = useFlag("huddle"); - - if (!isEnabled) return null; - - return ( -
-

Start a Huddle

-

Max participants: {config.payload?.maxParticipants ?? 10}

-

Video quality: {config.payload?.videoQuality ?? "standard"}

- -
- ); -} -``` - -This approach eliminates loading states and removes the initial render's dependency on the flags API. - -### Next.js App Router example - -For Next.js applications using the App Router (Next.js 13+), you can pre-fetch flags in Server Components and pass them to client components: - -```typescript -// app/layout.tsx (Server Component) -import { ReflagClient as ReflagNodeClient } from "@reflag/node-sdk"; -import { ClientProviders } from "./providers"; - -async function getBootstrapData() { - const serverClient = new ReflagNodeClient({ - secretKey: process.env.REFLAG_SECRET_KEY! - }); - await serverClient.initialize(); - - // In a real app, you'd get user/company from your auth system - const bootstrapData = serverClient.getFlagsForBootstrap({ - user: { id: "user123", name: "John Doe", email: "john@acme.com" }, - company: { id: "company456", name: "Acme Inc", plan: "enterprise" }, - other: { source: "web" } - }); - - return bootstrapData; -} - -export default async function RootLayout({ - children, -}: { - children: React.ReactNode; -}) { - const bootstrapData = await getBootstrapData(); - - return ( - - - - {children} - - - - ); -} -``` - -```typescript -// app/providers.tsx (Client Component) -"use client"; - -import { ReflagBootstrappedProvider, BootstrappedFlags } from "@reflag/react-sdk"; - -interface ClientProvidersProps { - children: React.ReactNode; - bootstrapData: BootstrappedFlags; -} - -export function ClientProviders({ children, bootstrapData }: ClientProvidersProps) { - return ( - - {children} - - ); -} -``` - -```typescript -// app/page.tsx (Server Component) -import { HuddleFeature } from "./huddle-feature"; - -export default function HomePage() { - return ( -
-

My App

- -
- ); -} +const model = useFlag("model", "quick"); // string +const settings = useFlag("huddle-settings", { maxParticipants: 10 }); // { maxParticipants: number } ``` -```typescript -// app/huddle-feature.tsx (Client Component) -"use client"; +While flags are loading, if the flag doesn't exist, or if its value has a different type, you get `false`, or your default if you passed one. Pass `null` as the default to accept any JSON value and narrow it yourself. -import { useFlag } from "@reflag/react-sdk"; +The SDK checks only the top-level type of a value. If your application depends on nested fields, validate them. -export function HuddleFeature() { - const { isEnabled, track, config } = useFlag("huddle"); +Each read records a check, which Reflag uses for launch monitoring. - if (!isEnabled) return null; +## Loading states and Suspense - return ( -
-

Start a Huddle

-

Max participants: {config.payload?.maxParticipants ?? 10}

-

Video quality: {config.payload?.videoQuality ?? "standard"}

- -
- ); -} -``` - -This App Router approach leverages Server Components for server-side flag fetching while using Client Components only where React state and hooks are needed. - -## `` component - -The `` is a lower-level component that accepts a `ReflagClient` instance. This is useful for advanced use cases where you need full control over client initialization or want to share a client instance across multiple parts of your application. - -In most cases you should initialize the client before rendering this provider. If you pass an idle client and enable `suspense`, a `useFlag()` call that suspends can initialize the client on demand; without Suspense, you must initialize the client yourself. - -### Usage +`useFlag()` returns immediately and never suspends. To show a loading UI, use `useIsLoading()` or the provider's `loadingComponent` prop: ```tsx -import { ReflagClient } from "@reflag/browser-sdk"; -import { ReflagClientProvider } from "@reflag/react-sdk"; - -// Initialize the client yourself -const client = new ReflagClient({ - publishableKey: "your-publishable-key", - user: { id: "user123", name: "John Doe" }, - company: { id: "company456", name: "Acme Inc" }, - // ... other configuration options -}); - -// Initialize the client -await client.initialize(); - -function App() { - return ( - }> - - - ); -} +} +> + + ``` -### Props - -The `ReflagClientProvider` accepts the following props: - -- `client`: A `ReflagClient` instance. Prefer passing an already-initialized client; idle clients are initialized on demand only by suspense-enabled `useFlag()` calls. -- `loadingComponent`: Optional React component to show while the client is initializing (same as `ReflagProvider`) -- `suspense`: Optional. Set to `true` to make `useFlag()` suspend while the client is loading - -> [!Note] -> Most applications should use `ReflagProvider` or `ReflagBootstrappedProvider` instead of `ReflagClientProvider`. Only use this component when you need the advanced control it provides. - -## `` component - -The `` initializes the Reflag SDK, fetches flags and starts listening for automated feedback survey events. The component can be configured using a number of props: - -- `publishableKey` is used to connect the provider to an _environment_ on Reflag. Find your `publishableKey` under [environment settings](https://app.reflag.com/env-current/settings/app-environments) in Reflag, -- `context` (recommended): An object containing `user`, `company`, and `other` properties that make up the evaluation context used to determine if a flag is enabled or not. `company` and `user` contexts are automatically transmitted to Reflag servers so the Reflag app can show you which companies have access to which flags etc. -- `company`, `user` and `other` (deprecated): Individual props for context. These are deprecated in favor of the `context` prop and will be removed in the next major version. - > [!Note] - > If you specify `company` and/or `user` they must have at least the `id` property, otherwise they will be ignored in their entirety. You should also supply anything additional you want to be able to evaluate flag targeting against, -- `fallbackFlags`: A list of strings which specify which flags to consider enabled if the SDK is unable to fetch flags. Can be provided in two formats: - - ```ts - // Simple array of flag keys - fallbackFlags={["flag1", "flag2"]} - - // Or with configuration overrides - fallbackFlags: { - "flag1": true, // just enable the flag - "flag2": { // enable with configuration - key: "variant-a", - payload: { - limit: 100, - mode: "test" - } - } - } - ``` - -- `timeoutMs`: Timeout in milliseconds when fetching flags from the server. -- `staleWhileRevalidate`: If set to `true`, stale flags will be returned while refetching flags in the background. -- `expireTimeMs`: If set, flags will be cached between page loads for this duration (in milliseconds). -- `staleTimeMs`: Maximum time (in milliseconds) that stale flags will be returned if `staleWhileRevalidate` is true and new flags cannot be fetched. -- `offline`: Provide this option when testing or in local development environments to avoid contacting Reflag servers. -- `loadingComponent` lets you specify an React component to be rendered instead of the children while the Reflag provider is initializing. If you want more control over loading screens, `useFlag()` and `useIsLoading` returns `isLoading` which you can use to customize the loading experience. -- `suspense`: Set to `true` to make `useFlag()` suspend while the provider is loading and `useOptInFlags()` suspend while required opt-in metadata is loading. Wrap components that call these hooks in React `` boundaries and omit `loadingComponent` if you want Suspense fallbacks to control loading UI. -- `enableTracking`: Set to `false` to stop sending tracking events and user/company updates to Reflag. Useful when you're impersonating a user (defaults to `true`), -- `enableLiveFlagUpdates`: Enables live flag updates over SSE. Defaults to `true` in the React SDK. -- `apiBaseUrl`: Optional base URL for the Reflag API. This also controls the SSE origin used for live flag updates and automated feedback, -- `credentials`: Optional fetch credentials mode. Set to `"include"` when proxying through your backend and authenticating with cookies; this also enables credentials for live-update SSE connections. -- `appBaseUrl`: Optional base URL for the Reflag application. Use this to override the default app URL, - -- `logger`: Optional custom logger implementation (`debug`, `info`, `warn`, `error`) used by the underlying client, -- `debug`: Set to `true` to enable debug logging to the console. If both `logger` and `debug` are provided, `logger` takes precedence, -- `toolbar`: Optional [configuration](https://docs.reflag.com/supported-languages/browser-sdk/globals#toolbaroptions) for the Reflag toolbar, -- `feedback`: Optional configuration for feedback collection - -## `` component - -The `` is a specialized version of the `ReflagProvider` that uses pre-fetched flag data for the initial render. This is ideal for server-side rendering scenarios. - -The component accepts the following props: - -- `flags`: Pre-fetched bootstrapped state of type `BootstrappedFlags` obtained from the Node SDK's `getFlagsForBootstrap()` method. This contains the context (`flags.context`), the evaluated flags (`flags.flags`), and an optional `flags.flagStateVersion`. -- All other props available in [`ReflagProvider`](#reflagprovider-component) are supported except `context`, `user`, `company`, and `other` (which are extracted from `flags.context`). - -**Example:** +To wait for flags with React Suspense, use `useFlagSuspense()`. It takes the same arguments as `useFlag()`: ```tsx -import { - ReflagBootstrappedProvider, - BootstrappedFlags, -} from "@reflag/react-sdk"; +import { Suspense } from "react"; +import { useFlagSuspense } from "@reflag/react-sdk"; -interface AppProps { - bootstrapData: BootstrappedFlags; +function Model() { + const model = useFlagSuspense("model", "quick"); + return {model}; } -function App({ bootstrapData }: AppProps) { - return ( - } - debug={process.env.NODE_ENV === "development"} - > - - - ); -} +Loading flags…}> + +; ``` -> [!Note] -> When using `ReflagBootstrappedProvider`, pass the entire object returned by `getFlagsForBootstrap()` directly as the `flags` prop. The context is extracted from `flags.context`, and `flags.flagStateVersion` is used when present. -> -> With `ReflagBootstrappedProvider`, `useOptInFlags()` requests a flags refresh on first use. It returns `isLoading: true` (or suspends) until that refresh settles. -> -> If you want live flag updates to continue working after bootstrapping, use a recent `@reflag/node-sdk` so `getFlagsForBootstrap()` includes `flagStateVersion`. -> -> After bootstrapping, any live flag updates are fetched directly by the browser SDK from Reflag using the browser-visible context. If your bootstrapped snapshot depends on server-only or secret context that is not available in the browser, later live refreshes may differ. In that case, keep `enableLiveFlagUpdates` disabled. -> -> Requesting opt-in flags also triggers a browser-side refresh, even when `enableLiveFlagUpdates` is disabled. - -## Hooks - -### `useFlag()` - -Returns the state of a given flag for the current context. The hook provides type-safe access to flags and their configurations. +## Track usage and feedback ```tsx -import { useFlag } from "@reflag/react-sdk"; -import { Loading } from "./Loading"; - -function StartHuddleButton() { - const { - isLoading, // true while flags are being loaded - isEnabled, // boolean indicating if the flag is enabled - config: { - // flag configuration - key, // string identifier for the config variant - payload, // type-safe configuration object - }, - track, // function to track flag usage - requestFeedback, // function to request feedback for this flag - } = useFlag("huddle"); - - if (isLoading) { - return ; - } +const track = useTrack(); +await track("Started huddle", { button: "cta" }); - if (!isEnabled) { - return null; - } - - return ( - <> - - - - ); -} -``` - -#### Suspense loading - -Enable `suspense` on the provider to have `useFlag()` throw a promise while `isLoading` is true. The nearest `` boundary will render its fallback until flags are ready. - -```tsx -import { Suspense } from "react"; -import { ReflagProvider } from "@reflag/react-sdk"; +const requestFeedback = useRequestFeedback(); +requestFeedback({ flagKey: "huddles", title: "How did it go?" }); - - }> - - -; +const sendFeedback = useSendFeedback(); +await sendFeedback({ flagKey: "huddles", score: 5 }); ``` -You can also opt in for a single call with `useFlag("huddle", { suspense: true })`, or opt out inside a suspense-enabled provider with `{ suspense: false }`. +Configure your flag's adoption rules to match the event names you send. See the [Browser feedback documentation](../../../supported-languages/browser-sdk/feedback.md) to configure feedback prompts and the feedback UI. -### `useOptInFlags()` and `useSetOptIn()` +## Update context -Use these hooks to build an end-user opt-in UI for flags where opt-in is enabled in Reflag. +`useUpdateUser()`, `useUpdateCompany()` and `useUpdateOtherContext()` return functions that merge new attributes into the current context. To replace the whole context, call `useClient().setContext(context)`. Flag values are refetched for the new context. -```tsx -import { - type OptInFlag, - useIsLoading, - useOptInFlags, - useSetOptIn, -} from "@reflag/react-sdk"; - -function OptInList() { - const isProviderLoading = useIsLoading(); - const { flags, isLoading } = useOptInFlags(); - const setOptIn = useSetOptIn(); - - async function toggleOptIn(flag: OptInFlag) { - try { - const response = await setOptIn(flag.key, { - optedIn: !flag.userOptedIn, - }); - if (!response?.ok) { - console.error("Could not update opt-in"); - } - } catch (error) { - console.error("Could not update opt-in", error); - } - } +## Bootstrap from the server - if (isProviderLoading || isLoading) { - return

Loading…

; - } +To render flags immediately, without waiting for a network request, evaluate them on your server with the **Node.js SDK**: - return flags.map((flag) => ( - - )); -} +```ts +const flags = serverClient.getFlagsForBootstrap(context); ``` -By default, `useSetOptIn()` changes the opt-in for the current user, so the current context must include a `user.id`. To manage the current company's opt-in instead, pass `scope: "company"`; the context must then include a `company.id`. - -User and company opt-ins are managed independently. Setting `optedIn` to `false` removes the opt-in only for the selected scope. For example, cancelling a user's opt-in does not change the company's opt-in for the same flag. - -`setOptIn` returns a promise so you can wait for the new membership state to be synchronized. On success, it resolves after the refreshed flag state has been applied locally, the requested membership change has been confirmed, and subscribers have been notified when flags change. React may not have committed the resulting render yet. - -The promise resolves to a `Response`, or `undefined` if skipped due to invalid input, offline mode etc. Check `response?.ok` for success. - -`useOptInFlags()` returns `{ flags, isLoading }`. With `ReflagBootstrappedProvider`, it fetches opt-in metadata on first use and reports `isLoading: true` until that refresh succeeds or fails. - -If fetching opt-in metadata fails, loading ends without exposing an error. Call `client.refresh()` on the client returned by `useClient()` to retry. - -With a regular `ReflagProvider`, opt-in metadata arrives as part of the normal initial flags request, so `useOptInFlags().isLoading` remains `false`. Use the general `useIsLoading()` hook or the provider's `loadingComponent` for that initial loading state. - -`useOptInFlags()` also supports Suspense. It respects the provider-level `suspense` option, or you can enable it for only this hook with `useOptInFlags({ suspense: true })`. While required opt-in metadata is loading, the nearest `` boundary renders its fallback: +Then pass the whole result to `ReflagBootstrappedProvider`, serialized with your framework's usual mechanism: ```tsx -import { Suspense } from "react"; +import { ReflagBootstrappedProvider } from "@reflag/react-sdk"; - - }> - - + + ; ``` -Opt-in metadata Suspense is primarily relevant with `ReflagBootstrappedProvider`. Use `useOptInFlags({ suspense: false })` to opt out for one call when Suspense is enabled on the provider. +Leave secrets and server-only attributes out of the context you bootstrap, because the browser can read it. Later refreshes evaluate flags using the browser's context. If values that depend on server-only attributes must not change, set `enableLiveFlagUpdates={false}`. -### `useTrack()` - -`useTrack()` lets you send custom events to Reflag. Use this whenever a user _uses_ a feature. These events can be used to analyze feature usage in Reflag. +## Let users opt in to flags ```tsx -import { useTrack } from "@reflag/react-sdk"; - -function StartHuddle() { - const { track } = useTrack(); -
- -
; -} -``` - -### `useRequestFeedback()` - -`useRequestFeedback()` returns a function that lets you open up a dialog to ask for feedback on a specific feature. This is useful for collecting targeted feedback about specific features as part of roll out. See [Automated Feedback Surveys](https://docs.reflag.com/product-handbook/live-satisfaction) for how to do this automatically, without code. +const { flags, isLoading } = useOptInFlags(); +const setOptIn = useSetOptIn(); -When using the `useRequestFeedback` you must pass the flag key to `requestFeedback`. -The example below shows how to use `position` to ensure the popover appears next to the "Give feedback!" button. - -```tsx -import { useRequestFeedback } from "@reflag/react-sdk"; - -function FeedbackButton() { - const requestFeedback = useRequestFeedback(); - return ( - - ); -} +await setOptIn("huddles", { optedIn: true }); +await setOptIn("huddles", { optedIn: false, scope: "company" }); ``` -See the [Feedback Documentation](https://github.com/reflagcom/javascript/blob/main/packages/browser-sdk/FEEDBACK.md#manual-feedback-collection) for more information on `requestFeedback` options. - -### `useSendFeedback()` - -Returns a function that lets you send feedback to Reflag. This is useful if you've manually collected feedback through your own UI and want to send it to Reflag. - -```tsx -import { useSendFeedback } from "@reflag/react-sdk"; - -function CustomFeedbackForm() { - const sendFeedback = useSendFeedback(); - - const handleSubmit = async (data: FormData) => { - await sendFeedback({ - flagKey: "reflag-flag-key", - score: parseInt(data.get("score") as string), - comment: data.get("comment") as string, - }); - }; +Each entry includes the flag's `key`, `name`, `description` and whether the user or company has opted in. User and company opt-ins are independent. Check `isLoading` before rendering an empty state. The provider's `suspense` prop, or `useOptInFlags({ suspense: true })`, makes this hook suspend instead. See [Beta feature opt-in](https://docs.reflag.com/guides/self-opt-in) for a complete example. - return
...
; -} -``` +## Overrides and toolbar -### `useUpdateUser()`, `useUpdateCompany()` and `useUpdateOtherContext()` - -These hooks return functions that let you update the attributes for the currently set user, company, or other context. Updates to user/company are stored remotely and affect flag targeting, while "other" context updates only affect the current session. +The toolbar shows on `localhost` by default and lets you toggle Boolean flags for yourself. Use the `toolbar` prop to show it elsewhere, for example to internal users in production: ```tsx -import { - useUpdateUser, - useUpdateCompany, - useUpdateOtherContext, -} from "@reflag/react-sdk"; - -function FlagOptIn() { - const updateUser = useUpdateUser(); - const updateCompany = useUpdateCompany(); - const updateOtherContext = useUpdateOtherContext(); - - const handleUserUpdate = async () => { - await updateUser({ - role: "admin", - betaFlags: "enabled", - }); - }; - - const handleCompanyUpdate = async () => { - await updateCompany({ - plan: "enterprise", - employees: 500, - }); - }; - - const handleContextUpdate = async () => { - await updateOtherContext({ - currentWorkspace: "workspace-123", - theme: "dark", - }); - }; - - return ( -
- - - -
- ); -} -``` - -### `useClient()` - -Returns the `ReflagClient` used by the `ReflagProvider`. The client offers more functionality that -is not directly accessible thorough the other hooks. - -```tsx -import { useClient } from "@reflag/react-sdk"; - -function LoggingWrapper({ children }: { children: ReactNode }) { - const client = useClient(); - - console.log(client.getContext()); - - return children; -} + + + ``` -### `useIsLoading()` +To override a flag from code, call `useClient().setFlagOverride(key, value)`. Pass `undefined` to remove the override. -Returns the loading state of the flags in the `ReflagClient`. -Initially, the value will be `true` if no bootstrap flags have been provided and the client has not be initialized. +## Type safety -```tsx -import { useIsLoading } from "@reflag/react-sdk"; -import { Spinner } from "./Spinner"; +Declaring your flags gives you autocompletion for keys and type checks for defaults. If you created a flag with `npx reflag new`, the declarations are already generated; run `npx reflag flags types` again when your flags change. A declaration looks like this: -function LoadingWrapper({ children }: { children: ReactNode }) { - const isLoading = useIsLoading(); +```ts +import "@reflag/react-sdk"; - if (isLoading) { - return ; +declare module "@reflag/react-sdk" { + interface Flags { + huddles: boolean; + "huddle-settings": { maxParticipants: number }; } - - return children; -} -``` - -### `useOnEvent()` - -Attach a callback handler to client events to act on changes. It automatically disposes itself on unmount. - -```tsx -import { useOnEvent } from "@reflag/react-sdk"; - -function LoggingWrapper({ children }: { children: ReactNode }) { - useOnEvent("flagsUpdated", (newFlags) => { - console.log(newFlags); - }); - - return children; } ``` -## Migrating from Bucket SDK - -If you have been using the Bucket SDKs, the following list will help you migrate to Reflag SDK: - -- `Bucket*` classes, and types have been renamed to `Reflag*` (e.g. `BucketClient` is now `ReflagClient`) -- `Feature*` classes, and types have been renamed to `Flag*` (e.g. `Feature` is now `Flag`, `RawFeatures` is now `RawFlags`) -- When using strongly-typed flags, the new `Flags` interface replaced `Features` interface -- All methods that contained `feature` in the name have been renamed to use the `flag` terminology (e.g. `getFeature` is `getFlag`) -- The `fallbackFeatures` property in client constructor and configuration files has been renamed to `fallbackFlags` -- `featureKey` has been renamed to `flagKey` in all methods that accepts that argument -- The SDKs will not emit `evaluate` and `evaluate-config` events anymore -- The new cookies that are stored in the client's browser are now `reflag-*` prefixed instead of `bucket-*` -- The `featuresUpdated` hook has been renamed to `flagsUpdated` -- The `checkIsEnabled` and `checkConfig` hooks have been removed, use `check` from now on - -To ease in transition to Reflag SDK, some of the old methods have been preserved as aliases to the new methods: +Declarations are checked at compile time only. See the [Reflag CLI](https://docs.reflag.com/api/cli) for more options. -- `getFeature` method is an alias for `getFlag` -- `getFeatures` method is an alias for `getFlags` -- `useFeature` method is an alias for `useFlag` -- `featuresUpdated` hook is an alias for `flagsUpdated` +## Use an existing client -If you are running with strict Content Security Policies active on your website, you will need change them as follows: +`useClient()` returns the underlying Browser SDK client. If you already create a Browser SDK client yourself, pass it to ``; your application is then responsible for initializing and stopping it. -- `connect-src https://front.bucket.co` to `connect-src https://front.reflag.com` +## Events -## Content Security Policy (CSP) +`useOnEvent(type, handler)` subscribes to [client events](../../../supported-languages/browser-sdk/README.md) and unsubscribes when the component unmounts. -See [CSP](https://github.com/reflagcom/javascript/blob/main/packages/browser-sdk/README.md#content-security-policy-csp) for info on using Reflag React SDK with CSP +## Configuration -## License +The provider accepts the Browser SDK's configuration options, such as `fallbackFlags`, `enableTracking`, `offline`, `feedback` and `logger`, as props. Live updates are on by default in React; set `enableLiveFlagUpdates={false}` to turn them off. Set `debug` to log to the console. -MIT License +For Content Security Policy requirements and the full list of options, see the [Browser SDK](../../../supported-languages/browser-sdk/README.md). -Copyright (c) 2025 Bucket ApS +Using v1? [Legacy docs](../../../legacy/v1/react-sdk/README.md) · [Upgrade guide](../../../supported-languages/migrating-from-v1.md). diff --git a/supported-languages/browser-sdk/README.md b/supported-languages/browser-sdk/README.md index 162250d..c9ccd8b 100644 --- a/supported-languages/browser-sdk/README.md +++ b/supported-languages/browser-sdk/README.md @@ -1,609 +1,195 @@ --- +layout: + visible: true title: visible: true +description: + visible: false tableOfContents: visible: true outline: visible: true pagination: visible: true -layout: - width: default - title: - visible: true - description: - visible: true - tableOfContents: - visible: true - outline: - visible: true - pagination: - visible: true - metadata: - visible: true - tags: - visible: true - actions: - visible: true - anchors: - visible: true --- -# Browser SDK - -Basic client for [Reflag.com](https://reflag.com). If you're using React, you'll be better off with the Reflag React SDK. - -Reflag supports flag toggling, tracking flag usage, [collecting feedback](./#qualitative-feedback-on-beta-flags) on flags, and [remotely configuring flags](./#remote-config). - -## Install - -First find your `publishableKey` under [environment settings](https://app.reflag.com/env-current/settings/app-environments) in Reflag. - -The package can be imported or used directly in a HTML script tag: - -A. Import module: - -```typescript -import { ReflagClient } from "@reflag/browser-sdk"; - -const user = { - id: 42, - role: "manager", -}; - -const company = { - id: 99, - plan: "enterprise", -}; - -const reflagClient = new ReflagClient({ publishableKey, user, company }); - -await reflagClient.initialize(); - -const { - isEnabled, - config: { payload: question }, - track, - requestFeedback, -} = reflagClient.getFlag("huddle"); - -if (isEnabled) { - // Show flag. When retrieving `isEnabled` the client automatically - // sends a "check" event for the "huddle" flag which is shown in the - // Reflag UI. - - // On usage, call `track` to let Reflag know that a user interacted with the flag - track(); - - // The `payload` is a user-supplied JSON in Reflag that is dynamically picked - // out depending on the user/company. - const question = payload?.question ?? "Tell us what you think of Huddles"; - - // Use `requestFeedback` to create "Send feedback" buttons easily for specific - // flags. This is not related to `track` and you can call them individually. - requestFeedback({ title: question }); -} - -// `track` just calls `reflagClient.track()` to send an event using the same flag key -// You can also use `track` on the client directly to send any custom event. -reflagClient.track("huddle"); - -// similarly, `requestFeedback` just calls `reflagClient.requestFeedback({flagKey: })` -// which you can also call directly: -reflagClient.requestFeedback({ flagKey: "huddle" }); -``` - -B. Script tag (client-side directly in html) - -See [example/browser.html](https://github.com/reflagcom/javascript/tree/main/packages/browser-sdk/example/browser.html) for a working example: - -```html - - -Loading... - -``` - -### Init options - -Supply these to the constructor call: - -```typescript -type Configuration = { - logger: console; // by default only logs warn/error, by passing `console` you'll log everything - apiBaseUrl?: "https://front.reflag.com"; - credentials?: "include" | "same-origin" | "omit"; // forwarded to fetch requests; "include" also enables credentials for the default EventSource transport - feedback?: undefined; // See FEEDBACK.md - enableTracking?: true; // set to `false` to stop sending track events and user/company updates to Reflag servers. Useful when you're impersonating a user - enableLiveFlagUpdates?: false; // Set to `true` to keep flags up to date over SSE (browser SDK default: false) - eventSourceFactory?: (url: string) => { - // Advanced: provide a custom EventSource-compatible transport - addEventListener: (type: string, cb: (event: any) => void) => void; - close: () => void; - }; - fallbackFlags?: - | string[] - | Record; // Enable these flags if unable to contact reflag.com. Can be a list of flag keys or a record with configuration values - timeoutMs?: number; // Timeout for fetching flags (default: 5000ms) - staleWhileRevalidate?: boolean; // Revalidate in the background when cached flags turn stale to avoid latency in the UI (default: false) - staleTimeMs?: number; // at initialization time flags are loaded from the cache unless they have gone stale. Defaults to 0 which means the cache is disabled. Increase this in the case of a non-SPA - expireTimeMs?: number; // In case we're unable to fetch flags from Reflag, cached/stale flags will be used instead until they expire after `expireTimeMs`. Default is 30 days - offline?: boolean; // Use the SDK in offline mode. Offline mode is useful during testing and local development -}; -``` - -## Migrating from Bucket SDK - -If you have been using the Bucket SDKs, the following list will help you migrate to Reflag SDK: - -* `Bucket*` classes, and types have been renamed to `Reflag*` (e.g. `BucketClient` is now `ReflagClient`) -* `Feature*` classes, and types have been renamed to `Feature*` (e.g. `Feature` is now `Flag`, `RawFeatures` is now `RawFlags`) -* All methods that contained `feature` in the name have been renamed to use the `flag` terminology (e.g. `getFeature` is `getFlag`) -* The `fallbackFeatures` property in client constructor and configuration files has been renamed to `fallbackFlags` -* `featureKey` has been renamed to `flagKey` in all methods that accepts that argument -* The new cookies that are stored in the client's browser are now `reflag-*` prefixed instead og `bucket-*` -* The `featuresUpdated` hook has been renamed to `flagsUpdated` -* The `checkIsEnabled` and `checkConfig` hooks have been removed, use `check` from now on - -To ease in transition to Reflag SDK, some of the old methods have been preserved as aliases to the new methods: +# Reflag Browser SDK -* `getFeature` method is an alias for `getFlag` -* `getFeatures` method is an alias for `getFlags` -* `featuresUpdated` hook is an alias for `flagsUpdated` +Feature flags, remote configuration, usage tracking and feedback for browser applications. -If you are running with strict Content Security Policies active on your website, you will need change them as follows: +This page covers SDK v2. -* `connect-src https://front.bucket.co` to `connect-src https://front.reflag.com` +## Get started -Finally, if you have customized the look & feel of the Feedback component, update `--bucket-feedback-*` CSS classes to `--reflag-feedback-*` +### 1. Create a client -## Flag toggles +Install the SDK: -Reflag determines which flags are active for a given user/company. The user/company is given in the ReflagClient constructor. - -If you supply `user` or `company` objects, they must include at least the `id` property otherwise they will be ignored in their entirety. In addition to the `id`, you must also supply anything additional that you want to be able to evaluate flag targeting rules against. - -Attributes cannot be nested (multiple levels) and must be either strings, integers or booleans. Some attributes are special and used in Reflag UI: - -* `name` -- display name for `user`/`company`, -* `email` -- is accepted for `user`s and will be highlighted in the Reflag UI if available, -* `avatar` -- can be provided for both `user` and `company` and should be an URL to an image. - -```ts -const reflagClient = new ReflagClient({ - publishableKey, - user: { - id: "user_123", - name: "John Doe", - email: "john@acme.com" - avatar: "https://example.com/images/udsy6363" - }, - company: { - id: "company_123", - name: "Acme, Inc", - avatar: "https://example.com/images/31232ds" - }, -}); +```sh +npm install @reflag/browser-sdk ``` -To retrieve flags along with their targeting information, use `getFlag(key: string)`: +Create a client with your **publishable** key and the signed-in user's context: ```ts -const huddle = reflagClient.getFlag("huddle"); -// { -// isEnabled: true, -// config: { key: "zoom", payload: { ... } }, -// track: () => Promise -// requestFeedback: (options: RequestFeedbackData) => void -// } -``` - -You can use `getFlags()` to retrieve all enabled flags currently. +import { ReflagClient } from "@reflag/browser-sdk"; -```ts -const flags = reflagClient.getFlags(); -// { -// huddle: { -// isEnabled: true, -// targetingVersion: 42, -// config: ... -// } -// } +const reflag = new ReflagClient({ + publishableKey: "your-publishable-key", + user: { id: "alice", role: "manager" }, + company: { id: "acme", plan: "enterprise" }, +}); +await reflag.initialize(); ``` -`getFlags()` is meant to be more low-level than `getFlag()` and it typically used by down-stream clients, like the React SDK. +Publishable keys are safe to ship to the browser. Keep secret keys on your server. -Note that accessing `isEnabled` on the object returned by `getFlags` does not automatically generate a `check` event, contrary to the `isEnabled` property on the object returned by `getFlag`. +### 2. Create a flag -## End-user opt-in +Create a flag with the key `huddles` in the Reflag app. -If a flag has end-user opt-in enabled in Reflag, you can list the opt-in options for the current context and set or cancel opt-in for the current user or company. +### 3. Read the flag ```ts -const optInFlags = reflagClient.getOptInFlags(); -// [{ key, name, description, isEnabled, userOptedIn, companyOptedIn, isOptedIn }] - -try { - const response = await reflagClient.setOptIn("huddle", { - optedIn: true, // Use false to cancel this scope's opt-in. - scope: "user", // Use "company" to change the current company's opt-in. - }); - if (!response?.ok) { - console.error("Could not update opt-in"); - } -} catch (error) { - console.error("Could not update opt-in", error); +if (reflag.getFlag("huddles")) { + await reflag.track("Started huddle"); } ``` -By default, `setOptIn()` changes the opt-in for the current user, so the current context must include a `user.id`. To manage the current company's opt-in instead, pass `scope: "company"`; the context must then include a `company.id`. - -User and company opt-ins are managed independently. Setting `optedIn` to `false` removes the opt-in only for the selected scope. For example, cancelling a user's opt-in does not change the company's opt-in for the same flag. - -`setOptIn` returns a promise so you can wait for the new membership state to be synchronized. On success, it resolves after the refreshed flag state has been applied locally, the requested membership change has been confirmed, and `flagsUpdated` listeners have been notified when flags change. - -The promise resolves to a `Response`, or `undefined` if skipped due to invalid input, offline mode etc. Check `response?.ok` for success. +## Read flags -The `description` comes from the dedicated SDK-facing opt-in description configured in Reflag. - -When using bootstrapped flags, the first `getOptInFlags()` or `getIsLoadingOptInFlags()` call requests a flags refresh. The list call returns the currently available list synchronously, and the loading getter returns `true` until that refresh succeeds or fails. Normal initialization also exposes loading through the client's state. - -Listen for `optInFlagsLoadingUpdated` to update UI when this loading state changes. `flagsUpdated` is emitted when a successful refresh updates the list. - -If fetching opt-in metadata fails, loading ends without exposing an error. Call `reflagClient.refresh()` to retry. - -## Remote config - -Remote config is a dynamic and flexible approach to configuring flag behavior outside of your app – without needing to re-deploy it. - -Similar to `isEnabled`, each flag has a `config` property. This configuration is managed from within Reflag. It is managed similar to the way access to flags is managed, but instead of the binary `isEnabled` you can have multiple configuration values which are given to different user/companies. +Pass a flag key to check whether the flag is enabled: ```ts -const flags = reflagClient.getFlags(); -// { -// huddle: { -// isEnabled: true, -// targetingVersion: 42, -// config: { -// key: "gpt-3.5", -// payload: { maxTokens: 10000, model: "gpt-3.5-beta1" } -// } -// } -// } -``` - -`key` is mandatory for a config, but if a flag has no config or no config value was matched against the context, the `key` will be `undefined`. Make sure to check against this case when trying to use the configuration in your application. `payload` is an optional JSON value for arbitrary configuration needs. - -Just as `isEnabled`, accessing `config` on the object returned by `getFlags` does not automatically generate a `check` event, contrary to the `config` property on the object returned by `getFlag`. - -## Server-side rendering and bootstrapping - -For server-side rendered applications, you can render immediately with pre-fetched flag data by bootstrapping the client. - -### Init options bootstrapped - -```typescript -type Configuration = { - logger: console; // by default only logs warn/error, by passing `console` you'll log everything - apiBaseUrl?: "https://front.reflag.com"; - credentials?: "include" | "same-origin" | "omit"; // forwarded to fetch requests; "include" also enables credentials for the default EventSource transport - feedback?: undefined; // See FEEDBACK.md - enableTracking?: true; // set to `false` to stop sending track events and user/company updates to Reflag servers. Useful when you're impersonating a user - offline?: boolean; // Use the SDK in offline mode. Offline mode is useful during testing and local development - bootstrappedState?: { - context: ReflagContext; - flags: FetchedFlags; - flagStateVersion?: number; - }; // Pre-fetched evaluated state from server-side (see Server-side rendering section) - bootstrappedFlags?: FetchedFlags; // Deprecated: use `bootstrappedState` instead -}; +const enabled = reflag.getFlag("huddles"); // true or false ``` -### Using `bootstrappedState` - -Use the Node SDK's `getFlagsForBootstrap()` method to pre-fetch evaluated state server-side, then pass the returned object directly to the browser client: - -```typescript -// Server-side: Get bootstrapped state using Node SDK -import { ReflagClient as ReflagNodeClient } from "@reflag/node-sdk"; - -const serverClient = new ReflagNodeClient({ secretKey: "your-secret-key" }); -await serverClient.initialize(); +To read a configuration value, pass a default as the second argument. You get back a value of the same type as the default: -const bootstrappedState = serverClient.getFlagsForBootstrap({ - user: { id: "user123", name: "John Doe", email: "john@acme.com" }, - company: { id: "company456", name: "Acme Inc", plan: "enterprise" }, -}); - -// Pass the bootstrapped state to the client using your framework's preferred method -app.get("/", (req, res) => { - res.set("Content-Type", "text/html"); - res.send( - Buffer.from( - ` -
`, - ), - ); -}); - -// Client-side: Initialize with pre-fetched evaluated state -import { ReflagClient } from "@reflag/browser-sdk"; - -const reflagClient = new ReflagClient({ - publishableKey: "your-publishable-key", - bootstrappedState, // Contains context, flags, and optional flagStateVersion -}); - -await reflagClient.initialize(); -const { isEnabled } = reflagClient.getFlag("huddle"); +```ts +const model = reflag.getFlag("model", "quick"); // string +const settings = reflag.getFlag("assistant-settings", { model: "quick" }); // { model: string } ``` -The `bootstrappedState` object contains: +If the flag doesn't exist, or its value has a different type, you get `false`, or your default if you passed one. Pass `null` as the default to accept any JSON value and narrow it yourself. -* `context`: the evaluation context used on the server -* `flags`: the evaluated raw flags -* `flagStateVersion`: an optional version used to avoid redundant live-update refreshes immediately after bootstrapping +The SDK checks only the top-level type of a value. If your application depends on nested fields, validate them. -If you want live flag updates to continue working after bootstrapping, use a recent `@reflag/node-sdk` so `getFlagsForBootstrap()` includes `flagStateVersion`. +`getFlags()` returns all flag values as a record. -If a bootstrapped application requests opt-in flags, the browser SDK performs one flags refresh. Applications that do not request opt-in data do not make this request. +Each read records a check, which Reflag uses for launch monitoring. -If you previously used `bootstrappedFlags`, migrate like this: - -```typescript -// Before -const { flags } = serverClient.getFlagsForBootstrap(context); -const client = new ReflagClient({ - publishableKey, - user: context.user, - company: context.company, - other: context.other, - bootstrappedFlags: flags, -}); +## Track usage and feedback -// After -const bootstrappedState = serverClient.getFlagsForBootstrap(context); -const client = new ReflagClient({ - publishableKey, - bootstrappedState, -}); +```ts +await reflag.track("Started huddle", { button: "cta" }); +reflag.requestFeedback({ flagKey: "huddles", title: "How did it go?" }); +await reflag.feedback({ flagKey: "huddles", score: 5 }); ``` -{% hint style="info" %} -After bootstrapping, any live flag updates are fetched directly by the browser SDK from Reflag using the browser-visible context. If your bootstrapped snapshot depends on server-only or secret context that is not available in the browser, later live refreshes may differ. In that case, keep `enableLiveFlagUpdates` disabled. - -Requesting opt-in flags also triggers a browser-side refresh, even when `enableLiveFlagUpdates` is disabled. -{% endhint %} - -This eliminates loading states and removes the initial render's dependency on the flags API. - -## Context management +`requestFeedback()` opens the feedback form. `feedback()` sends feedback you collected yourself. -### Updating user/company/other context +Configure your flag's adoption rules to match the event names you send. See [FEEDBACK.md](feedback.md) to configure feedback prompts and the feedback UI. -Attributes given for the user/company/other context in the ReflagClient constructor can be updated for use in flag targeting evaluation with the `updateUser()`, `updateCompany()` and `updateOtherContext()` methods. They return a promise which resolves once the flags have been re-evaluated follow the update of the attributes. - -### setContext() - -The `setContext()` method allows you to replace the entire context (user, company, and other attributes) at once. This method is useful when you need to completely change the context, such as when a user logs in or switches between different accounts. +## Update context ```ts -await reflagClient.setContext({ - user: { - id: "new-user-123", - name: "Jane Doe", - email: "jane@example.com", - role: "admin", - }, - company: { - id: "company-456", - name: "New Company Inc", - plan: "enterprise", - }, - other: { - feature: "beta", - locale: "en-US", - }, +await reflag.updateUser({ role: "admin" }); +await reflag.updateCompany({ plan: "enterprise" }); +await reflag.updateOtherContext({ region: "eu" }); + +// Replace the whole context, for example after the user switches company: +await reflag.setContext({ + user: { id: "bob" }, + company: { id: "other-company" }, }); ``` -The method will: +The update methods merge into their section of the context, while `setContext()` replaces all of it. User and company sections need an `id`. Flag values are refetched for the new context. -* Replace the entire context with the new values -* Re-evaluate all flags based on the new context -* Update the user and company information on Reflag servers -* Return a promise that resolves once the flags have been re-evaluated +## Bootstrap from the server -### getContext() - -The `getContext()` method returns the current context being used for flag evaluation. This is useful for debugging or when you need to inspect the current user, company, and other attributes. +To render flags immediately, without waiting for a network request, evaluate them on your server with the **Node.js SDK** and pass the result to the browser: ```ts -const currentContext = reflagClient.getContext(); -console.log(currentContext); -// { -// user: { id: "user-123", name: "John Doe", email: "john@example.com" }, -// company: { id: "company-456", name: "Acme Inc", plan: "enterprise" }, -// other: { locale: "en-US", feature: "beta" } -// } -``` - -The returned context object contains: - -* `user`: Current user attributes (if any) -* `company`: Current company attributes (if any) -* `other`: Additional context attributes not related to user or company - -## Toolbar - -The Reflag Toolbar is great for toggling flags on/off for yourself to ensure that everything works both when a flag is on and when it's off. - -Toolbar screenshot - -The toolbar will automatically appear on `localhost`. However, it can also be incredibly useful in production. You have full control over when it appears through the `toolbar` configuration option passed to the `ReflagClient`. - -You can pass a simple boolean to force the toolbar to appear/disappear: - -```typescript -const client = new ReflagClient({ - // show the toolbar even in production if the user is an internal/admin user - toolbar: user?.isInternal, - ... -}); -``` - -You can also configure the position of the toolbar on the screen: - -```typescript -const client = new ReflagClient({ - toolbar: { - show: true; - position: { - placement: "bottom-left", - offset: {x: "1rem", y: "1rem"} - } - } - ... -}) +// On the server +const bootstrappedState = serverClient.getFlagsForBootstrap(context); ``` -See [the reference](https://docs.reflag.com/supported-languages/browser-sdk/globals#toolbaroptions) for details. - -## Qualitative feedback on beta flags - -Reflag can collect qualitative feedback from your users in the form of a [Customer Satisfaction Score](https://en.wikipedia.org/wiki/Customer_satisfaction) and a comment. - -### Automated feedback collection - -The Reflag Browser SDK comes with automated feedback collection mode enabled by default, which lets the Reflag service ask your users for feedback for relevant flags just after they've used them. - -{% hint style="info" %} -To get started with automatic feedback collection, make sure you've set `user` in the `ReflagClient` constructor. -{% endhint %} - -Automated feedback surveys work even if you're not using the SDK to send events to Reflag. It works because the Reflag Browser SDK maintains a live connection to Reflag's servers and can automatically show a feedback prompt whenever the Reflag servers determines that an event should trigger a prompt - regardless of how this event is sent to Reflag. - -You can find all the options to make changes to the default behavior in the [Reflag feedback documentation](feedback.md). - -### Reflag feedback UI - -Reflag can assist you with collecting your user's feedback by offering a pre-built UI, allowing you to get started with minimal code and effort. - -[Read the Reflag feedback UI documentation](feedback.md) - -### Reflag feedback SDK - -Feedback can be submitted to Reflag using the SDK: - ```ts -reflagClient.feedback({ - flagKey: "my-flag-key", // String (required), copy from Flag feedback tab - score: 5, // Number: 1-5 (optional) - comment: "Absolutely stellar work!", // String (optional) -}); +// In the browser +const reflag = new ReflagClient({ publishableKey, bootstrappedState }); +await reflag.initialize(); ``` -### Reflag feedback API - -If you are not using the Reflag Browser SDK, you can still submit feedback using the HTTP API. - -See details in [Feedback HTTP API](https://docs.reflag.com/api/http-api#post-feedback) +Pass the whole object returned by `getFlagsForBootstrap()`, serialized with your framework's usual mechanism. Leave secrets and server-only attributes out of the context you bootstrap, because the browser can read it. -## Tracking flag usage +Later refreshes evaluate flags using the browser's context. If values that depend on server-only attributes must not change, leave `enableLiveFlagUpdates` off (the default). -The `track` function lets you send events to Reflag to denote flag usage. By default Reflag expects event names to align with the flag keys, but you can customize it as you wish. +## Let users opt in to flags ```ts -reflagClient.track("huddle", { voiceHuddle: true }); +const optInFlags = reflag.getOptInFlags(); +await reflag.setOptIn("huddles", { optedIn: true }); +await reflag.setOptIn("huddles", { optedIn: false, scope: "company" }); ``` -## Event listeners +Each entry includes the flag's `key`, `name`, `description` and whether the user or company has opted in. User and company opt-ins are independent. Use `getIsLoadingOptInFlags()` and the `optInFlagsLoadingUpdated` event to show a loading state. -Event listeners allow for capturing various events occurring in the `ReflagClient`. This is useful to build integrations with other system or for various debugging purposes. The available events are: +## Overrides and toolbar -* `check`: Your code used `isEnabled` or `config` for a flag -* `flagsUpdated`: Flags were updated. Either because they were loaded as part of initialization or because the user/company updated -* `optInFlagsLoadingUpdated`: The opt-in flag loading state changed -* `user`: User information updated (similar to the `identify` call used in tracking terminology) -* `company`: Company information updated (sometimes to the `group` call used in tracking terminology) -* `track`: Track event occurred. - -Use the `on()` method to add an event listener to respond to certain events. See the API reference for details on each hook. +Override flags locally while developing or testing: ```ts -import { ReflagClient, CheckEvent, RawFlags } from "@reflag/browser-sdk"; - -const client = new ReflagClient({ - // options -}); - -// or add the hooks after construction: -const unsub = client.on("check", (check: CheckEvent) => - console.log(`Check event ${check}`), -); -// use the returned function to unsubscribe, or call `off()` with the same arguments again -unsub(); +reflag.setFlagOverride("huddles", true); +reflag.setFlagOverride("assistant-settings", { model: "local" }); +reflag.setFlagOverride("huddles", undefined); // remove the override ``` -## Zero PII - -The Reflag Browser SDK doesn't collect any metadata and HTTP IP addresses are _not_ being stored. - -For tracking individual users, we recommend using something like database ID as userId, as it's unique and doesn't include any PII (personal identifiable information). If, however, you're using e.g. email address as userId, but prefer not to send any PII to Reflag, you can hash the sensitive data before sending it to Reflag: +The toolbar shows on `localhost` by default and lets you toggle Boolean flags for yourself. Use the `toolbar` option to show it elsewhere, for example to internal users in production: ```ts -import reflag from "@reflag/browser-sdk"; -import { sha256 } from "crypto-hash"; - -reflag.user(await sha256("john_doe")); +const reflag = new ReflagClient({ + publishableKey, + toolbar: user.isInternal, // show the toolbar to internal users +}); ``` -## Use of cookies - -The Reflag Browser SDK uses a couple of cookies to support automated feedback surveys. These cookies are not used for tracking purposes and thus should not need to appear in cookie consent forms. - -The two cookies are: - -* `reflag-prompt-${userId}`: store the last automated feedback prompt message ID received to avoid repeating surveys -* `reflag-token-${userId}`: caching a token used to connect to Reflag's live messaging infrastructure that is used to deliver automated feedback surveys in real time. +## Events -## TypeScript +`on(event, handler)` subscribes to client events and returns an unsubscribe function. Events include `stateUpdated`, `flagsUpdated`, `check`, `track`, `user`, `company` and `optInFlagsLoadingUpdated`. -Types are bundled together with the library and exposed automatically when importing through a package manager. +## Configuration -## Content Security Policy (CSP) +| Option | Description | +| -------------------------- | --------------------------------------------------------------- | +| `fallbackFlags` | Values to use if flags can't be fetched | +| `enableLiveFlagUpdates` | Update flags when they change in Reflag; default `false` | +| `staleTimeMs` | How long cached flags count as fresh; default `0` | +| `staleWhileRevalidate` | Use stale cached flags while fetching new ones; default `false` | +| `expireTimeMs` | How long cached flags are kept; default 30 days | +| `timeoutMs` | Flag request timeout; default 5,000 ms | +| `enableTracking` | Set to `false` to stop sending checks and usage events | +| `offline` | Make no network requests, for example in tests | +| `toolbar`, `feedback` | Toolbar and feedback UI options | +| `logger` | Custom logger | +| `apiBaseUrl`, `appBaseUrl` | Override the API and app URLs | +| `credentials` | Fetch credentials mode | +| `storage` | Custom async storage for the flag cache | +| `eventSourceFactory` | Custom EventSource implementation for runtimes without one | +| `trackingQueue` | Event batching: `flushDelayMs` and `maxSize` | -If you are running with strict Content Security Policies active on your website, you will need to enable these directives in order to use the SDK: +## Shut down -| Directive | Values | Reason | -| ----------- | ---------------------------------------------------- | ------------------------------------------------------------------------------------------------------- | -| connect-src | [https://front.reflag.com](https://front.reflag.com) | API requests plus Server-Sent Events for live flag updates and automated feedback surveys. | -| style-src | 'unsafe-inline' | The feedback UI is styled with inline styles. Not having this directive results unstyled HTML elements. | +Call `await reflag.stop()` to send buffered events and close the client, for example when the user signs out. -If you are including the Reflag tracking SDK with a ` ``` -## Internationalization (i18n) +## Internationalization (i18n) By default, the feedback UI is written in English. However, you can supply your own translations by passing an object in the options to either or both of the @@ -282,10 +284,10 @@ See examples below. ![image](https://github.com/reflagcom/javascript/assets/331790/68805b38-e9f6-4de5-9f55-188216983e3c) -See [default English localization keys](https://github.com/reflagcom/javascript/tree/main/packages/browser-sdk/src/feedback/ui/config/defaultTranslations.tsx) +See [default English localization keys](https://github.com/reflagcom/javascript/tree/ed0e7725719756855c20e939265713914e956b8b/packages/browser-sdk/src/feedback/ui/config/defaultTranslations.tsx) for a reference of what translation keys can be supplied. -### Static language configuration +### Static language configuration If you know the language at page load, you can configure your translation keys while initializing the Reflag Browser SDK: @@ -316,7 +318,7 @@ new ReflagClient({ }); ``` -### Runtime language configuration +### Runtime language configuration If you only know the user's language after the page has loaded, you can provide translations to either the `reflagClient.requestFeedback(options)` call or @@ -332,7 +334,7 @@ reflagClient.requestFeedback({ }) ``` -### Translations +### Translations When you are collecting feedback through the Reflag automation, you can intercept the default prompt handling and override the defaults. @@ -359,7 +361,7 @@ new ReflagClient({ }); ``` -## Custom styling +## Custom styling You can adapt parts of the look of the Reflag feedback UI by applying CSS custom properties to your page in your CSS `:root`-scope. @@ -396,9 +398,9 @@ For example, a dark mode theme might look like this: } ``` -Other examples of custom styling can be found in our [development example style-sheet](https://github.com/reflagcom/javascript/tree/main/packages/browser-sdk/src/feedback/ui/index.css). +Other examples of custom styling can be found in our [development example style-sheet](https://github.com/reflagcom/javascript/tree/ed0e7725719756855c20e939265713914e956b8b/packages/browser-sdk/src/feedback/ui/index.css). -## Using your own UI to collect feedback +## Using your own UI to collect feedback You may have very strict design guidelines for your app and maybe the Reflag feedback UI doesn't quite work for you. In this case, you can implement your own feedback @@ -418,10 +420,10 @@ type DataToCollect = { Either `score` or `comment` must be defined in order to pass validation in the Reflag API. -### Manual feedback collection with custom UI +### Manual feedback collection with custom UI Examples of a HTML-form that collects the relevant data can be found -in [feedback.html](https://github.com/reflagcom/javascript/tree/main/packages/browser-sdk/example/feedback/feedback.html) and [feedback.jsx](https://github.com/reflagcom/javascript/tree/main/packages/browser-sdk/example/feedback/Feedback.jsx). +in [feedback.html](https://github.com/reflagcom/javascript/tree/ed0e7725719756855c20e939265713914e956b8b/packages/browser-sdk/example/feedback/feedback.html) and [feedback.jsx](https://github.com/reflagcom/javascript/tree/ed0e7725719756855c20e939265713914e956b8b/packages/browser-sdk/example/feedback/Feedback.jsx). Once you have collected the feedback data, pass it along to `reflagClient.feedback()`: @@ -434,7 +436,7 @@ reflagClient.feedback({ }); ``` -### Intercepting automated feedback survey events +### Intercepting automated feedback survey events When using automated feedback surveys, the Reflag service will, when specified, send a feedback prompt message to your user's instance of the Reflag Browser SDK. @@ -471,3 +473,5 @@ new ReflagClient({ }, }); ``` + +Using v1? [Legacy docs](../../legacy/v1/browser-sdk/feedback.md) · [Upgrade guide](../migrating-from-v1.md). diff --git a/supported-languages/browser-sdk/globals.md b/supported-languages/browser-sdk/globals.md index 25f4c55..4804e0a 100644 --- a/supported-languages/browser-sdk/globals.md +++ b/supported-languages/browser-sdk/globals.md @@ -13,17 +13,19 @@ pagination: visible: true --- -# @reflag/browser-sdk +# @reflag/browser-sdk -## Classes +This page covers SDK v2. -### ReflagClient +## Classes + +### ReflagClient ReflagClient lets you interact with the Reflag API. -#### Constructors +#### Constructors -##### new ReflagClient() +### new ReflagClient() ```ts new ReflagClient(opts: InitOptions): ReflagClient @@ -31,7 +33,7 @@ new ReflagClient(opts: InitOptions): ReflagClient Create a new ReflagClient instance. -###### Parameters +###### Parameters @@ -56,11 +58,11 @@ Create a new ReflagClient instance.
-###### Returns +###### Returns [`ReflagClient`](globals.md#reflagclient) -#### Properties +#### Properties @@ -84,22 +86,22 @@ Create a new ReflagClient instance.
-[`Logger`](globals.md#logger-1) +[`Logger`](globals.md#logger)
-#### Methods +#### Methods -##### applyBootstrappedState() +### applyBootstrappedState() ```ts applyBootstrappedState(bootstrappedState: BootstrappedState, triggerEvent: boolean): void ``` -###### Parameters +###### Parameters @@ -147,11 +149,11 @@ applyBootstrappedState(bootstrappedState: BootstrappedState, triggerEvent: boole
-###### Returns +###### Returns `void` -##### feedback() +### feedback() ```ts feedback(payload: Feedback): Promise< @@ -161,7 +163,7 @@ feedback(payload: Feedback): Promise< Submit user feedback to Reflag. Must include either `score` or `comment`, or both. -###### Parameters +###### Parameters @@ -180,7 +182,7 @@ Submit user feedback to Reflag. Must include either `score` or `comment`, or bot
-[`Feedback`](globals.md#feedback-1) +[`Feedback`](globals.md#feedback) @@ -192,7 +194,7 @@ The feedback details to submit.
-###### Returns +###### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\< \| `undefined` @@ -200,7 +202,7 @@ The feedback details to submit. The server response. -##### getConfig() +### getConfig() ```ts getConfig(): Config @@ -208,11 +210,11 @@ getConfig(): Config Get the current configuration. -###### Returns +###### Returns [`Config`](globals.md#config) -##### getContext() +### getContext() ```ts getContext(): ReflagContext @@ -220,17 +222,35 @@ getContext(): ReflagContext Get the current context. -###### Returns +###### Returns [`ReflagContext`](globals.md#reflagcontext) -##### ~~getFeature()~~ +### ~~getFeatures()~~ ```ts -getFeature(flagKey: string): Flag +getFeatures(): Record ``` -###### Parameters +###### Returns + +[`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, `undefined` \| [`FlagValue`](globals.md#flagvalue)\> + +###### Deprecated + +Use `getFlags` instead. + +### getFlag() + +###### Call Signature + +```ts +getFlag(key: string, defaultValue?: undefined): boolean +``` + +Boolean-first reads; positional defaults select other top-level JSON categories. + +###### Parameters @@ -243,7 +263,7 @@ getFeature(flagKey: string): Flag - -
-`flagKey` +`key` @@ -252,94 +272,164 @@ getFeature(flagKey: string): Flag
+
-###### Returns +`defaultValue`? -[`Flag`](globals.md#flag) + -###### Deprecated +`undefined` -Use `getFlag` instead. +
-##### ~~getFeatures()~~ +###### Returns -```ts -getFeatures(): RawFlags -``` +`boolean` -###### Returns +###### Call Signature -[`RawFlags`](globals.md#rawflags) +```ts +getFlag(key: string, defaultValue: Default): FlagValueFromDefault +``` -###### Deprecated +Boolean-first reads; positional defaults select other top-level JSON categories. -Use `getFlags` instead. +###### Type Parameters -##### getFlag() + + + + + + + + + + + +
Type Parameter
-```ts -getFlag(flagKey: string): Flag -``` +`Default` *extends* `object` \| [`FlagDefaultValue`](globals.md#flagdefaultvalue) -Return a flag. Accessing `isEnabled` or `config` will automatically send a `check` event. +
-###### Parameters +###### Parameters - + + +
Parameter TypeDescription
-`flagKey` +`key` `string` +
+ +`defaultValue` + -The key of the flag to get. +`Default`
-###### Returns +###### Returns + +[`FlagValueFromDefault`](globals.md#flagvaluefromdefaultt)\<`Default`\> + +### getFlagOverride() -[`Flag`](globals.md#flag) +```ts +getFlagOverride(key: string): undefined | FlagValue +``` -A flag. +###### Parameters -##### getFlags() + + + + + + + + + + + + + +
ParameterType
+ +`key` + + + +`string` + +
+ +###### Returns + +`undefined` \| [`FlagValue`](globals.md#flagvalue) + +### getFlagResults() ```ts -getFlags(): RawFlags +getFlagResults(): RawFlags ``` -Returns a map of enabled flags. -Accessing a flag will *not* send a check event -and `isEnabled` does not take any flag overrides -into account. +Owned evaluated diagnostics; inspecting these is not an application read. -###### Returns +###### Returns [`RawFlags`](globals.md#rawflags) -Map of flags. +### getFlags() + +```ts +getFlags(): Record +``` + +Return direct values and register checks for these returned roots. +Use getFlagResults() for diagnostic/serialization access without checks. + +###### Returns + +[`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, `undefined` \| [`FlagValue`](globals.md#flagvalue)\> -##### getIsLoadingOptInFlags() +### getFlagsForBootstrap() + +```ts +getFlagsForBootstrap(): BootstrappedState +``` + +###### Returns + +[`BootstrappedState`](globals.md#bootstrappedstate) + +### getIsLoadingOptInFlags() ```ts getIsLoadingOptInFlags(): boolean @@ -349,11 +439,11 @@ Returns whether opt-in flags are loading for the current context. Calling this method requests opt-in metadata if it is not already available. -###### Returns +###### Returns `boolean` -##### getOptInFlags() +### getOptInFlags() ```ts getOptInFlags(): OptInFlag[] @@ -361,21 +451,21 @@ getOptInFlags(): OptInFlag[] Returns opt-in-enabled flags for the current context. -###### Returns +###### Returns [`OptInFlag`](globals.md#optinflag)[] -##### getState() +### getState() ```ts getState(): State ``` -###### Returns +###### Returns [`State`](globals.md#state) -##### initialize() +### initialize() ```ts initialize(): Promise @@ -385,11 +475,11 @@ Initialize the Reflag SDK. Must be called before calling other SDK methods. -###### Returns +###### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> -##### off() +### off() ```ts off(type: THookType, handler: (args0: HookArgs[THookType]) => void): void @@ -397,7 +487,7 @@ off(type: THookType, handler: (args0: HookArgs[THookType]) => void): Remove an event listener -###### Type Parameters +###### Type Parameters @@ -416,7 +506,7 @@ Remove an event listener
-###### Parameters +###### Parameters @@ -464,13 +554,13 @@ The same function that was passed to `on`.
-###### Returns +###### Returns `void` A function to remove the hook. -##### on() +### on() ```ts on(type: THookType, handler: (args0: HookArgs[THookType]) => void): () => void @@ -478,7 +568,7 @@ on(type: THookType, handler: (args0: HookArgs[THookType]) => void): ( Add an event listener -###### Type Parameters +###### Type Parameters @@ -497,7 +587,7 @@ Add an event listener
-###### Parameters +###### Parameters @@ -545,17 +635,17 @@ The function to call when the event is triggered.
-###### Returns +###### Returns `Function` A function to remove the hook. -###### Returns +###### Returns `void` -##### refresh() +### refresh() ```ts refresh(): Promise @@ -563,11 +653,11 @@ refresh(): Promise Force refresh flags from the API, bypassing cache. -###### Returns +###### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`undefined` \| [`RawFlags`](globals.md#rawflags)\> -##### requestFeedback() +### requestFeedback() ```ts requestFeedback(options: RequestFeedbackData): void @@ -577,7 +667,7 @@ Display the Reflag feedback form UI programmatically. This can be used to collect feedback from users in Reflag in cases where Automated Feedback Surveys isn't appropriate. -###### Parameters +###### Parameters @@ -602,11 +692,11 @@ This can be used to collect feedback from users in Reflag in cases where Automat
-###### Returns +###### Returns `void` -##### setContext() +### setContext() ```ts setContext(context: ReflagDeprecatedContext): Promise @@ -615,7 +705,7 @@ setContext(context: ReflagDeprecatedContext): Promise Update the context. Replaces the existing context with a new context. -###### Parameters +###### Parameters @@ -646,11 +736,60 @@ The context to update.
-###### Returns +###### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> -##### setOptIn() +### setFlagOverride() + +```ts +setFlagOverride(key: string, value: undefined | FlagValue): void +``` + +Overrides are applied after server evaluation and never invent selections. + +###### Parameters + + + + + + + + + + + + + + + + + + +
ParameterType
+ +`key` + + + +`string` + +
+ +`value` + + + +`undefined` \| [`FlagValue`](globals.md#flagvalue) + +
+ +###### Returns + +`void` + +### setOptIn() ```ts setOptIn(flagKey: string, options: SetOptInOptions): Promise< @@ -660,13 +799,7 @@ setOptIn(flagKey: string, options: SetOptInOptions): Promise< Set whether the current user or company has opted into a flag. -A successful Response is returned after the refreshed flag state confirms -the membership change. HTTP failures return a non-OK Response without -refreshing flags. Offline mode, invalid arguments, or missing scoped context -return undefined. Network and confirmation failures reject the promise; -a confirmation failure may occur after membership changed remotely. - -###### Parameters +###### Parameters @@ -703,19 +836,19 @@ a confirmation failure may occur after membership changed remotely.
-###### Returns +###### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\< \| `undefined` \| [`Response`](https://developer.mozilla.org/docs/Web/API/Response)\> -##### showToolbarToggle() +### showToolbarToggle() ```ts showToolbarToggle(position?: ToolbarPosition): void ``` -###### Parameters +###### Parameters @@ -740,11 +873,11 @@ showToolbarToggle(position?: ToolbarPosition): void
-###### Returns +###### Returns `void` -##### stop() +### stop() ```ts stop(): Promise @@ -753,14 +886,14 @@ stop(): Promise Stop the SDK. This will stop any automated feedback surveys. -###### Returns +###### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> -##### track() +### track() ```ts -track(eventName: string, attributes?: +track(eventName: string, attributes?: | null | Record): Promise< | undefined @@ -769,7 +902,7 @@ track(eventName: string, attributes?: Track an event in Reflag. -###### Parameters +###### Parameters @@ -817,13 +950,13 @@ Any attributes you want to attach to the event.
-###### Returns +###### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\< \| `undefined` \| [`Response`](https://developer.mozilla.org/docs/Web/API/Response)\> -##### updateCompany() +### updateCompany() ```ts updateCompany(company: {}): Promise @@ -833,7 +966,7 @@ Update the company context. Performs a shallow merge with the existing company context. It will not update the context if nothing has changed. -###### Parameters +###### Parameters @@ -864,22 +997,22 @@ The company details.
-###### Returns +###### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> -##### updateFlags() +### updateFlags() ```ts updateFlags( - flags: RawFlags, - triggerEvent: boolean, + flags: RawFlags, + triggerEvent: boolean, flagStateVersion?: number): void ``` Update the flags. -###### Parameters +###### Parameters @@ -960,11 +1093,11 @@ Whether to trigger the `flagsUpdated` event.
-###### Returns +###### Returns `void` -##### updateOtherContext() +### updateOtherContext() ```ts updateOtherContext(otherContext: {}): Promise @@ -974,7 +1107,7 @@ Update the company context. Performs a shallow merge with the existing company context. It will not update the context if nothing has changed. -###### Parameters +###### Parameters @@ -1005,11 +1138,11 @@ Additional context.
-###### Returns +###### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> -##### updateUser() +### updateUser() ```ts updateUser(user: {}): Promise @@ -1019,7 +1152,7 @@ Update the user context. Performs a shallow merge with the existing user context. It will not update the context if nothing has changed. -###### Parameters +###### Parameters @@ -1044,24 +1177,23 @@ It will not update the context if nothing has changed.
-###### Returns +###### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> -## Interfaces +## Interfaces -### CheckEvent +### CheckEvent -Event representing checking the flag evaluation result +A root read records selection identity, never its JSON payload. -#### Properties +#### Properties - @@ -1073,53 +1205,38 @@ Event representing checking the flag evaluation result - - - + + + - + + - - + + @@ -1195,19 +1310,19 @@ Version of targeting rules. *** -### CompanyContext +### CompanyContext Context is a set of key-value pairs. This is used to determine if feature targeting matches and to track events. Id should always be present so that it can be referenced to an existing company. -#### Indexable +#### Indexable ```ts [key: string]: ContextValue ``` -#### Properties +#### Properties
Property TypeDescription
-`"check-is-enabled"` \| `"check-config"` - - - -`check-is-enabled` means `isEnabled` was checked, `check-config` means `config` was checked. +`"check"`
- `evaluationErrors?` - - - -\{ `code`: `string`; `field`: `string`; `message`: `string`; `operator`: `string`; \}[] + `evalContext?` -Non-fatal diagnostics produced while evaluating the flag. +[`ReflagContext`](globals.md#reflagcontext)
- `key` + `evalErrors?` -`string` - - - -Flag key. +[`EvaluationError`](globals.md#evaluationerror)[]
- ~~`missingContextFields?`~~ + `evalMissingFields?` @@ -1127,66 +1244,64 @@ Flag key. `string`[]
-Missing context fields. + `evalResult?` -**Deprecated** + -Use `evaluationErrors` and check for `MISSING_CONTEXT_FIELD`. +`string`
- `ruleEvaluationResults?` + `evalRuleResults?` `boolean`[] - - -Rule evaluation results. -
- `value?` + `flagStateVersion?` - \| `boolean` \| \{ `key`: `string`; `payload`: `any`; \} +`number`
-Result of flag or configuration evaluation. -If `action` is `check-is-enabled`, this is the result of the flag evaluation and `value` is a boolean. -If `action` is `check-config`, this is the result of the configuration evaluation. + `key`
- `version?` +`string`
-`number` + `sourceVersionId?` -Version of targeting rules. +`string`
@@ -1257,11 +1372,11 @@ Company name *** -### Config +### Config ReflagClient configuration. -#### Properties +#### Properties
@@ -1380,9 +1495,9 @@ Defaults to `apiBaseUrl`. *** -### FeedbackScoreSubmission +### FeedbackScoreSubmission -#### Properties +#### Properties
@@ -1433,9 +1548,9 @@ Defaults to `apiBaseUrl`. *** -### FeedbackSubmission +### FeedbackSubmission -#### Properties +#### Properties
@@ -1498,153 +1613,9 @@ Defaults to `apiBaseUrl`. *** -### Flag - -#### Properties - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
PropertyTypeDescription
- - `config` - - - -[`FlagRemoteConfig`](globals.md#flagremoteconfig) - - - -‐ - -
- - `isEnabled` - - - -`boolean` - - - -Result of flag flag evaluation. -Note: Does not take local overrides into account. - -
- - `isEnabledOverride` - - - -`null` \| `boolean` - - - -The current override status of isEnabled for the flag. - -
- - `requestFeedback` - - - -(`options`: [`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys)\<[`RequestFeedbackData`](globals.md#requestfeedbackdata), `"featureId"` \| `"flagKey"`\>) => `void` - - - -Function to request feedback for this flag. - -
- - `track` - - - -() => [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\< \| `undefined` \| [`Response`](https://developer.mozilla.org/docs/Web/API/Response)\> - - - -Function to send analytics events for this flag. - -
- -#### Methods - -##### setIsEnabledOverride() - -```ts -setIsEnabledOverride(isEnabled: null | boolean): void -``` - -Set the override status for isEnabled for the flag. -Set to `null` to remove the override. - -###### Parameters - - - - - - - - - - - - - - -
ParameterType
- -`isEnabled` - - - -`null` \| `boolean` - -
- -###### Returns - -`void` - -*** - -### HookArgs +### HookArgs -#### Properties +#### Properties @@ -1762,7 +1733,7 @@ Use `flagsUpdated` instead. - - - +
- `track` + `track` @@ -1798,17 +1769,17 @@ Use `flagsUpdated` instead. *** -### Logger +### Logger -#### Methods +#### Methods -##### debug() +### debug() ```ts debug(message: string, ...args: any[]): void ``` -###### Parameters +###### Parameters @@ -1845,17 +1816,17 @@ debug(message: string, ...args: any[]): void
-###### Returns +###### Returns `void` -##### error() +### error() ```ts error(message: string, ...args: any[]): void ``` -###### Parameters +###### Parameters @@ -1892,17 +1863,17 @@ error(message: string, ...args: any[]): void
-###### Returns +###### Returns `void` -##### info() +### info() ```ts info(message: string, ...args: any[]): void ``` -###### Parameters +###### Parameters @@ -1939,17 +1910,17 @@ info(message: string, ...args: any[]): void
-###### Returns +###### Returns `void` -##### warn() +### warn() ```ts warn(message: string, ...args: any[]): void ``` -###### Parameters +###### Parameters @@ -1986,15 +1957,15 @@ warn(message: string, ...args: any[]): void
-###### Returns +###### Returns `void` *** -### OnScoreSubmitResult +### OnScoreSubmitResult -#### Properties +#### Properties @@ -2021,9 +1992,9 @@ warn(message: string, ...args: any[]): void *** -### OpenFeedbackFormOptions +### OpenFeedbackFormOptions -#### Properties +#### Properties
@@ -2145,7 +2116,7 @@ Defaults to `false` - - - -
-[`Position`](globals.md#position-1) +[`Position`](globals.md#position) @@ -2194,16 +2165,16 @@ Undefined translation keys fall back to english defaults. *** -### ReflagContext +### ReflagContext Context is a set of key-value pairs. This is used to determine if feature targeting matches and to track events. -#### Extended by +#### Extended by - [`ReflagDeprecatedContext`](globals.md#reflagdeprecatedcontext) -#### Properties +#### Properties @@ -2272,19 +2243,19 @@ user attributes on Reflag servers. *** -### ~~ReflagDeprecatedContext~~ +### ~~ReflagDeprecatedContext~~ **`Internal`** -#### Deprecated +#### Deprecated Use `ReflagContext` instead, this interface will be removed in the next major version -#### Extends +#### Extends - [`ReflagContext`](globals.md#reflagcontext) -#### Properties +#### Properties
@@ -2374,9 +2345,9 @@ user attributes on Reflag servers. *** -### ToolbarPosition +### ToolbarPosition -#### Properties +#### Properties
@@ -2394,7 +2365,7 @@ user attributes on Reflag servers. @@ -2415,19 +2386,19 @@ user attributes on Reflag servers. *** -### UserContext +### UserContext Context is a set of key-value pairs. This is used to determine if feature targeting matches and to track events. Id should always be present so that it can be referenced to an existing user. -#### Indexable +#### Indexable ```ts [key: string]: ContextValue ``` -#### Properties +#### Properties
-[`Offset`](globals.md#offset-1) +[`Offset`](globals.md#offset)
@@ -2492,21 +2463,22 @@ User name
-## Type Aliases +## Type Aliases -### BootstrappedState +### BootstrappedState ```ts type BootstrappedState = { context: ReflagContext; flags: RawFlags; flagStateVersion: number; + protocolVersion: 2; }; ``` Pre-fetched evaluated state used to bootstrap the client. -#### Type declaration +#### Type declaration @@ -2543,13 +2515,25 @@ Pre-fetched evaluated state used to bootstrap the client. + + + + @@ -2557,7 +2541,7 @@ Pre-fetched evaluated state used to bootstrap the client. *** -### ContextValue +### ContextValue ```ts type ContextValue = DefinedContextValue | undefined; @@ -2567,10 +2551,10 @@ A context value. Object properties set to `undefined` are omitted. *** -### DefinedContextValue +### DefinedContextValue ```ts -type DefinedContextValue = +type DefinedContextValue = | string | number | boolean @@ -2583,7 +2567,7 @@ A JSON-compatible context value that is not `undefined`. *** -### DialogPlacement +### DialogPlacement ```ts type DialogPlacement = "bottom-right" | "bottom-left" | "top-right" | "top-left"; @@ -2591,13 +2575,130 @@ type DialogPlacement = "bottom-right" | "bottom-left" | "top-right" | "top-left" *** -### EventSourceFactory() +### EvaluationError + +```ts +type EvaluationError = { + code: string; + field: string; + message: string; + operator: string; + source: { + key: string; + type: "flag" | "segment"; + }; +}; +``` + +#### Type declaration + +
- `flagStateVersion`? + `flagStateVersion`? `number` +
+ + `protocolVersion` + + + +`2` +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameType
+ + `code` + + + +`string` + +
+ + `field`? + + + +`string` + +
+ + `message` + + + +`string` + +
+ + `operator`? + + + +`string` + +
+ + `source`? + + + +\{ + `key`: `string`; + `type`: `"flag"` \| `"segment"`; + \} + +
+ +`source.key` + + + +`string` + +
+ +`source.type` + + + +`"flag"` \| `"segment"` + +
+ +*** + +### EventSourceFactory() ```ts type EventSourceFactory = (url: string) => EventSourceLike; ``` -#### Parameters +#### Parameters @@ -2622,13 +2723,13 @@ type EventSourceFactory = (url: string) => EventSourceLike;
-#### Returns +#### Returns [`EventSourceLike`](globals.md#eventsourcelike) *** -### EventSourceLike +### EventSourceLike ```ts type EventSourceLike = { @@ -2637,7 +2738,7 @@ type EventSourceLike = { }; ``` -#### Type declaration +#### Type declaration @@ -2676,20 +2777,15 @@ type EventSourceLike = { *** -### FallbackFlagOverride +### FallbackFlagOverride ```ts -type FallbackFlagOverride = - | { - key: string; - payload: any; - } - | true; +type FallbackFlagOverride = FlagValue; ``` *** -### Feedback +### Feedback ```ts type Feedback = UnassignedFeedback & { @@ -2698,7 +2794,7 @@ type Feedback = UnassignedFeedback & { }; ``` -#### Type declaration +#### Type declaration
@@ -2748,7 +2844,7 @@ User ID from your own application. *** -### FeedbackOptions +### FeedbackOptions ```ts type FeedbackOptions = { @@ -2761,7 +2857,7 @@ type FeedbackOptions = { }; ``` -#### Type declaration +#### Type declaration
@@ -2815,7 +2911,7 @@ Enables automatic feedback prompting if it's set up in Reflag - - - - - - - -
\{ - `position`: [`Position`](globals.md#position-1); + `position`: [`Position`](globals.md#position); `translations`: [`Partial`](https://www.typescriptlang.org/docs/handbook/utility-types.html#partialtype)\<[`FeedbackTranslations`](globals.md#feedbacktranslations)\>; \} @@ -2834,7 +2930,7 @@ With these options you can override the look of the feedback prompt -[`Position`](globals.md#position-1) +[`Position`](globals.md#position) @@ -2866,7 +2962,7 @@ Undefined translation keys fall back to english defaults. *** -### FeedbackPrompt +### FeedbackPrompt ```ts type FeedbackPrompt = { @@ -2878,7 +2974,7 @@ type FeedbackPrompt = { }; ``` -#### Type declaration +#### Type declaration @@ -2979,13 +3075,13 @@ Feedback prompt will not be shown after this time *** -### FeedbackPromptHandler() +### FeedbackPromptHandler() ```ts type FeedbackPromptHandler = (prompt: FeedbackPrompt, handlers: FeedbackPromptHandlerCallbacks) => void; ``` -#### Parameters +#### Parameters
@@ -3022,13 +3118,13 @@ type FeedbackPromptHandler = (prompt: FeedbackPrompt, handlers: FeedbackPromptHa
-#### Returns +#### Returns `void` *** -### FeedbackPromptHandlerCallbacks +### FeedbackPromptHandlerCallbacks ```ts type FeedbackPromptHandlerCallbacks = { @@ -3037,7 +3133,7 @@ type FeedbackPromptHandlerCallbacks = { }; ``` -#### Type declaration +#### Type declaration @@ -3076,10 +3172,10 @@ type FeedbackPromptHandlerCallbacks = { *** -### FeedbackPromptHandlerOpenFeedbackFormOptions +### FeedbackPromptHandlerOpenFeedbackFormOptions ```ts -type FeedbackPromptHandlerOpenFeedbackFormOptions = Omit ```ts type FeedbackPromptReply = { @@ -3101,7 +3197,7 @@ type FeedbackPromptReply = { }; ``` -#### Type declaration +#### Type declaration
@@ -3164,7 +3260,7 @@ type FeedbackPromptReply = { *** -### FeedbackPromptReplyHandler() +### FeedbackPromptReplyHandler() ```ts type FeedbackPromptReplyHandler = (reply: T) => T extends null ? Promise : Promise<{ @@ -3172,7 +3268,7 @@ type FeedbackPromptReplyHandler = (reply: T) => T extends null ? Promise; ``` -#### Type Parameters +#### Type Parameters
@@ -3191,7 +3287,7 @@ type FeedbackPromptReplyHandler = (reply: T) => T extends null ? Promise
-#### Parameters +#### Parameters @@ -3216,7 +3312,7 @@ type FeedbackPromptReplyHandler = (reply: T) => T extends null ? Promise
-#### Returns +#### Returns `T` *extends* `null` ? [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> : [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<\{ `feedbackId`: `string`; @@ -3224,7 +3320,7 @@ type FeedbackPromptReplyHandler = (reply: T) => T extends null ? Promise ```ts type FeedbackTranslations = { @@ -3246,7 +3342,7 @@ type FeedbackTranslations = { You can use this to override text values in the feedback form with desired language translation -#### Type declaration +#### Type declaration @@ -3405,132 +3501,121 @@ with desired language translation *** -### FlagOverrides +### FlagDefaultFor\ ```ts -type FlagOverrides = Record; +type FlagDefaultFor = keyof Registry extends never ? FlagDefaultValue | object : Key extends keyof Registry ? ReadonlyFlagValue | null : never; ``` -*** +Registered defaults match the value schema; null explicitly requests arbitrary JSON. -### FlagRemoteConfig - -```ts -type FlagRemoteConfig = - | { - key: string; - payload: any; - } - | { - key: undefined; - payload: undefined; -}; -``` - -A remotely managed configuration value for a flag. - -#### Type declaration - -\{ - `key`: `string`; - `payload`: `any`; - \} +#### Type Parameters
- - - + + + - + +
NameTypeDescriptionType Parameter
-`key` +`Registry`
-`string` +`Key` *extends* `PropertyKey` +
-The key of the matched configuration value. +*** -
+### FlagDefaultValue -`payload` +```ts +type FlagDefaultValue = + | null + | boolean + | number + | string + | readonly FlagDefaultValue[] +| {}; +``` - +*** + +### FlagOverrides + +```ts +type FlagOverrides = Record; +``` + +*** + +### FlagValue -`any` +```ts +type FlagValue = + | null + | boolean + | number + | string + | FlagValue[] +| {}; +``` - +*** -The optional user-supplied payload data. +### FlagValueFromDefault\ -
+```ts +type FlagValueFromDefault = T extends null ? FlagValue : T extends boolean ? boolean : T extends number ? number : T extends string ? string : T extends readonly infer Element[] ? [Element] extends [never] ? FlagValue[] : FlagValueFromDefault[] : T extends object ? { -readonly [Key in keyof T]: FlagValueFromDefault } : never; +``` -\{ - `key`: `undefined`; - `payload`: `undefined`; - \} +Widen literals and return mutable copies. Null requests arbitrary JSON. + +#### Type Parameters - - + - - - +
NameTypeType Parameter
-`key` - - - -`undefined` +`T`
- -`payload` +
-
+*** -`undefined` +### FlagValues -
+```ts +type FlagValues = Record; +``` *** -### InitOptions +### InitOptions ```ts type InitOptions = ReflagDeprecatedContext & { apiBaseUrl: string; appBaseUrl: string; - bootstrappedFlags: RawFlags; bootstrappedState: BootstrappedState; credentials: "include" | "same-origin" | "omit"; enableLiveFlagUpdates: boolean; @@ -3561,7 +3646,7 @@ type InitOptions = ReflagDeprecatedContext & { ReflagClient initialization options. -#### Type declaration +#### Type declaration @@ -3609,28 +3694,6 @@ Base URL of the Reflag web app. Links open ín this app by default. - - - - - @@ -3758,10 +3821,8 @@ If set, flags will be cached between page loads for this duration @@ -3790,7 +3851,7 @@ AutoFeedback specific configuration - - +
-`bootstrappedFlags`? - - - -[`RawFlags`](globals.md#rawflags) - - - -Pre-fetched flags used for the initial flag state. -The client fetches opt-in metadata on demand when opt-in flags are requested. - -**Deprecated** - -Use `bootstrappedState` instead. - -
- `bootstrappedState`? -Flag keys for which `isEnabled` should fallback to true -if SDK fails to fetch flags from Reflag servers. If a record -is supplied instead of array, the values of each key represent the -configuration values and `isEnabled` is assume `true`. +Value-only startup fallbacks. An array enables the listed Boolean flags. +Fallback values never identify an authored selection.
-[`Logger`](globals.md#logger-1) +[`Logger`](globals.md#logger) @@ -4062,7 +4123,7 @@ Deprecated: retries are no longer performed for bulk delivery. *** -### Offset +### Offset ```ts type Offset = { @@ -4071,7 +4132,7 @@ type Offset = { }; ``` -#### Type declaration +#### Type declaration @@ -4121,7 +4182,7 @@ Offset from the nearest vertical screen edge after placement is resolved *** -### OptInFlag +### OptInFlag ```ts type OptInFlag = RawFlagOptIn & { @@ -4130,7 +4191,7 @@ type OptInFlag = RawFlagOptIn & { }; ``` -#### Type declaration +#### Type declaration
@@ -4180,7 +4241,7 @@ Flag key. *** -### PopoverPlacement +### PopoverPlacement ```ts type PopoverPlacement = Placement; @@ -4188,10 +4249,10 @@ type PopoverPlacement = Placement; *** -### Position +### Position ```ts -type Position = +type Position = | { type: "MODAL"; } @@ -4209,38 +4270,26 @@ type Position = *** -### RawFlag +### RawFlag ```ts type RawFlag = { - config: { - evaluationErrors: RawFlag["evaluationErrors"]; - key: string; - missingContextFields: string[]; - payload: any; - ruleEvaluationResults: boolean[]; - version: number; - }; - evaluationErrors: { - code: string; - field: string; - message: string; - operator: string; - }[]; - isEnabled: boolean; - isEnabledOverride: boolean | null; - key: string; - missingContextFields: string[]; + allocationIndex: number; + errors: EvaluationError[]; + matchedRuleId: string; optIn: RawFlagOptIn | null; optInEnabled: boolean; - ruleEvaluationResults: boolean[]; - targetingVersion: number; + resolved: boolean; + ruleResults: RuleEvaluationResult[]; + sourceVersionId: string; + value: FlagValue | undefined; + variantKey: string; }; ``` -A flag fetched from the server. +Evaluated diagnostics for v2 transport/bootstrap, not a flag wrapper. -#### Type declaration +#### Type declaration
@@ -4254,48 +4303,41 @@ A flag fetched from the server. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - @@ -4549,7 +4475,7 @@ Version of targeting rules. *** -### RawFlagOptIn +### RawFlagOptIn ```ts type RawFlagOptIn = { @@ -4561,7 +4487,7 @@ type RawFlagOptIn = { }; ``` -#### Type declaration +#### Type declaration
- `config`? + `allocationIndex`? -\{ - `evaluationErrors`: [`RawFlag`](globals.md#rawflag)\[`"evaluationErrors"`\]; - `key`: `string`; - `missingContextFields`: `string`[]; - `payload`: `any`; - `ruleEvaluationResults`: `boolean`[]; - `version`: `number`; - \} +`number` -Optional user-defined dynamic configuration. +‐
-`config.evaluationErrors`? + `errors` -[`RawFlag`](globals.md#rawflag)\[`"evaluationErrors"`\] +[`EvaluationError`](globals.md#evaluationerror)[] -Non-fatal diagnostics produced while evaluating targeting rules. +‐
-`config.key` + `matchedRuleId`? @@ -4305,108 +4347,48 @@ Non-fatal diagnostics produced while evaluating targeting rules. -The key of the matched configuration value. - -
- -`config.missingContextFields`? - - - -`string`[] - - - -The missing context fields. - -**Deprecated** - -Use `evaluationErrors` and check for `MISSING_CONTEXT_FIELD`. - -
- -`config.payload`? - - - -`any` - - - -The optional user-supplied payload data. - -
- -`config.ruleEvaluationResults`? - - - -`boolean`[] - - - -The rule evaluation results. +‐
-`config.version`? + `optIn`? -`number` +[`RawFlagOptIn`](globals.md#rawflagoptin) \| `null` -The version of the matched configuration value. +‐
- `evaluationErrors`? + `optInEnabled`? -\{ - `code`: `string`; - `field`: `string`; - `message`: `string`; - `operator`: `string`; - \}[] +`boolean` -Non-fatal diagnostics produced while evaluating targeting rules. +Absent in Node bootstrap/older snapshots; null optIn means unavailable.
- `isEnabled` + `resolved` @@ -4416,32 +4398,31 @@ Non-fatal diagnostics produced while evaluating targeting rules. -Result of flag evaluation. -Note: does not take local overrides into account. +‐
- `isEnabledOverride`? + `ruleResults` -`boolean` \| `null` +[`RuleEvaluationResult`](globals.md#ruleevaluationresult)[] -If not null or undefined, the result is being overridden locally +‐
- `key` + `sourceVersionId`? @@ -4451,96 +4432,41 @@ If not null or undefined, the result is being overridden locally -Flag key. - -
- - `missingContextFields`? - - - -`string`[] - - - -Missing context fields. - -**Deprecated** - -Use `evaluationErrors` and check for `MISSING_CONTEXT_FIELD`. - -
- - `optIn`? - - - -[`RawFlagOptIn`](globals.md#rawflagoptin) \| `null` - - - -Opt-in metadata for this flag and the current context. - -
- - `optInEnabled`? - - - -`boolean` - - - -Whether end-user opt-in is enabled for this flag. +‐
- `ruleEvaluationResults`? + `value` -`boolean`[] +[`FlagValue`](globals.md#flagvalue) \| `undefined` -Rule evaluation results. +‐
- `targetingVersion`? + `variantKey`? -`number` +`string` -Version of targeting rules. +‐
@@ -4662,7 +4588,7 @@ Whether the current user has opted into the flag. *** -### RawFlags +### RawFlags ```ts type RawFlags = Record; @@ -4670,7 +4596,7 @@ type RawFlags = Record; *** -### RequestFeedbackData +### RequestFeedbackData ```ts type RequestFeedbackData = Omit & { @@ -4680,7 +4606,7 @@ type RequestFeedbackData = Omit & { }; ``` -#### Type declaration +#### Type declaration
@@ -4751,7 +4677,7 @@ copy of the feedback in your own application or CRM. *** -### RequestFeedbackOptions +### RequestFeedbackOptions ```ts type RequestFeedbackOptions = RequestFeedbackData & { @@ -4759,7 +4685,7 @@ type RequestFeedbackOptions = RequestFeedbackData & { }; ``` -#### Type declaration +#### Type declaration
@@ -4792,7 +4718,93 @@ User ID from your own application. *** -### SetOptInOptions +### RuleEvaluationResult + +```ts +type RuleEvaluationResult = { + allocationIndex: number; + destination: | { + type: "nextRule"; + } + | { + type: "variant"; + variantKey: string; + }; + matched: boolean; + ruleId: string; +}; +``` + +#### Type declaration + +
+ + + + + + + + + + + + + + + + + + + + + + + + +
NameType
+ + `allocationIndex`? + + + +`number` + +
+ + `destination`? + + + + \| \{ + `type`: `"nextRule"`; + \} + \| \{ + `type`: `"variant"`; + `variantKey`: `string`; + \} + +
+ + `matched` + + + +`boolean` + +
+ + `ruleId` + + + +`string` + +
+ +*** + +### SetOptInOptions ```ts type SetOptInOptions = { @@ -4801,9 +4813,9 @@ type SetOptInOptions = { }; ``` -Options for changing the current user or company's opt-in membership. +Represents a flag. -#### Type declaration +#### Type declaration @@ -4853,7 +4865,7 @@ Whether to update the current user or current company. Defaults to `user`. *** -### State +### State ```ts type State = "idle" | "initializing" | "initialized" | "stopped"; @@ -4863,7 +4875,7 @@ State of the client. *** -### StorageAdapter +### StorageAdapter ```ts type StorageAdapter = { @@ -4873,7 +4885,7 @@ type StorageAdapter = { }; ``` -#### Type declaration +#### Type declaration
@@ -4924,10 +4936,10 @@ type StorageAdapter = { *** -### ToolbarOptions +### ToolbarOptions ```ts -type ToolbarOptions = +type ToolbarOptions = | boolean | { position: ToolbarPosition; @@ -4939,7 +4951,7 @@ Toolbar options. *** -### TrackEvent +### TrackEvent ```ts type TrackEvent = { @@ -4951,7 +4963,7 @@ type TrackEvent = { }; ``` -#### Type declaration +#### Type declaration
@@ -5015,7 +5027,7 @@ type TrackEvent = { *** -### UnassignedFeedback +### UnassignedFeedback ```ts type UnassignedFeedback = { @@ -5030,7 +5042,7 @@ type UnassignedFeedback = { }; ``` -#### Type declaration +#### Type declaration
@@ -5170,7 +5182,7 @@ Customer satisfaction score.
- `source`? + `source`? @@ -5190,9 +5202,9 @@ Source of the feedback, depending on how the user was asked
-## Variables +## Variables -### DEFAULT\_TRANSLATIONS +### DEFAULT\_TRANSLATIONS ```ts const DEFAULT_TRANSLATIONS: FeedbackTranslations; @@ -5221,7 +5233,7 @@ export const DEFAULT_TRANSLATIONS: FeedbackTranslations = { *** -### feedbackContainerId +### feedbackContainerId ```ts const feedbackContainerId: "reflag-feedback-dialog-container" = "reflag-feedback-dialog-container"; @@ -5231,7 +5243,7 @@ ID of HTML DIV element which contains the feedback dialog *** -### propagatedEvents +### propagatedEvents ```ts const propagatedEvents: string[]; @@ -5239,6 +5251,8 @@ const propagatedEvents: string[]; These events will be propagated to the feedback dialog -#### See +#### See [https://developer.mozilla.org/en-US/docs/Web/API/Element#events](https://developer.mozilla.org/en-US/docs/Web/API/Element#events) + +Using v1? [Legacy docs](../../legacy/v1/browser-sdk/globals.md) · [Upgrade guide](../migrating-from-v1.md). diff --git a/supported-languages/migrating-from-v1.md b/supported-languages/migrating-from-v1.md new file mode 100644 index 0000000..f093bf1 --- /dev/null +++ b/supported-languages/migrating-from-v1.md @@ -0,0 +1,143 @@ +--- +description: Upgrade Browser, React, Vue and Node.js integrations from protocol v1 to v2. +--- + +# Migrating from v1 + +Version 2 of the Browser, React, Vue and Node.js SDKs changes how you read flags, and includes breaking changes. The [v1 documentation](../legacy/v1/README.md) is still available. + +## What changes + +- **Flags return their value directly.** `useFlag("new-editor")` returns `true` or `false` instead of `{ isEnabled }`. +- **Remote config is a Multivariate flag.** Pass a default and get the value back, instead of reading `.config.payload`. +- **Tracking and feedback are separate.** They have their own hooks and client methods instead of being returned with a flag. +- **React's `useFlag()` no longer suspends.** Use `useFlagSuspense()` when you want Suspense. +- **v1 bootstrap data, fallback snapshots and generated types don't work with v2.** Regenerate them. + +React Native, OpenFeature and the Management SDK are released separately and aren't covered by this guide. + +## Upgrade the packages + +{% hint style="warning" %} +These pages document the `2.0.0-next.0` prerelease. Until stable v2 packages are published, install the exact prerelease versions you were given: an unversioned install or the `@next` tag may not give you v2. The `@2` commands below work once v2 is published. +{% endhint %} + +Update the SDKs your application uses: + +```sh +# Choose the SDKs used by your application. +npm install @reflag/browser-sdk@2 +npm install @reflag/react-sdk@2 +npm install @reflag/vue-sdk@2 +npm install @reflag/node-sdk@2 + +# If you generate flag types: +npm install --save-dev @reflag/cli@2 +``` + +Then work through the steps below. + +## 1. Read values directly + +### Browser and Node.js + +```ts +// v1 +const { isEnabled } = boundClient.getFlag("new-editor"); + +// v2: Browser client or context-bound Node client +const enabled = boundClient.getFlag("new-editor"); +const settings = boundClient.getFlag("editor-settings", { maxItems: 10 }); +``` + +On the unbound Node client, pass context first: + +```ts +const enabled = client.getFlag(context, "new-editor"); +const settings = client.getFlag(context, "editor-settings", { maxItems: 10 }); +``` + +### React + +```tsx +// v1 +const { isEnabled } = useFlag("new-editor"); + +// v2 +const enabled = useFlag("new-editor"); +const settings = useFlag("editor-settings", { maxItems: 10 }); +``` + +### Vue + +```ts +// v1 +const { isEnabled } = useFlag("new-editor"); + +// v2 +const enabled = useFlag("new-editor"); +// enabled.value in script; refs unwrap automatically in templates +const settings = useFlag("editor-settings", { maxItems: 10 }); +``` + +Without a default, a read returns a Boolean: `false` if the flag is missing. Pass a default to read any other value; the return type follows the default. Pass `null` to accept any JSON value and narrow it yourself. + +`getFlags()` now returns a record of values, such as `{ "new-editor": true }`. + +## 2. Migrate remote config explicitly + +v2 has no `.config` property. Create a Multivariate flag with a new key and the values your application needs, then read it with a default: + +```ts +// v1 +const { config } = useFlag("editor-settings"); +const maxItems = config.payload?.maxItems ?? 10; + +// v2 +const { maxItems } = useFlag("editor-config", { maxItems: 10 }); +``` + +Existing remote config is **not converted automatically**. If a v1 flag controlled both access and configuration, keep the existing Boolean flag for access and use the new Multivariate flag for settings. Follow the [Remote config migration steps](../product-handbook/multivariate-flags.md#migrating-from-remote-config). + +## 3. Separate usage tracking and feedback + +React and Vue use their dedicated hooks/composables rather than methods returned by `useFlag()`: + +```ts +const track = useTrack(); +const requestFeedback = useRequestFeedback(); +track("Document created"); +requestFeedback({ flagKey: "new-editor", title: "How is the new editor?" }); +``` + +In Browser and Node.js, call `track()` and the feedback methods on the client. Either way, you name the event you track; configure your flag's adoption rules to match it. + +## 4. Update loading and Suspense + +- React `useFlag()` never suspends. Use `useFlagSuspense()` for a suspending read, or `useIsLoading()` / the provider's `loadingComponent` for loading presentation. +- React's second `useFlag()` argument is the fallback value, not `{ suspense: ... }` options. +- Vue returns a ref containing the direct value; use `useIsLoading()` or the provider's loading slot for loading presentation. +- `useOptInFlags()` is unchanged: its entries still include `isEnabled` and the opt-in fields. + +## 5. Upgrade bootstrap and saved state together + +Generate bootstrap data with Node.js SDK v2 and pass the whole object returned by `getFlagsForBootstrap()` to Browser, React or Vue SDK v2, not just its `flags` property. + +v1 and v2 bootstrap data aren't compatible, so upgrade the server and client SDKs together. Anything still on v1, such as React Native, needs bootstrap data from Node.js SDK v1. + +Saved state doesn't carry over. The Browser SDK starts with a fresh cache and no overrides, and Node.js fallback providers store v2 snapshots separately from v1 ones. Let a v2 process fetch flags once to save a new snapshot; don't rename v1 snapshot files. + +## 6. Regenerate types and review overrides + +Regenerate flag types with CLI 2. Generated types are optional in v2, because the default you pass already determines the return type. See [Type safety](../product-handbook/type-safety.md). + +Overrides and static fallback values are now plain values, such as `true` or `{ maxItems: 5 }`. In the Browser SDK, `undefined` removes an override, while `null` sets the value to `null`. Run your offline and outage tests against v2 before upgrading production. + +## SDK documentation + +| SDK | Current v2 | Legacy v1 | +| ------- | -------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | +| Browser | [Guide](browser-sdk/README.md) · [Reference](browser-sdk/globals.md) | [Guide](../legacy/v1/browser-sdk/README.md) · [Reference](../legacy/v1/browser-sdk/globals.md) | +| React | [Guide](react-sdk/README.md) · [Reference](react-sdk/globals.md) | [Guide](../legacy/v1/react-sdk/README.md) · [Reference](../legacy/v1/react-sdk/globals.md) | +| Vue | [Guide](vue-sdk/README.md) · [Reference](vue-sdk/globals.md) | [Guide](../legacy/v1/vue-sdk/README.md) · [Reference](../legacy/v1/vue-sdk/globals.md) | +| Node.js | [Guide](node-sdk/README.md) · [Reference](node-sdk/globals.md) | [Guide](../legacy/v1/node-sdk/README.md) · [Reference](../legacy/v1/node-sdk/globals.md) | diff --git a/supported-languages/next.js.md b/supported-languages/next.js.md index 2b58030..bf02175 100644 --- a/supported-languages/next.js.md +++ b/supported-languages/next.js.md @@ -1,84 +1,58 @@ --- -description: Next.js client for Reflag +description: Use the Node.js and React SDKs with Next.js. --- # Next.js -Using Reflag with Next.js is straightforward. You can use the [@reflag/node-sdk](https://github.com/reflagcom/docs/blob/main/supported-languages/node-sdk/README.md) on the server or [@reflag/react-sdk](https://github.com/reflagcom/docs/blob/main/supported-languages/react-sdk/README.md) in the browser. Handling flag targeting server-side is often advantageous because it removes the need for additional handling of loading states. +Use the [Node.js SDK](node-sdk/README.md) to evaluate flags on the server and the [React SDK](react-sdk/README.md) in client components. -## Server-side Rendering (SSR) +This page covers SDK v2. -It's often advantageous to use Server-side Rendering when possible because it can help avoid extra loading screens while your Reflag flags are loading. +## Server-side rendering -For pages that use server-side rendering, use the `@reflag/node-sdk` in the following manner. Create a new file called `reflag.ts` and adjust it to your needs: +Create one client per server process. Share the initialization promise so concurrent requests do not create separate clients: -```typescript +```ts // app/reflag.ts import { ReflagClient } from "@reflag/node-sdk"; -import { auth } from "@/auth"; +const client = new ReflagClient({ secretKey: process.env.REFLAG_SECRET_KEY }); +let initialized: Promise | undefined; -export let reflagClient: ReflagClient; - -async function initReflag() { - reflagClient = new ReflagClient({ - secretKey: process.env.REFLAG_SECRET_KEY ?? "", - logger: console, +export async function getReflagClient() { + initialized ??= client.initialize().then(() => undefined).catch((error) => { + initialized = undefined; + throw error; }); - await reflagClient.initialize(); -} - -export async function getContext() { - // get the logged-in session - const session = await auth(); - const user = session?.user; - if (!user || !user.id) { - return {}; - } - const userId = user.id; - - return { - user: { - id: userId, - ...user, - }, - company: session.company, - }; -} - -export async function getFlag(key: string) { - if (!reflagClient) { - await initReflag(); - } - - return reflagClient.getFlag(await getContext(), key); + await initialized; + return client; } ``` -And then start using flags! +Build the user and company context from your authenticated session on the server. The examples below assume a `getContext()` helper in your application that does this. {% tabs %} {% tab title="App router" %} -Here's how you use flags with App router: - ```tsx -// members-add/page.tsx -import { getFlag } from "@/app/reflag"; +// app/members-add/page.tsx +import { getReflagClient } from "@/app/reflag"; +import { getContext } from "@/app/auth"; -async addMember() { +async function addMember() { "use server"; - const { track } = await getFlag("member-add"); - track() + const client = await getReflagClient(); + const bound = client.bindClient(await getContext()); + if (!bound.getFlag("members-add")) throw new Error("Access denied"); - // add member + // Perform the authorized operation here, then track successful usage. + await bound.track("Member added"); + await client.flush(); } export default async function Page() { - const { isEnabled } = await getFlag("members-add"); - - if (!isEnabled) { - return null; - } + const client = await getReflagClient(); + const enabled = client.getFlag(await getContext(), "members-add"); + if (!enabled) return null; return (
@@ -88,95 +62,66 @@ export default async function Page() { } ``` {% endtab %} - {% tab title="Pages router" %} -Here's how you use flags with Pages router: - ```tsx -// members-add/page.tsx -import { getFlag } from "@/app/reflag"; -import type { InferGetServerSidePropsType, GetServerSideProps } from "next"; +// pages/members-add.tsx +import type { GetServerSideProps, InferGetServerSidePropsType } from "next"; +import { getReflagClient } from "@/app/reflag"; +import { getContext } from "@/app/auth"; export const getServerSideProps = (async () => { - const { isEnabled: membersAddEnabled } = await getFlag("members-add"); - return { props: { membersAddEnabled } }; -}) satisfies GetServerSideProps<{ membersAddEnabled: boolean }>; - -export default function Page({ - huddles, -}: InferGetServerSidePropsType) { - if (!membersAddEnabled) return null; - - return ( - - - - ); + const client = await getReflagClient(); + const enabled = client.getFlag(await getContext(), "members-add"); + return { props: { enabled } }; +}) satisfies GetServerSideProps<{ enabled: boolean }>; + +export default function Page({ enabled }: InferGetServerSidePropsType) { + if (!enabled) return null; + return

You can add members.

; } ``` {% endtab %} {% endtabs %} -### Flags SDK by Vercel - -[Flags SDK by Vercel](https://flags-sdk.dev/) is a Next.js oriented interface for server-side flags. It's straightforward to use with the Reflag Node.js SDK: +The server action checks the flag again, because hiding a button doesn't stop someone from calling the action directly. Configure the flag's adoption rules to match the event name you track. To read a configuration value, pass a default after the key, for example `client.getFlag(context, "member-settings", { maxMembers: 10 })`. -```typescript -import { flag } from '@vercel/flags/next'; -import { getFlag } from "@/app/reflag"; +### Flags SDK by Vercel -export const huddles = flag({ - key: 'huddles', - async decide() { - return getFlag(this.key).isEnabled; - }, -}); -``` +When using a custom Vercel Flags SDK definition, return the Boolean flag value from its `decide` function. See the [Reflag provider integration](https://flags-sdk.dev/providers/reflag) for setup and compatibility. -## Client-side Rendering +## Client-side rendering -Use `@reflag/react-sdk` with Next.js client-side rendering like so: +Put the provider in a client component. In the browser, use your publishable key; the secret key stays on the server: ```tsx -// layout.tsx -import { ReflagProvider } from "@reflag/react-sdk"; - -import { useUser } from "./auth"; +"use client"; -export default function Layout({ children }: { children: React.ReactNode }) { - const { user } = useUser() +import type { ReactNode } from "react"; +import { ReflagProvider, useFlag, useTrack } from "@reflag/react-sdk"; +export function FlagProvider({ children }: { children: ReactNode }) { return ( {children} ); } +export function StartHuddle() { + const enabled = useFlag("huddle"); + const track = useTrack(); + if (!enabled) return null; + return ; +} ``` -In a client components, use the hooks `useFlag` - -```tsx -"use client"; - -import { useFlag } from "@reflag/react-sdk"; - -function StartHuddle() { - const { isEnabled, track } = useFlag("huddle"); +Replace the example IDs with your signed-in user and company. For a loading UI, use `useIsLoading()` or the provider's `loadingComponent` prop, or use `useFlagSuspense()` to wait with React Suspense. - if (!isEnabled) { - return null - } +## Server-to-client bootstrap - return ( - - ); -} -``` +To render flags on the client immediately, evaluate them on the server with the Node.js SDK's `getFlagsForBootstrap()` and pass the result to the React SDK's `ReflagBootstrappedProvider`. See [Bootstrap from the server](react-sdk/README.md#bootstrap-from-the-server) in the React SDK guide. -For more details, please see the [React SDK documentation](https://github.com/bucketco/docs/blob/main/supported-languages/react-sdk/README.md) +Using v1? [Legacy docs](../legacy/v1/README.md) · [Upgrade guide](migrating-from-v1.md). diff --git a/supported-languages/node-sdk/README.md b/supported-languages/node-sdk/README.md index 8fc901e..1050edc 100644 --- a/supported-languages/node-sdk/README.md +++ b/supported-languages/node-sdk/README.md @@ -1,1073 +1,267 @@ --- +layout: + visible: true title: visible: true +description: + visible: false tableOfContents: visible: true outline: visible: true pagination: visible: true -layout: - width: default - title: - visible: true - description: - visible: true - tableOfContents: - visible: true - outline: - visible: true - pagination: - visible: true - metadata: - visible: true - tags: - visible: true - actions: - visible: true - anchors: - visible: true --- -# Node.js SDK +# Reflag Node.js SDK -Node.js, JavaScript/TypeScript client for [Reflag.com](https://reflag.com). +Feature flags, remote configuration and usage tracking for Node.js servers. -Reflag supports flag toggling, tracking flag usage, collecting feedback on features, and [remotely configuring flags](./#remote-config). +This page covers SDK v2. -## Installation +## Get started -Install using your favorite package manager: +### 1. Create a client -{% tabs %} -{% tab title="npm" %} -```sh -npm i @reflag/node-sdk -``` -{% endtab %} +Install the SDK: -{% tab title="yarn" %} ```sh yarn add @reflag/node-sdk ``` -{% endtab %} -{% tab title="bun" %} -```sh -bun add @reflag/node-sdk -``` -{% endtab %} +Create one client per process with your environment's **secret** key, found in your Reflag environment settings. Initialize it before reading flags: -{% tab title="pnpm" %} -```sh -pnpm add @reflag/node-sdk -``` -{% endtab %} - -{% tab title="deno" %} -```sh -deno add npm:@reflag/node-sdk -``` -{% endtab %} -{% endtabs %} - -Other supported languages/frameworks are in the [Supported languages](https://docs.reflag.com/quickstart/supported-languages) documentation pages. - -You can also [use the HTTP API directly](https://docs.reflag.com/api/http-api) - -## Basic usage - -To get started you need to obtain your secret key from the [environment settings](https://app.reflag.com/env-current/settings/app-environments) in Reflag. - -Reflag will load settings through the various environment variables automatically (see [Configuring](./#configuring) below). - -1. Find the Reflag secret key for your development environment under [environment settings](https://app.reflag.com/env-current/settings/app-environments) in Reflag. -2. Set `REFLAG_SECRET_KEY` in your `.env` file -3. Create a `reflag.ts` file containing the following: - -```typescript +```ts import { ReflagClient } from "@reflag/node-sdk"; -// Create a new instance of the client with the secret key. Additional options -// are available, such as supplying a logger and other custom properties. -// -// We recommend that only one global instance of `client` should be created -// to avoid multiple round-trips to our servers. -export const reflagClient = new ReflagClient(); - -// Initialize the client and begin fetching flag targeting definitions. -// You must call this method prior to any calls to `getFlags()`, -// otherwise an empty object will be returned. -reflagClient.initialize().then(() => { - console.log("Reflag initialized!"); +export const reflag = new ReflagClient({ + secretKey: process.env.REFLAG_SECRET_KEY, }); +await reflag.initialize(); ``` -Once the client is initialized, you can obtain flags along with the `isEnabled` status to indicate whether the flag is targeted for this user/company: - -{% hint style="warning" %} -If `user.id` is not given, the whole `user` object is ignore. Similarly, without `company.id` the `company` object is ignored. -{% endhint %} - -```typescript -// configure the client -const boundClient = reflagClient.bindClient({ - user: { - id: "john_doe", - name: "John Doe", - email: "john@acme.com", - avatar: "https://example.com/users/jdoe", - }, - company: { - id: "acme_inc", - name: "Acme, Inc.", - avatar: "https://example.com/companies/acme", - }, -}); - -// get the huddle flag using company, user and custom context to -// evaluate the targeting. -const { isEnabled, track, config } = boundClient.getFlag("huddle"); - -if (isEnabled) { - // this is your flag gated code ... - // send an event when the flag is used: - track(); - - if (config?.key === "zoom") { - // this code will run if a given remote configuration - // is set up. - } +Keep the secret key on your server. - // CAUTION: if you plan to use the event for automated feedback surveys - // call `flush` immediately after `track`. It can optionally be awaited - // to guarantee the sent happened. - boundClient.flush(); -} -``` +### 2. Create a flag -You can also use the `getFlags()` method which returns a map of all flags: +Install the Reflag CLI and create a flag: -```typescript -// get the current flags (uses company, user and custom context to -// evaluate the flags). -const flags = boundClient.getFlags(); -const bothEnabled = flags.huddle?.isEnabled && flags.voiceHuddle?.isEnabled; +```sh +yarn add --dev @reflag/cli +npx reflag new ``` -## High performance flag targeting - -The SDK contacts the Reflag servers when you call `initialize()` and downloads the flags with their targeting rules. These rules are then matched against the user/company information you provide to `getFlags()` (or through `bindClient(..).getFlags()`). That means the `getFlags()` call does not need to contact the Reflag servers once `initialize()` has completed. By default, `ReflagClient` uses `flagsSyncMode: "push"`, which keeps targeting rules up to date via live SSE updates. You can switch `flagsSyncMode` to `polling` for periodic background refreshes or `in-request` for request-driven refreshes instead. - -### Batch Operations +The first time you run it, it signs you in to Reflag, saves its settings in `reflag.config.json` and generates types for your flags in `gen/flags.d.ts`. Choose `node` when asked for the output format, and make sure your `tsconfig.json` includes the generated file. You can also create flags in the Reflag app. -The SDK automatically batches operations like user/company updates and flag tracking events to minimize API calls. The batch buffer is configurable through the client options: +### 3. Read the flag -```typescript -const client = new ReflagClient({ - batchOptions: { - maxSize: 100, // Maximum number of events to batch - intervalMs: 10000, // Flush interval in milliseconds (default: 10000) - }, -}); -``` +Read a flag for a user and company: -You can manually flush the batch buffer at any time: +```ts +const context = { + user: { id: "user-1" }, + company: { id: "acme", plan: "enterprise" }, +}; -```typescript -await client.flush(); +if (reflag.getFlag(context, "new-editor")) { + // Show the new editor +} ``` -{% hint style="success" %} -It's recommended to call `flush()` before your application shuts down to ensure all events are sent. -{% endhint %} - -### Rate Limiting - -The SDK includes automatic rate limiting for flag events to prevent overwhelming the API. Rate limiting is applied per unique combination of flag key and evaluation context. This behavior is built in and does not currently require configuration. - -### Flag definitions +The SDK downloads your flag definitions and evaluates flags locally, so reads don't make network requests. -Flag definitions include the rules needed to determine which flags should be enabled and which config values should be applied to any given user/company. Flag definitions are automatically fetched when calling `initialize()`. They are then cached and refreshed in the background. Ordinary refreshes use ETags to avoid downloading unchanged definitions. A `304 Not Modified` response keeps the cached definitions and resets their freshness without recompiling rules or writing a new fallback snapshot. Initial fetches and refreshes with a `waitForVersion` target remain unconditional. When a fallback provider is configured, the SDK retains the ETag only after the snapshot is saved successfully. A failed or pending save keeps ordinary refreshes unconditional so persistence can recover, without delaying flag availability. +## Read flags -Custom HTTP clients can enable this optimization by returning the exact ETag value in `HttpClientResponse.etag` and returning 304 responses with `body: undefined`. Clients that omit the ETag continue using full fetches. +Pass a context and a flag key to check whether the flag is enabled: -It's also possible to get the currently in use flag definitions: - -```typescript -import fs from "fs"; - -const client = new ReflagClient(); - -const flagDefs = await client.getFlagDefinitions(); -// [{ -// key: "huddle", -// description: "Live voice conversations with colleagues." -// flag: { ... } -// config: { ... } -// }] +```ts +const enabled = reflag.getFlag(context, "new-editor"); // true or false ``` -### Fallback provider - -`flagsFallbackProvider` is a reliability feature that lets the SDK persist the latest successfully fetched raw flag definitions to fallback storage such as a local file, Redis, S3, GCS, or a custom backend. - -{% hint style="info" %} -`fallbackFlags` is deprecated. Prefer `flagsFallbackProvider` for startup fallback and outage recovery. `flagsFallbackProvider` is not used in offline mode. -{% endhint %} - -#### How it works - -Reflag servers remain the primary source of truth. On `initialize()`, the SDK always tries to fetch a live copy of the flag definitions first, and it continues refreshing those definitions from the Reflag servers over time. - -If that initial live fetch fails, the SDK can call `flagsFallbackProvider.load()` and start with the last saved snapshot instead. This is mainly useful for cold starts in the exceedingly rare case that Reflag has an outage. - -If Reflag becomes unavailable after the SDK has already initialized successfully, the SDK keeps using the last successfully fetched definitions it already has in memory. In other words, the fallback provider is mainly what helps future processes start, not what keeps an already running process alive. - -After successfully fetching updated flag definitions, the SDK calls `flagsFallbackProvider.save()` to keep the stored snapshot up to date. - -Typical reliability flow: - -1. The SDK starts and tries to fetch live flag definitions from Reflag. -2. If that succeeds, those definitions are used immediately and the SDK continues operating normally. -3. After successfully fetching updated flag definitions, the SDK saves the latest snapshot through the fallback provider so a recent copy is available if needed later. -4. If a future process starts while Reflag is unavailable, it can load the last saved snapshot from the fallback provider and still initialize. -5. Once Reflag becomes available again, the SDK resumes using live data and refreshes the fallback snapshot. - -Most deployments run multiple SDK processes, so more than one process may save identical flag definitions to the fallback storage at roughly the same time. This is expected and generally harmless for backends like a local file, Redis, S3, or GCS because the operation is cheap. In practice, this only becomes worth thinking about once you have many thousands of SDK processes writing to the same fallback storage. - -{% hint style="success" %} -If you are building a web or client-side application and want the most resilient setup, combine `flagsFallbackProvider` on the server with bootstrapped flags on the client. +To read a configuration value, pass a default as the third argument. You get back a value of the same type as the default: -`flagsFallbackProvider` helps new server processes start if they cannot reach Reflag during initialization. Bootstrapping helps clients render from server-provided flags instead of depending on an initial client-side fetch from the Reflag servers. - -This applies to React (`getFlagsForBootstrap()` + `ReflagBootstrappedProvider`), React Native, the Browser SDK (`bootstrappedState`), and the Vue SDK (bootstrapped flags via the provider). -{% endhint %} - -#### Built-in providers - -You can access the built-in providers through the `fallbackProviders` namespace: - -* `fallbackProviders.static(...)` -* `fallbackProviders.file(...)` -* `fallbackProviders.redis(...)` -* `fallbackProviders.s3(...)` -* `fallbackProviders.gcs(...)` - -**Static provider** - -If you just want a fixed fallback copy of simple enabled/disabled flags, you can provide a static map: - -```typescript -import { ReflagClient, fallbackProviders } from "@reflag/node-sdk"; - -const client = new ReflagClient({ - secretKey: process.env.REFLAG_SECRET_KEY, - flagsFallbackProvider: fallbackProviders.static({ - flags: { - huddle: true, - "smart-summaries": false, - }, - }), -}); - -await client.initialize(); +```ts +const model = reflag.getFlag(context, "model", "quick"); // string +const limits = reflag.getFlag(context, "limits", { maxItems: 10 }); // { maxItems: number } ``` -**File provider** +If the flag doesn't exist, or its value has a different type, you get `false`, or your default if you passed one. Pass `null` as the default to accept any JSON value and narrow it yourself. -```typescript -import { ReflagClient, fallbackProviders } from "@reflag/node-sdk"; +The SDK checks only the top-level type of a value. If your application depends on nested fields, validate them. -const client = new ReflagClient({ - secretKey: process.env.REFLAG_SECRET_KEY, - flagsFallbackProvider: fallbackProviders.file({ - directory: ".reflag", - }), -}); +`getFlags(context)` returns all flag values as a record; a value can be `undefined` if the flag is unavailable. -await client.initialize(); -``` +Each read records a check, which Reflag uses for launch monitoring. -The file provider stores one snapshot file per environment in the configured `directory`, using the filename `flags-fallback-.json`. +## Bind a client to a request -**Redis provider** +To avoid passing the context on every call, bind it once, for example per request: -The built-in Redis provider creates a Redis client automatically when omitted and uses `REDIS_URL` from the environment. It stores snapshots under the configured `keyPrefix` and appends the first 16 characters of the secret key hash to that prefix. +```ts +const bound = reflag.bindClient(context); -Without a `keyPrefix` set, it will default to the key `reflag:flags-fallback:`. When you provide a custom `keyPrefix`, any trailing `:` is trimmed before the hash suffix is appended. +const model = bound.getFlag("model", "quick"); +const allValues = bound.getFlags(); +``` -```typescript -import { ReflagClient, fallbackProviders } from "@reflag/node-sdk"; +Binding also sends the user's and company's attributes to Reflag, so you can target and filter by them. -const client = new ReflagClient({ - secretKey: process.env.REFLAG_SECRET_KEY, - flagsFallbackProvider: fallbackProviders.redis(), -}); +## Track usage -await client.initialize(); +```ts +await bound.track("Document created", { attributes: { source: "editor" } }); ``` -**S3 provider** - -The built-in S3 provider works out of the box using the AWS SDK's default credential chain and region resolution. It stores the snapshot object under the configured `keyPrefix` and uses the filename `flags-fallback-.json`. +Configure your flag's adoption rules to match the event names you send. Events are sent in batches; see [Shutting down](#shutting-down) to send them before your process exits. -Without a `keyPrefix` set, it will default to the object key `reflag/flags-fallback/flags-fallback-.json`. When you provide a custom `keyPrefix`, any trailing `/` is trimmed before the filename is appended. +## Keep flags up to date -```typescript -import { ReflagClient, fallbackProviders } from "@reflag/node-sdk"; - -const client = new ReflagClient({ - secretKey: process.env.REFLAG_SECRET_KEY, - flagsFallbackProvider: fallbackProviders.s3({ - bucket: "reflag-fallback-bucket", - }), -}); +The client keeps flag definitions up to date in the background. Choose how with `flagsSyncMode`: -await client.initialize(); -``` +- `push` (default): receive updates as soon as flags change. +- `polling`: refresh periodically. +- `in-request`: refresh when flags are read, for environments without long-running background work. -**GCS provider** +Call `await reflag.refreshFlags()` to request a refresh yourself. If a refresh fails, the client keeps using the flags it already has. -The built-in GCS provider works out of the box using Google Cloud's default application credentials. It stores the snapshot object under the configured `keyPrefix` and uses the filename `flags-fallback-.json`. +## Fallback providers -Without a `keyPrefix` set, it will default to the object key `reflag/flags-fallback/flags-fallback-.json`. When you provide a custom `keyPrefix`, any trailing `/` is trimmed before the filename is appended. +A fallback provider saves the latest flag definitions so your service can start even if Reflag is unreachable: -```typescript +```ts import { ReflagClient, fallbackProviders } from "@reflag/node-sdk"; const client = new ReflagClient({ secretKey: process.env.REFLAG_SECRET_KEY, - flagsFallbackProvider: fallbackProviders.gcs({ - bucket: "reflag-fallback-bucket", - }), + flagsFallbackProvider: fallbackProviders.file({ directory: ".reflag" }), }); - -await client.initialize(); -``` - -#### Testing fallback startup locally - -To test fallback startup in your own app, first run it once with a working Reflag connection so a snapshot is saved. Then restart it with the same secret key and fallback provider configuration, but set `apiBaseUrl` (or set the `REFLAG_API_BASE_URL` environment variable) to `http://127.0.0.1:65535`. That forces the live fetch to fail and lets you verify that the SDK initializes from the saved snapshot instead. - -#### Writing a custom provider - -If you just store definitions in your database or similar, a custom provider can be very small: - -```typescript -import type { - FlagsFallbackProvider, - FlagsFallbackSnapshot, -} from "@reflag/node-sdk"; - -export const customFallbackProvider: FlagsFallbackProvider = { - async load(context) { - // load snapshot from database - // optionally, look up the snapshot using the context.secretKeyHash as a key - return snapshot; - }, - - async save(context, snapshot) { - const serialized = JSON.stringify(snapshot); - // write serialized snapshot to database, optionally using context.secretKeyHash as a key - }, -}; -``` - -## Bootstrapping client-side applications - -The `getFlagsForBootstrap()` method is useful whenever you need to pass flag data to another runtime or serialize it without wrapper functions. Server-side rendering (SSR) is a common example, but it is also useful for other bootstrapping and hydration flows. - -```typescript -const client = new ReflagClient(); await client.initialize(); - -// Get bootstrapped state with full context -const bootstrappedState = client.getFlagsForBootstrap({ - user: { - id: "user123", - name: "John Doe", - email: "john@acme.com", - }, - company: { - id: "company456", - name: "Acme Inc", - plan: "enterprise", - }, - other: { - source: "web", - platform: "desktop", - }, -}); - -// Pass this data to your client-side application -console.log(bootstrappedState); -// { -// context: { ... }, -// flags: { -// "huddle": { -// "key": "huddle", -// "isEnabled": true, -// "config": { -// "key": "enhanced", -// "payload": { "maxParticipants": 50, "videoQuality": "hd" }, -// } -// } -// }, -// flagStateVersion: 42 -// } -``` - -You can also use a bound client for simpler API: - -```typescript -const boundClient = client.bindClient({ - user: { id: "user123", name: "John Doe", email: "john@acme.com" }, - company: { id: "company456", name: "Acme Inc", plan: "enterprise" }, -}); - -const bootstrappedState = boundClient.getFlagsForBootstrap(); -``` - -### Key differences from `getFlags()` - -* **Raw data**: Returns plain objects without `track()` functions, making them JSON serializable -* **Context included**: Returns both the evaluated flags and the context used for evaluation -* **Version included**: Returns `flagStateVersion` when known so bootstrapped clients can avoid redundant live-update refreshes -* **Bootstrapping focus**: Designed specifically for passing data to client-side applications - -## Edge-runtimes like Cloudflare Workers - -To use the Reflag NodeSDK with Cloudflare workers, set the `node_compat` flag [in your wrangler file](https://developers.cloudflare.com/workers/runtime-apis/nodejs/#get-started). - -Instead of using `ReflagClient`, use `EdgeClient` and make sure you call `ctx.waitUntil(reflag.flush());` before returning from your worker function. - -```typescript -import { EdgeClient } from "@reflag/node-sdk"; - -// set the REFLAG_SECRET_KEY environment variable or pass the secret key in the constructor -const reflag = new EdgeClient(); - -export default { - async fetch(request, _env, ctx): Promise { - // initialize the client and wait for it to complete - // if the client was initialized on a previous invocation, this is a no-op. - await reflag.initialize(); - const flags = reflag.getFlags({ - user: { id: "userId" }, - company: { id: "companyId" }, - }); - - // ensure all events are flushed and any requests to refresh the flag cache - // have completed after the response is sent - ctx.waitUntil(reflag.flush()); - - return new Response( - `Flags for user ${userId} and company ${companyId}: ${JSON.stringify(flags, null, 2)}`, - ); - }, -}; -``` - -See [examples/cloudflare-worker](https://github.com/reflagcom/javascript/tree/main/packages/node-sdk/examples/cloudflare-worker/src/index.ts) for a deployable example. - -Reflag maintains a cached set of flag definitions in the memory of your worker which it uses to decide which flags to turn on for which users/companies. - -The SDK caches flag definitions in memory for fast performance. The first request to a new worker instance fetches definitions from Reflag's servers, while subsequent requests use the cache. When the cache expires, it's updated in the background. `ctx.waitUntil(reflag.flush())` ensures completion of the background work, so response times are not affected. This background work may increase wall-clock time for your worker, but it will not measurably increase billable CPU time on platforms like Cloudflare. - -`EdgeClient` uses `flagsSyncMode: "in-request"`. Refresh fetch starts are throttled to at most once per second, and Cloudflare Workers cannot rely on delayed timer callbacks to run follow-up refreshes later. That means `refreshFlags()` calls made during the throttle window only mark a refresh as pending, so the call itself may resolve before the fetch runs. The queued refresh runs on the next request/access or `refreshFlags()` call after the throttle window expires. - -## Error Handling - -The SDK is designed to fail gracefully and never throw exceptions to the caller. Instead, it logs errors and provides fallback behavior: - -1. **Flag Evaluation Failures**: - - ```typescript - const { isEnabled } = client.getFlag("my-flag"); - // If flag evaluation fails, isEnabled will be false - ``` -2. **Network Errors**: - - ```typescript - // Network errors during tracking are logged but don't affect your application - const { isEnabled, track } = client.getFlag("my-flag"); - if (isEnabled) { - // network errors are caught internally and logged and never bubbled up to your application - // no need to try/catch around "track" or "getFlag" - await track(); - } - ``` -3. **Missing Context**: - - ```typescript - // The SDK tracks missing context fields but continues operation - const flags = client.getFlags({ - user: { id: "user123" }, - // Missing company context will be logged but won't cause errors - }); - ``` -4. **Offline Mode**: - - ```typescript - // In offline mode, the SDK uses explicit local configuration only. - // It does not fetch from Reflag or use flagsFallbackProvider. - const client = new ReflagClient({ - offline: true, - flagOverrides: () => ({ - "my-flag": true, - }), - }); - ``` - -The SDK logs all errors with appropriate severity levels. You can customize logging by providing your own logger: - -```typescript -const client = new ReflagClient({ - logger: { - debug: (msg) => console.debug(msg), - info: (msg) => console.info(msg), - warn: (msg) => console.warn(msg), - error: (msg, error) => { - console.error(msg, error); - // Send to your error tracking service - errorTracker.capture(error); - }, - }, -}); ``` -## Remote config +The client uses saved definitions only when it can't fetch them at startup. Built-in providers are `file`, `redis`, `s3`, `gcs` and `static`. You can also implement your own `FlagsFallbackProvider`. -Remote config is a dynamic and flexible approach to configuring flag behavior outside of your app – without needing to re-deploy it. - -Similar to `isEnabled`, each flag has a `config` property. This configuration is managed from within Reflag. It is managed similar to the way access to flags is managed, but instead of the binary `isEnabled` you can have multiple configuration values which are given to different user/companies. +A static provider takes fixed values: ```ts -const flags = reflagClient.getFlags(); -// { -// huddle: { -// isEnabled: true, -// targetingVersion: 42, -// config: { -// key: "gpt-3.5", -// payload: { maxTokens: 10000, model: "gpt-3.5-beta1" } -// } -// } -// } -``` - -`key` is mandatory for a config, but if a flag has no config or no config value was matched against the context, the `key` will be `undefined`. Make sure to check against this case when trying to use the configuration in your application. `payload` is an optional JSON value for arbitrary configuration needs. - -Just as `isEnabled`, accessing `config` on the object returned by `getFlags` does not automatically generate a `check` event, contrary to the `config` property on the object returned by `getFlag`. - -## Configuring - -The Reflag `Node.js` SDK can be configured through environment variables, a configuration file on disk or by passing options to the `ReflagClient` constructor. By default, the SDK searches for `reflag.config.json` in the current working directory. - -| Option | Type | Description | Env Var | -| ----------------------- | ------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------- | -| `secretKey` | string | The secret key used for authentication with Reflag's servers. | REFLAG\_SECRET\_KEY | -| `logLevel` | string | The log level for the SDK (e.g., `"DEBUG"`, `"INFO"`, `"WARN"`, `"ERROR"`). Default: `INFO` | REFLAG\_LOG\_LEVEL | -| `offline` | boolean | Operate in offline mode. Default: `false`, except in tests it will default to `true` based off of the `TEST` env. var. In offline mode the SDK does not fetch from Reflag and does not use `flagsFallbackProvider`. | REFLAG\_OFFLINE | -| `apiBaseUrl` | string | The base API URL for the Reflag servers. | REFLAG\_API\_BASE\_URL | -| `flagOverrides` | Record\ | An object specifying flag overrides for testing or local development. See [examples/express/app.test.ts](https://github.com/reflagcom/javascript/tree/main/packages/node-sdk/examples/express/app.test.ts) for how to use `flagOverrides` in tests. | REFLAG\_FLAGS\_ENABLED, REFLAG\_FLAGS\_DISABLED | -| `flagsFallbackProvider` | `FlagsFallbackProvider` | Optional provider used to load and save raw flag definitions for fallback startup when the initial live fetch fails. Available only through the constructor. Ignored in offline mode. | - | -| `flagsSyncMode` | `"polling" \| "in-request" \| "push"` | Flag-definition sync mode. `push` subscribes to live updates, `polling` uses periodic background refresh, and `in-request` refreshes stale flags during request handling. Default: `"push"`. | - | -| `flagsPushUrl` | string | Push endpoint used when `flagsSyncMode: "push"`. The SDK opens it as an authenticated streaming GET. Default: `https://front.reflag.com/sse/server`. | - | -| `configFile` | string | Load this config file from disk. Default: `reflag.config.json` | REFLAG\_CONFIG\_FILE | - -{% hint style="info" %} -`REFLAG_FLAGS_ENABLED` and `REFLAG_FLAGS_DISABLED` are comma separated lists of flags which will be enabled or disabled respectively. -{% endhint %} - -`reflag.config.json` example: - -```json -{ - "secretKey": "...", - "logLevel": "warn", - "offline": true, - "apiBaseUrl": "https://proxy.slick-demo.com", - "flagOverrides": { - "huddles": true, - "voiceChat": { "isEnabled": false }, - "aiAssist": { - "isEnabled": true, - "config": { - "key": "gpt-4.0", - "payload": { - "maxTokens": 50000 - } - } - } - } -} -``` - -When using a `reflag.config.json` for local development, make sure you add it to your `.gitignore` file. You can also set these options directly in the `ReflagClient` constructor. The precedence for configuration options is as follows, listed in the order of importance: - -1. Options passed along to the constructor directly, -2. Environment variable, -3. The config file. - -## Type safe flags - -To get type checked flags, install the Reflag CLI: - -```sh -npm i --save-dev @reflag/cli -``` - -then generate the types: - -```sh -npx reflag flags types -``` - -This will generate a `reflag.d.ts` containing all your flags. Any flag look ups will now be checked against the flags that exist in Reflag. - -Here's an example of a failed type check: - -```typescript -import { ReflagClient } from "@reflag/node-sdk"; - -export const reflagClient = new ReflagClient(); - -reflagClient.initialize().then(() => { - console.log("Reflag initialized!"); - - // TypeScript will catch this error: "invalid-flag" doesn't exist - reflagClient.getFlag("invalid-flag"); - - const { - isEnabled, - config: { payload }, - } = reflagClient.getFlag("create-todos"); -}); -``` - -![Type check failed](<../../.gitbook/assets/type-check-failed (1).png>) - -This is an example of a failed config payload check: - -```typescript -reflagClient.initialize().then(() => { - // TypeScript will catch this error as well: "minLength" is not part of the payload. - if (isEnabled && todo.length > config.payload.minLength) { - // ... - } +fallbackProviders.static({ + flags: { "new-editor": false, model: "quick", limits: null }, }); ``` -![Config type check failed](<../../.gitbook/assets/type-check-payload-failed (1).png>) - -## Testing with flag overrides - -When writing tests that cover code with flags, you can toggle flags on/off programmatically to test different behavior. For tests, you will often want to run the client in offline mode: - -`reflag.ts`: - -```typescript -import { ReflagClient } from "@reflag/node-sdk"; - -export const reflag = new ReflagClient({ - offline: true, -}); -``` +## Overrides and tests -There are a few ways to programmatically manipulate the overrides which are appropriate when testing: +Use offline mode and overrides to run tests without contacting Reflag: -### Base overrides - -You can set base overrides for a test run by passing `flagOverrides` in the constructor, replacing them later with `setFlagOverrides()` and clearing them with `clearFlagOverrides()`: - -```typescript -// pass directly in the constructor +```ts const client = new ReflagClient({ offline: true, - flagOverrides: { myFlag: true }, -}); - -// or replace the base overrides at a later time -client.setFlagOverrides({ myFlag: false }); - -// clear only the base overrides -client.clearFlagOverrides(); -``` - -`app.test.ts`: - -```typescript -import { reflag } from "./reflag.ts"; - -beforeAll(async () => await reflag.initialize()); -afterEach(() => { - reflag.clearFlagOverrides(); -}); - -describe("API Tests", () => { - it("should return 200 for the root endpoint", async () => { - reflag.setFlagOverrides({ - "show-todo": true, - }); - - const response = await request(app).get("/"); - expect(response.status).toBe(200); - expect(response.body).toEqual({ message: "Ready to manage some TODOs!" }); - }); -}); -``` - -### Layering overrides - -`pushFlagOverrides()` serves a different purpose: it adds a temporary layer on top of the base overrides and returns a remove function that removes only that layer. This is useful for nested tests: - -```typescript -export const flag = function (name: string, enabled: boolean): void { - let remove: (() => void) | undefined; - - beforeEach(function () { - remove = reflagClient.pushFlagOverrides({ [name]: enabled }); - }); - - afterEach(function () { - remove?.(); - remove = undefined; - }); -}; - -describe("foo", () => { - describe("with new search ranking enabled", () => { - flag("search-ranking-v2", true); - - describe("with summaries enabled", () => { - flag("smart-summaries", true); - - // ... - }); - }); + flagOverrides: { "new-editor": true, limits: { maxItems: 5 } }, }); -``` - -The precedence is: - -1. Base overrides from the constructor or `setFlagOverrides()` -2. Temporary layers added by `pushFlagOverrides()` - -If the same flag is set in both places, the pushed override wins until its remove function is called. - -### Context dependent overrides +await client.initialize(); -`setFlagOverrides()` and `pushFlagOverrides()` also accept a function if the override depends on the evaluation context: +client.setFlagOverrides({ model: "quick" }); -```typescript const remove = client.pushFlagOverrides((context) => ({ - "smart-summaries": context.user?.id === "qa-user", + model: context.company?.id === "qa" ? "quality" : "quick", })); - -// ... - remove(); -``` - -### Additional ways to provide flag overrides -You also have these additional ways to provide overrides, which can be helpful when testing out locally: - -1. Through environment variables: - -```bash -REFLAG_FLAGS_ENABLED=flag1,flag2 -REFLAG_FLAGS_DISABLED=flag3,flag4 -``` - -1. Through `reflag.config.json`: - -```json -{ - "flagOverrides": { - "delete-todos": { - "isEnabled": true, - "config": { - "key": "dev-config", - "payload": { - "requireConfirmation": true, - "maxDeletionsPerDay": 5 - } - } - } - } -} -``` - -## Remote Flag Evaluation - -In addition to local flag evaluation, Reflag supports remote evaluation using stored context. This is useful when you want to evaluate flags using user/company attributes that were previously sent to Reflag: - -```typescript -// First, update user and company attributes -await client.updateUser("user123", { - attributes: { - role: "admin", - subscription: "premium", - }, -}); - -await client.updateCompany("company456", { - attributes: { - tier: "enterprise", - employees: 1000, - }, -}); - -// Later, evaluate flags remotely using stored context. -// Note: the argument order is (userId, companyId, additionalContext?) -const userId = "user123"; -const companyId = "company456"; - -const flags = await client.getFlagsRemote(userId, companyId); -// Or evaluate a single flag -const flag = await client.getFlagRemote("create-todos", userId, companyId); - -// You can also provide additional context -const flagsWithContext = await client.getFlagsRemote(userId, companyId, { - other: { - location: "US", - platform: "mobile", - }, -}); +client.clearFlagOverrides(); ``` -Remote evaluation is particularly useful when: - -* You want to use the most up-to-date user/company attributes stored in Reflag -* You don't want to pass all context attributes with every evaluation -* You need to ensure consistent flag evaluation across different services - -## Using with Express - -A popular way to integrate the Reflag Node.js SDK is through an express middleware. - -```typescript -import reflag from "./reflag"; -import express from "express"; -import { BoundReflagClient } from "@reflag/node-sdk"; +Overrides pushed with `pushFlagOverrides()` take precedence over base overrides and can be removed independently. In offline mode, the client makes no network requests and sends no events. -// Augment the Express types to include a `boundReflagClient` property on the -// `res.locals` object. -// This will allow us to access the ReflagClient instance in our route handlers -// without having to pass it around manually -declare global { - namespace Express { - interface Locals { - boundReflagClient: BoundReflagClient; - } - } -} - -// Add express middleware -app.use((req, res, next) => { - // Extract the user and company IDs from the request - // You'll want to use a proper authentication and identification - // mechanism in a real-world application - const user = { - id: req.user?.id, - name: req.user?.name, - email: req.user?.email - } - - const company = { - id: req.user?.companyId, - name: req.user?.companyName - } - - // Create a new BoundReflagClient instance by calling the `bindClient` - // method on a `ReflagClient` instance - // This will create a new instance that is bound to the user/company given. - const boundReflagClient = reflag.bindClient({ user, company }); +## Type safety - // Store the BoundReflagClient instance in the `res.locals` object so we - // can access it in our route handlers - res.locals.boundReflagClient = boundReflagClient; - next(); -}); +Declaring your flags gives you autocompletion for keys, type checks for defaults and typed `getFlags()` results. If you created a flag with `npx reflag new`, the declarations are already generated; run `npx reflag flags types` again when your flags change. A declaration looks like this: -// Now use res.locals.boundReflagClient in your handlers -app.get("/todos", async (_req, res) => { - const { track, isEnabled } = res.locals.boundReflagClient.getFlag("show-todos"); - - if (!isEnabled) { - res.status(403).send({"error": "flag inaccessible"}) - return +```ts +declare module "@reflag/node-sdk" { + interface Flags { + "new-editor": boolean; + model: "quick" | "quality"; + limits: { maxItems: number } | null; } - - ... -} -``` - -See [examples/express/app.ts](https://github.com/reflagcom/javascript/tree/main/packages/node-sdk/example/express/app.ts) for a full example. - -## Remote flag evaluation with stored context - -If you don't want to provide context each time when evaluating flags but rather you would like to utilize the attributes you sent to Reflag previously (by calling `updateCompany` and `updateUser`) you can do so by calling `getFlagsRemote` (or `getFlagRemote` for a specific flag) with just `userId` and `companyId` in that order. These methods will call Reflag's servers and flags will be evaluated remotely using the stored attributes. - -```typescript -// Update user and company attributes -client.updateUser("john_doe", { - attributes: { - name: "John O.", - role: "admin", - }, -}); - -client.updateCompany("acme_inc", { - attributes: { - name: "Acme, Inc", - tier: "premium" - }, -}); -... - -// This will evaluate flags using the stored attributes for the user/company pair -const flags = await client.getFlagsRemote("john_doe", "acme_inc"); -``` - -{% hint style="warning" %} -User and company attribute updates are processed asynchronously, so there might be a small delay between when attributes are updated and when they are available for evaluation. -{% endhint %} - -## Opting out of tracking - -There are use cases in which you not want to be sending `user`, `company` and `track` events to [Reflag.com](https://reflag.com). These are usually cases where you could be impersonating another user in the system and do not want to interfere with the data being collected by Reflag. - -To disable tracking, bind the client using `bindClient()` as follows: - -```typescript -// binds the client to a given user and company and set `enableTracking` to `false`. -const boundClient = client.bindClient({ user, company, enableTracking: false }); - -boundClient.track("some event"); // this will not actually send the event to Reflag. - -// the following code will not update the `user` nor `company` in Reflag and will -// not send `track` events either. -const { isEnabled, track } = boundClient.getFlag("user-menu"); -if (isEnabled) { - track(); } ``` -Another way way to disable tracking without employing a bound client is to call `getFlag()` or `getFlags()` by supplying `enableTracking: false` in the arguments passed to these functions. - -{% hint style="warning" %} -Note, however, that calling `track()`, `updateCompany()` or `updateUser()` in the `ReflagClient` will still send tracking data. As such, it is always recommended to use `bindClient()` when using this SDK. -{% endhint %} - -## Flushing +Declarations are checked at compile time only. See the [Reflag CLI](https://docs.reflag.com/api/cli) for more options. -ReflagClient employs a batching technique to minimize the number of calls that are sent to Reflag's servers. +## Bootstrap the browser -By default, the SDK attempts to flush pending events when the Node.js event loop empties (the `beforeExit` event). This behavior is controlled by the `flushOnExit` option in the client configuration: +To render flags in the browser without waiting for a network request, evaluate them on the server and pass the result to the Browser, React or Vue SDK's bootstrap option: -```typescript -const client = new ReflagClient({ - batchOptions: { - flushOnExit: false, // disable automatic flushing on exit - }, -}); +```ts +const bootstrap = reflag.getFlagsForBootstrap(context); ``` -Node.js does not emit `beforeExit` for unhandled termination signals (such as `SIGTERM` or `SIGINT`) or explicit `process.exit()` calls. For these shutdown paths, **await `client.flush()` in your application's existing graceful shutdown hook**, after stopping incoming work and waiting for in-flight requests or jobs to finish, and before exiting. This ensures events produced during shutdown are included. Automatic flushing is best-effort and does not replace an application-managed shutdown hook. - -## Tracking custom events and setting custom attributes - -Tracking allows events and updating user/company attributes in Reflag. For example, if a customer changes their plan, you'll want Reflag to know about it, in order to continue to provide up-do-date targeting information in the Reflag interface. - -The following example shows how to register a new user, associate it with a company and finally update the plan they are on. +Pass the whole object, serialized with your framework's usual mechanism. Leave secrets and server-only attributes out of the context you bootstrap, because the browser can read it. -```typescript -// registers the user with Reflag using the provided unique ID, and -// providing a set of custom attributes (can be anything) -client.updateUser("user_id", { - attributes: { longTimeUser: true, payingCustomer: false }, -}); -client.updateCompany("company_id", { userId: "user_id" }); - -// the user started a voice huddle -client.track("user_id", "huddle", { attributes: { voice: true } }); -``` +## Remote evaluation -It's also possible to achieve the same through a bound client in the following manner: +To evaluate flags on Reflag's servers instead of locally, use the remote methods: -```typescript -const boundClient = client.bindClient({ - user: { id: "user_id", longTimeUser: true, payingCustomer: false }, - company: { id: "company_id" }, +```ts +const model = await reflag.getFlagRemote("model", "quick", "user-1", "acme"); +const boundModel = await reflag + .bindClient(context) + .getFlagRemote("model", "quick"); +const values = await reflag.getFlagsRemote("user-1", "acme", { + other: { region: "eu" }, }); - -boundClient.track("huddle", { attributes: { voice: true } }); ``` -Some attributes are used by Reflag to improve the UI, and are recommended to provide for easier navigation: +Unlike `getFlag()`, `getFlagRemote()` on the root client takes the default before the user and company IDs. To read a Boolean, pass `undefined` as the default. -* `name` -- display name for `user`/`company`, -* `email` -- the email of the user, -* `avatar` -- the URL for `user`/`company` avatar image. +## Edge runtimes -Attributes cannot be nested (multiple levels) and must be either strings, integers or booleans. +Use `EdgeClient` in edge runtimes such as Cloudflare Workers, with Node.js compatibility enabled. It refreshes flags as they're read, instead of in the background: -## Managing `Last seen` - -By default `updateUser`/`updateCompany` calls automatically update the given user/company `Last seen` property on Reflag servers. - -You can control if `Last seen` should be updated when the events are sent by setting `meta.active = false`. This is often useful if you have a background job that goes through a set of companies just to update their attributes but not their activity. - -Example: +```ts +import { EdgeClient } from "@reflag/node-sdk"; -```typescript -client.updateUser("john_doe", { - attributes: { name: "John O." }, - meta: { active: true }, -}); +let reflag: EdgeClient | undefined; -client.updateCompany("acme_inc", { - attributes: { name: "Acme, Inc" }, - meta: { active: false }, -}); +export default { + async fetch(request, env, ctx) { + reflag ??= new EdgeClient({ secretKey: env.REFLAG_SECRET_KEY }); + await reflag.initialize(); + const enabled = reflag.getFlag({ user: { id: "user-1" } }, "new-editor"); + ctx.waitUntil(reflag.flush()); + return new Response(enabled ? "New editor" : "Old editor"); + }, +}; ``` -`bindClient()` updates attributes on the Reflag servers but does not automatically update `Last seen`. - -## Zero PII +Call `ctx.waitUntil(reflag.flush())` before returning so queued events are sent. -The Reflag SDK doesn't collect any metadata and HTTP IP addresses are _not_ being stored. For tracking individual users, we recommend using something like database ID as userId, as it's unique and doesn't include any PII (personal identifiable information). If, however, you're using e.g. email address as userId, but prefer not to send any PII to Reflag, you can hash the sensitive data before sending it to Reflag: +## Configuration -```typescript -import { sha256 } from 'crypto-hash'; - -client.updateUser({ userId: await sha256("john_doe"), ... }); -``` +Options can be set in the constructor, through environment variables, or in `reflag.config.json`, in that order of precedence. -## Migrating from Bucket SDK +| Option | Environment variable | Description | +| ----------------------- | ----------------------------------------------- | -------------------------------------------------------------------- | +| `secretKey` | `REFLAG_SECRET_KEY` | Your environment's secret key | +| `apiBaseUrl` | `REFLAG_API_BASE_URL` | Override the API URL | +| `logLevel`, `logger` | `REFLAG_LOG_LEVEL` | Log level (default `INFO`) or a custom logger | +| `offline` | `REFLAG_OFFLINE` | Make no network requests, for example in tests | +| `configFile` | `REFLAG_CONFIG_FILE` | Path to a config file other than `reflag.config.json` | +| `flagOverrides` | `REFLAG_FLAGS_ENABLED`, `REFLAG_FLAGS_DISABLED` | Override flags; the variables take comma-separated Boolean flag keys | +| `flagsSyncMode` | | How flag definitions are kept up to date; default `push` | +| `flagsFallbackProvider` | | Where to save flag definitions for startup | +| `fetchTimeoutMs` | | Request timeout; default 10,000 ms | +| `flagsFetchRetries` | | Retries for fetching flag definitions; default 3 | +| `batchOptions` | | Event batching: `maxSize`, `intervalMs` and `flushOnExit` | +| `httpClient` | | Custom HTTP client | -If you have been using the Bucket SDKs previously, the following list will help you migrate to Reflag SDK: +To stop sending checks and events for a context, include `enableTracking: false` in it. -* `Bucket*` classes, and types have been renamed to `Reflag*` (e.g. `BucketClient` is now `ReflagClient`) -* `Feature*` classes, and types have been renamed to `Flag*` (e.g. `Feature` is now `Flag`, `RawFeatures` is now `RawFlags`) -* When using strongly-typed flags, the new `Flags` interface replaced `Features` interface -* All methods that contained `feature` in the name have been renamed to use the `flag` terminology (e.g. `getFeature` is `getFlag`) -* All environment variables that were prefixed with `BUCKET_` are now prefixed with `REFLAG_` -* The `BUCKET_HOST` environment variable and `host` option have been removed from `ReflagClient` constructor, use `REFLAG_API_BASE_URL` instead -* The `BUCKET_FEATURES_ENABLED` and `BUCKET_FEATURES_DISABLED` have been renamed to `REFLAG_FLAGS_ENABLED` and `REFLAG_FLAGS_DISABLED` -* The default configuration file has been renamed from `bucketConfig.json` to `reflag.config.json` -* The `fallbackFeatures` property in client constructor and configuration files has been renamed to `fallbackFlags` -* `featureKey` has been renamed to `flagKey` in all methods that accepts that argument -* The SDKs will not emit `evaluate` and `evaluate-config` events anymore +## Shutting down -## Typescript +Before your process exits, call `await reflag.flush()` to send queued events, then `reflag.destroy()` to stop background work. `batchOptions.flushOnExit` flushes only when Node exits on its own; if you exit on a signal or call `process.exit()`, call `flush()` in your shutdown handler first. -Types are bundled together with the library and exposed automatically when importing through a package manager. +## License -## License +MIT License. Copyright (c) 2025 Bucket ApS. -> MIT License Copyright (c) 2025 Bucket ApS +Using v1? [Legacy docs](../../legacy/v1/node-sdk/README.md) · [Upgrade guide](../migrating-from-v1.md). diff --git a/supported-languages/node-sdk/globals.md b/supported-languages/node-sdk/globals.md index 60078ca..90a1bc7 100644 --- a/supported-languages/node-sdk/globals.md +++ b/supported-languages/node-sdk/globals.md @@ -13,34 +13,31 @@ pagination: visible: true --- -# @reflag/node-sdk +# @reflag/node-sdk -## Classes +This page covers SDK v2. -### BoundReflagClient +## Classes -A client bound with a specific user, company, and other context. +### BoundReflagClient -#### Constructors +Context-bound reads have the same direct-value and immediate-check semantics. -##### new BoundReflagClient() +### Constructors + +### new BoundReflagClient() ```ts new BoundReflagClient(client: ReflagClient, options: ContextWithTracking): BoundReflagClient ``` -**`Internal`** - -(Internal) Creates a new BoundReflagClient. Use `bindClient` to create a new client bound with a specific context. - -###### Parameters +###### Parameters - @@ -54,11 +51,6 @@ new BoundReflagClient(client: ReflagClient, options: ContextWithTracking): Bound [`ReflagClient`](globals.md#reflagclient) - - @@ -71,167 +63,136 @@ The `ReflagClient` to use. [`ContextWithTracking`](globals.md#contextwithtracking) - -
Parameter TypeDescription
- -The `ReflagClient` to use. -
- -The options for the client. -
-###### Returns +###### Returns [`BoundReflagClient`](globals.md#boundreflagclient) -#### Accessors +#### Accessors -##### company +### company -###### Get Signature +###### Get Signature ```ts -get company(): +get company(): | undefined | { -[k: string]: any; avatar: string; - id: undefined | string | number; +[key: string]: any; avatar: string; + id: undefined | IdType; name: string; } ``` -Gets the company associated with the client. - -###### Returns +###### Returns \| `undefined` \| \{ -`[k: string]`: `any`; `avatar`: `string`; - `id`: `undefined` \| `string` \| `number`; +`[key: string]`: `any`; `avatar`: `string`; + `id`: `undefined` \| [`IdType`](globals.md#idtype); `name`: `string`; \} -The company or `undefined` if it is not set. - -##### otherContext +### otherContext -###### Get Signature +###### Get Signature ```ts -get otherContext(): +get otherContext(): | undefined | Record ``` -Gets the "other" context associated with the client. - -###### Returns +###### Returns \| `undefined` \| [`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, `any`\> -The "other" context or `undefined` if it is not set. - -##### user +### user -###### Get Signature +###### Get Signature ```ts -get user(): +get user(): | undefined | { -[k: string]: any; avatar: string; +[key: string]: any; avatar: string; email: string; - id: undefined | string | number; + id: undefined | IdType; name: string; } ``` -Gets the user associated with the client. - -###### Returns +###### Returns \| `undefined` \| \{ -`[k: string]`: `any`; `avatar`: `string`; +`[key: string]`: `any`; `avatar`: `string`; `email`: `string`; - `id`: `undefined` \| `string` \| `number`; + `id`: `undefined` \| [`IdType`](globals.md#idtype); `name`: `string`; \} -The user or `undefined` if it is not set. - -#### Methods +#### Methods -##### bindClient() +### bindClient() ```ts -bindClient(context: ContextWithTracking): BoundReflagClient +bindClient(next: ContextWithTracking): BoundReflagClient ``` -Create a new client bound with the additional context. -Note: This performs a shallow merge for user/company/other individually. - -###### Parameters +###### Parameters - -
Parameter TypeDescription
-`context` +`next` [`ContextWithTracking`](globals.md#contextwithtracking) - - -The context to bind the client to. -
-###### Returns +###### Returns [`BoundReflagClient`](globals.md#boundreflagclient) -new client bound with the additional context - -##### flush() +### flush() ```ts flush(): Promise ``` -Flushes the batch buffer. - -###### Returns +###### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> -##### getFlag() +### getFlag() + +###### Call Signature ```ts -getFlag(key: TKey): Flag +getFlag(key: Key, defaultValue?: undefined): boolean ``` -Get a specific flag for the user/company/other context bound to this client. -Using the `isEnabled` property sends a `check` event to Reflag. - -###### Type Parameters +###### Type Parameters @@ -243,21 +204,20 @@ Using the `isEnabled` property sends a `check` event to Reflag.
-`TKey` *extends* `string` +`Key` *extends* `string`
-###### Parameters +###### Parameters - @@ -269,40 +229,68 @@ Using the `isEnabled` property sends a `check` event to Reflag. + + +
Parameter TypeDescription
-`TKey` +`Key` + +
+ +`defaultValue`? -The key of the flag to get. +`undefined`
-###### Returns - -[`Flag`](globals.md#flagtconfig) +###### Returns -Flags for the given user/company and whether each one is enabled or not +`boolean` -##### getFlagRemote() +###### Call Signature ```ts -getFlagRemote(key: string): Promise +getFlag(key: Key, defaultValue: Default): FlagValueFromDefault ``` -Get remotely evaluated flag for the user/company/other context bound to this client. +###### Type Parameters + + + + + + + + + + + + + + + +
Type Parameter
+ +`Key` *extends* `string` + +
+ +`Default` *extends* `object` \| [`FlagDefaultValue`](globals.md#flagdefaultvalue) -###### Parameters +
+ +###### Parameters - @@ -314,92 +302,213 @@ Get remotely evaluated flag for the user/company/other context bound to this cli + + +
Parameter TypeDescription
-`string` +`Key` + +
+ +`defaultValue` -The key of the flag to get. +`Default`
-###### Returns +###### Returns -[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<[`Flag`](globals.md#flagtconfig)\> +[`FlagValueFromDefault`](globals.md#flagvaluefromdefaultt)\<`Default`\> -Flag for the given user/company and key and whether it's enabled or not +### getFlagRemote() -##### getFlags() +###### Call Signature ```ts -getFlags(): Record +getFlagRemote(key: Key, defaultValue?: undefined): Promise ``` -Get flags for the user/company/other context bound to this client. -Meant for use in serialization of flags for transferring to the client-side/browser. +###### Type Parameters + + + + + + + + + + + + +
Type Parameter
+ +`Key` *extends* `string` + +
+ +###### Parameters + + + + + + + + + + + + + + + + + + +
ParameterType
+ +`key` + + + +`Key` + +
+ +`defaultValue`? + + + +`undefined` -###### Returns +
-[`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, [`Flag`](globals.md#flagtconfig)\> +###### Returns -Flags for the given user/company and whether each one is enabled or not +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`boolean`\> -##### getFlagsForBootstrap() +###### Call Signature ```ts -getFlagsForBootstrap(): BootstrappedFlags +getFlagRemote(key: Key, defaultValue: Default): Promise> ``` -Get raw flags for the user/company/other context bound to this client without wrapping them in getters. -This method returns raw flag data suitable for bootstrapping client-side applications. +###### Type Parameters + + + + + + + + + + + + + + + +
Type Parameter
+ +`Key` *extends* `string` + +
-###### Returns +`Default` *extends* `object` \| [`FlagDefaultValue`](globals.md#flagdefaultvalue) -[`BootstrappedFlags`](globals.md#bootstrappedflags) +
+ +###### Parameters + + + + + + + + + + + + + + + + + + +
ParameterType
+ +`key` + + + +`Key` + +
+ +`defaultValue` + + + +`Default` -Raw flags for the given user/company and whether each one is enabled or not +
-##### getFlagsRemote() +###### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<[`FlagValueFromDefault`](globals.md#flagvaluefromdefaultt)\<`Default`\>\> + +### getFlags() ```ts -getFlagsRemote(): Promise> +getFlags(): Record ``` -Get remotely evaluated flag for the user/company/other context bound to this client. +###### Returns + +[`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, `undefined` \| [`FlagValue`](globals.md#flagvalue)\> + +### getFlagsForBootstrap() -###### Returns +```ts +getFlagsForBootstrap(): BootstrappedFlags +``` -[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<[`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, [`Flag`](globals.md#flagtconfig)\>\> +###### Returns -Flags for the given user/company and whether each one is enabled or not +[`BootstrappedFlags`](globals.md#bootstrappedflags) -##### refreshFlags() +### getFlagsRemote() ```ts -refreshFlags(waitForVersion?: number): Promise +getFlagsRemote(): Promise> ``` -Refreshes the flag definitions from the server. +###### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<[`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, `undefined` \| [`FlagValue`](globals.md#flagvalue)\>\> -Fetch starts are throttled to at most once per second. Outside -`in-request` mode, a call to `refreshFlags(waitForVersion)` still waits -until the cache has applied that version or newer. +### refreshFlags() -In `in-request` mode, a throttled call only records pending refresh work. -The fetch then runs on the next request/access or `refreshFlags()` call -after the throttle window expires. +```ts +refreshFlags(waitForVersion?: number): Promise +``` -###### Parameters +###### Parameters - @@ -413,38 +522,30 @@ after the throttle window expires. `number` - -
Parameter TypeDescription
- -Optional flag state version to wait for before returning updated definitions. -
-###### Returns +###### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> -##### track() +### track() ```ts track(event: string, options?: TrackOptions & { - companyId: string; + companyId: IdType; }): Promise ``` -Track an event in Reflag. - -###### Parameters +###### Parameters - @@ -458,11 +559,6 @@ Track an event in Reflag. `string` - - @@ -473,29 +569,20 @@ The event to track. -
Parameter TypeDescription
- -The event to track. -
-[`TrackOptions`](globals.md#trackoptions) & \{ `companyId`: `string`; \} - - - -The options for the event. +[`TrackOptions`](globals.md#trackoptions) & \{ `companyId`: [`IdType`](globals.md#idtype); \}
-###### Returns +###### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> -###### Throws - -An error if the event is invalid or the options are invalid. - *** -### EdgeClient +### EdgeClient The EdgeClient is ReflagClient pre-configured to be used in edge runtimes, like Cloudflare Workers. @@ -506,7 +593,7 @@ that throttle window only records pending refresh work, so the call may resolve before the fetch runs. That pending refresh is executed on the next request/access or `refreshFlags()` call after the window expires. -#### Example +#### Example ```ts // set the REFLAG_SECRET_KEY environment variable or pass the secret key in the constructor @@ -521,19 +608,19 @@ const { isEnabled } = client.getFlag(context, "flag-key"); ``` -#### Extends +#### Extends - [`ReflagClient`](globals.md#reflagclient) -#### Constructors +#### Constructors -##### new EdgeClient() +### new EdgeClient() ```ts new EdgeClient(options: EdgeClientOptions): EdgeClient ``` -###### Parameters +###### Parameters @@ -558,15 +645,15 @@ new EdgeClient(options: EdgeClientOptions): EdgeClient
-###### Returns +###### Returns [`EdgeClient`](globals.md#edgeclient) -###### Overrides +###### Overrides -[`ReflagClient`](globals.md#reflagclient).[`constructor`](globals.md#constructors-2) +[`ReflagClient`](globals.md#reflagclient).[`constructor`](globals.md#constructors) -#### Properties +#### Properties @@ -574,7 +661,6 @@ new EdgeClient(options: EdgeClientOptions): EdgeClient - @@ -586,17 +672,12 @@ new EdgeClient(options: EdgeClientOptions): EdgeClient - @@ -613,35 +694,30 @@ new EdgeClient(options: EdgeClientOptions): EdgeClient -
Property Modifier TypeDescription
-`public` - - - -[`HttpClient`](globals.md#httpclient-2) +`readonly` -‐ +[`HttpClient`](globals.md#httpclient)
-[`Logger`](globals.md#logger-2) - - - -Gets the logger associated with the client. +[`Logger`](globals.md#logger)
-#### Accessors +#### Accessors -##### flagOverrides +### flagOverrides -###### Set Signature +###### Set Signature ```ts -set flagOverrides(overrides: - | Partial> +set flagOverrides(overrides: + | Partial> | FlagOverridesFn): void ``` -###### Deprecated +###### Deprecated -Use `setFlagOverrides()` for replacing the base override set. +Use setFlagOverrides. -###### Parameters +###### Parameters @@ -659,167 +735,118 @@ Use `setFlagOverrides()` for replacing the base override set.
- \| [`Partial`](https://www.typescriptlang.org/docs/handbook/utility-types.html#partialtype)\<[`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, [`FlagOverride`](globals.md#flagoverride)\>\> \| [`FlagOverridesFn`](globals.md#flagoverridesfn) + \| [`Partial`](https://www.typescriptlang.org/docs/handbook/utility-types.html#partialtype)\<[`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, [`FlagValue`](globals.md#flagvalue)\>\> \| [`FlagOverridesFn`](globals.md#flagoverridesfn)
-###### Returns +###### Returns `void` -###### Inherited from +###### Inherited from -[`ReflagClient`](globals.md#reflagclient).[`flagOverrides`](globals.md#flagoverrides-1) +[`ReflagClient`](globals.md#reflagclient).[`flagOverrides`](globals.md#flagoverrides) -#### Methods +#### Methods -##### bindClient() +### bindClient() ```ts -bindClient(context: ContextWithTracking): BoundReflagClient +bindClient(options: ContextWithTracking): BoundReflagClient ``` -Returns a new BoundReflagClient with the user/company/otherContext -set to be used in subsequent calls. -For example, for evaluating flag targeting or tracking events. - -###### Parameters +###### Parameters - -
Parameter TypeDescription
-`context` +`options` [`ContextWithTracking`](globals.md#contextwithtracking) - - -The context to bind the client to. -
-###### Returns +###### Returns [`BoundReflagClient`](globals.md#boundreflagclient) -A new client bound with the arguments given. - -###### Throws +###### Inherited from -An error if the user/company is given but their ID is not a string. +[`ReflagClient`](globals.md#reflagclient).[`bindClient`](globals.md#bindclient) -###### Remarks - -The `updateUser` / `updateCompany` methods will automatically be called when -the user/company is set respectively. - -###### Inherited from - -[`ReflagClient`](globals.md#reflagclient).[`bindClient`](globals.md#bindclient-2) - -##### clearFlagOverrides() +### clearFlagOverrides() ```ts clearFlagOverrides(): void ``` -Clears the base flag overrides. - -###### Returns +###### Returns `void` -###### Remarks - -This does not affect temporary layers added with `pushFlagOverrides()`. - -###### Example - -```ts -client.clearFlagOverrides(); -``` +###### Inherited from -###### Inherited from +[`ReflagClient`](globals.md#reflagclient).[`clearFlagOverrides`](globals.md#clearflagoverrides) -[`ReflagClient`](globals.md#reflagclient).[`clearFlagOverrides`](globals.md#clearflagoverrides-1) - -##### destroy() +### destroy() ```ts destroy(): void ``` -Destroys the client and cleans up all resources including timers and background processes. - -###### Returns +###### Returns `void` -###### Remarks +###### Inherited from -After calling this method, the client should not be used anymore. -This is particularly useful in development environments with hot reloading to prevent -multiple background processes from running simultaneously. +[`ReflagClient`](globals.md#reflagclient).[`destroy`](globals.md#destroy) -###### Inherited from - -[`ReflagClient`](globals.md#reflagclient).[`destroy`](globals.md#destroy-1) - -##### flush() +### flush() ```ts flush(): Promise ``` -Flushes and completes any in-flight fetches in the flag cache. - -###### Returns +###### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> -###### Remarks - -It is recommended to call this method when the application is shutting down to ensure all events are sent -before the process exits. +###### Inherited from -This method is automatically called on natural process exit (`beforeExit`) if -`batchOptions.flushOnExit` is `true` in the options (default). For signal-driven -shutdown or an explicit `process.exit()`, await this method in your application's -shutdown hook before exiting. The SDK does not install signal handlers. +[`ReflagClient`](globals.md#reflagclient).[`flush`](globals.md#flush) -###### Inherited from +### getFlag() -[`ReflagClient`](globals.md#reflagclient).[`flush`](globals.md#flush-2) - -##### getFlag() +###### Call Signature ```ts -getFlag(__namedParameters: ContextWithTracking, key: TKey): Flag +getFlag( + options: ContextWithTracking, + key: Key, + defaultValue?: undefined): boolean ``` -Gets the evaluated flag for the current context which includes the user, company, and custom context. -Using the `isEnabled` property sends a `check` event to Reflag. +Read a Boolean with an implicit false default, or supply an explicit value default. -###### Type Parameters +###### Type Parameters @@ -831,28 +858,27 @@ Using the `isEnabled` property sends a `check` event to Reflag.
-`TKey` *extends* `string` +`Key` *extends* `string`
-###### Parameters +###### Parameters - + + - - + +
Parameter TypeDescription
-`__namedParameters` +`options` @@ -860,79 +886,166 @@ Using the `isEnabled` property sends a `check` event to Reflag. [`ContextWithTracking`](globals.md#contextwithtracking)
-‐ +`key`
-`key` +`Key`
-`TKey` +`defaultValue`? -The key of the flag to get. +`undefined`
-###### Returns +###### Returns -[`Flag`](globals.md#flagtconfig) +`boolean` -The evaluated flag. +###### Inherited from -###### Remarks +[`ReflagClient`](globals.md#reflagclient).[`getFlag`](globals.md#getflag) -Call `initialize` before calling this method to ensure the flag definitions are cached, no flags will be returned otherwise. +###### Call Signature -###### Inherited from +```ts +getFlag( + options: ContextWithTracking, + key: Key, +defaultValue: Default): FlagValueFromDefault +``` -[`ReflagClient`](globals.md#reflagclient).[`getFlag`](globals.md#getflag-2) +Read a Boolean with an implicit false default, or supply an explicit value default. -##### getFlagDefinitions() +###### Type Parameters + + + + + + + + + + + + + + + +
Type Parameter
+ +`Key` *extends* `string` + +
+ +`Default` *extends* `object` \| [`FlagDefaultValue`](globals.md#flagdefaultvalue) + +
+ +###### Parameters + + + + + + + + + + + + + + + + + + + + + + +
ParameterType
+ +`options` + + + +[`ContextWithTracking`](globals.md#contextwithtracking) + +
+ +`key` + + + +`Key` + +
+ +`defaultValue` + + + +`Default` + +
+ +###### Returns + +[`FlagValueFromDefault`](globals.md#flagvaluefromdefaultt)\<`Default`\> + +###### Inherited from + +[`ReflagClient`](globals.md#reflagclient).[`getFlag`](globals.md#getflag) + +### getFlagDefinitions() ```ts -getFlagDefinitions(): FlagDefinition[] +getFlagDefinitions(): FlagCollection ``` -Gets the flag definitions, including all config values. -To evaluate which flags are enabled for a given user/company, use `getFlags`. +Complete definitions, including segments needed for offline evaluation. -###### Returns +###### Returns -[`FlagDefinition`](globals.md#flagdefinition)[] +[`FlagCollection`](globals.md#flagcollection) -The flags definitions. +###### Inherited from -###### Inherited from +[`ReflagClient`](globals.md#reflagclient).[`getFlagDefinitions`](globals.md#getflagdefinitions) -[`ReflagClient`](globals.md#reflagclient).[`getFlagDefinitions`](globals.md#getflagdefinitions-1) +### getFlagRemote() -##### getFlagRemote() +###### Call Signature ```ts -getFlagRemote( - key: TKey, - userId?: IdType, - companyId?: IdType, -additionalContext?: Context): Promise +getFlagRemote( + key: Key, + defaultValue?: undefined, + userId?: IdType, + companyId?: IdType, +context?: ContextWithTracking): Promise ``` -Gets evaluated flag with the usage of remote context. -This method triggers a network request every time it's called. - -###### Type Parameters +###### Type Parameters @@ -944,21 +1057,20 @@ This method triggers a network request every time it's called.
-`TKey` *extends* `string` +`Key` *extends* `string`
-###### Parameters +###### Parameters - @@ -970,12 +1082,19 @@ This method triggers a network request every time it's called. + + + @@ -990,75 +1109,175 @@ The key of the flag to get. [`IdType`](globals.md#idtype) + + + + + +
Parameter TypeDescription
-`TKey` +`Key`
-The key of the flag to get. +`defaultValue`? + + + +`undefined`
-The userId of the user to get the flag for. +`companyId`? + + + +[`IdType`](globals.md#idtype)
-`companyId`? +`context`? -[`IdType`](globals.md#idtype) +[`ContextWithTracking`](globals.md#contextwithtracking)
+ +###### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`boolean`\> + +###### Inherited from + +[`ReflagClient`](globals.md#reflagclient).[`getFlagRemote`](globals.md#getflagremote) + +###### Call Signature + +```ts +getFlagRemote( + key: Key, + defaultValue: Default, + userId?: IdType, + companyId?: IdType, +context?: ContextWithTracking): Promise> +``` + +###### Type Parameters + + + + + + + + + + + +
Type Parameter
-The companyId of the company to get the flag for. +`Key` *extends* `string`
-`additionalContext`? +`Default` *extends* `object` \| [`FlagDefaultValue`](globals.md#flagdefaultvalue)
+ +###### Parameters + + + + + + + + + + + + + + + + + + + + + + + + + +
ParameterType
+ +`key` + + + +`Key` + +
+ +`defaultValue` + + + +`Default` + +
+ +`userId`? + + + +[`IdType`](globals.md#idtype) + +
-[`Context`](globals.md#context-1) +`companyId`? -The additional context to get the flag for. +[`IdType`](globals.md#idtype) + +
+ +`context`? + + + +[`ContextWithTracking`](globals.md#contextwithtracking)
-###### Returns +###### Returns -[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<[`Flag`](globals.md#flagtconfig)\> +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<[`FlagValueFromDefault`](globals.md#flagvaluefromdefaultt)\<`Default`\>\> -evaluated flag +###### Inherited from -###### Inherited from +[`ReflagClient`](globals.md#reflagclient).[`getFlagRemote`](globals.md#getflagremote) -[`ReflagClient`](globals.md#reflagclient).[`getFlagRemote`](globals.md#getflagremote-2) - -##### getFlags() +### getFlags() ```ts -getFlags(options: ContextWithTracking): Record +getFlags(options: ContextWithTracking): Record ``` -Gets the evaluated flags for the current context which includes the user, company, and custom context. +Return all values and immediately register checks for the returned roots. -###### Parameters +###### Parameters - @@ -1072,47 +1291,34 @@ Gets the evaluated flags for the current context which includes the user, compan [`ContextWithTracking`](globals.md#contextwithtracking) - -
Parameter TypeDescription
- -The options for the context. -
-###### Returns +###### Returns -[`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, [`Flag`](globals.md#flagtconfig)\> +[`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, `undefined` \| [`FlagValue`](globals.md#flagvalue)\> -The evaluated flags. +###### Inherited from -###### Remarks +[`ReflagClient`](globals.md#reflagclient).[`getFlags`](globals.md#getflags) -Call `initialize` before calling this method to ensure the flag definitions are cached, no flags will be returned otherwise. - -###### Inherited from - -[`ReflagClient`](globals.md#reflagclient).[`getFlags`](globals.md#getflags-2) - -##### getFlagsForBootstrap() +### getFlagsForBootstrap() ```ts getFlagsForBootstrap(options: ContextWithTracking): BootstrappedFlags ``` -Gets the evaluated flags for the current context without wrapping them in getters. -This method returns raw flag data suitable for bootstrapping client-side applications. +Serialization is not a read by the browser; it must not emit check events. -###### Parameters +###### Parameters - @@ -1126,51 +1332,35 @@ This method returns raw flag data suitable for bootstrapping client-side applica [`ContextWithTracking`](globals.md#contextwithtracking) - -
Parameter TypeDescription
- -The options for the context. -
-###### Returns +###### Returns [`BootstrappedFlags`](globals.md#bootstrappedflags) -The evaluated raw flags and the context. - -###### Remarks - -Call `initialize` before calling this method to ensure the flag definitions are cached, no flags will be returned otherwise. -This method returns RawFlag objects without wrapping them in getters, making them suitable for serialization. - -###### Inherited from +###### Inherited from -[`ReflagClient`](globals.md#reflagclient).[`getFlagsForBootstrap`](globals.md#getflagsforbootstrap-2) +[`ReflagClient`](globals.md#reflagclient).[`getFlagsForBootstrap`](globals.md#getflagsforbootstrap) -##### getFlagsRemote() +### getFlagsRemote() ```ts getFlagsRemote( - userId?: IdType, - companyId?: IdType, -additionalContext?: Context): Promise> + userId?: IdType, + companyId?: IdType, +context?: ContextWithTracking): Promise> ``` -Gets evaluated flags with the usage of remote context. -This method triggers a network request every time it's called. - -###### Parameters +###### Parameters - @@ -1184,11 +1374,6 @@ This method triggers a network request every time it's called. [`IdType`](globals.md#idtype) - - @@ -1201,82 +1386,60 @@ The userId of the user to get the flags for. [`IdType`](globals.md#idtype) - - -
Parameter TypeDescription
- -The userId of the user to get the flags for. -
- -The companyId of the company to get the flags for. -
-`additionalContext`? +`context`? -[`Context`](globals.md#context-1) - - - -The additional context to get the flags for. +[`ContextWithTracking`](globals.md#contextwithtracking)
-###### Returns - -[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<[`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, [`Flag`](globals.md#flagtconfig)\>\> +###### Returns -evaluated flags +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<[`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, `undefined` \| [`FlagValue`](globals.md#flagvalue)\>\> -###### Inherited from +###### Inherited from -[`ReflagClient`](globals.md#reflagclient).[`getFlagsRemote`](globals.md#getflagsremote-2) +[`ReflagClient`](globals.md#reflagclient).[`getFlagsRemote`](globals.md#getflagsremote) -##### initialize() +### initialize() ```ts initialize(): Promise ``` -Initializes the client by caching the flags definitions. - -###### Returns +###### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> -###### Remarks - -Call this method before calling `getFlags` to ensure the flag definitions are cached. -The client will ignore subsequent calls to this method. +###### Inherited from -###### Inherited from +[`ReflagClient`](globals.md#reflagclient).[`initialize`](globals.md#initialize) -[`ReflagClient`](globals.md#reflagclient).[`initialize`](globals.md#initialize-1) - -##### pushFlagOverrides() +### pushFlagOverrides() ```ts -pushFlagOverrides(overrides: - | Partial> +pushFlagOverrides(overrides: + | Partial> | FlagOverridesFn): () => void ``` -Temporarily layers flag overrides on top of the current overrides. - -###### Parameters +###### Parameters - @@ -1288,68 +1451,38 @@ Temporarily layers flag overrides on top of the current overrides. -
Parameter TypeDescription
- \| [`Partial`](https://www.typescriptlang.org/docs/handbook/utility-types.html#partialtype)\<[`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, [`FlagOverride`](globals.md#flagoverride)\>\> \| [`FlagOverridesFn`](globals.md#flagoverridesfn) - - - -The flag overrides to apply for the scoped period. + \| [`Partial`](https://www.typescriptlang.org/docs/handbook/utility-types.html#partialtype)\<[`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, [`FlagValue`](globals.md#flagvalue)\>\> \| [`FlagOverridesFn`](globals.md#flagoverridesfn)
-###### Returns +###### Returns `Function` -A remove function that removes only this override layer. - -###### Returns +###### Returns `void` -###### Remarks +###### Inherited from -This is intended for tests or other short-lived local overrides. The remove -function is idempotent and can safely be called multiple times. +[`ReflagClient`](globals.md#reflagclient).[`pushFlagOverrides`](globals.md#pushflagoverrides) -###### Example - -```ts -let remove: (() => void) | undefined; - -beforeEach(() => { - remove = client.pushFlagOverrides({ "flag-1": true }); -}); - -afterEach(() => { - remove?.(); - remove = undefined; -}); -``` - -###### Inherited from - -[`ReflagClient`](globals.md#reflagclient).[`pushFlagOverrides`](globals.md#pushflagoverrides-1) - -##### refreshFlags() +### refreshFlags() ```ts refreshFlags(waitForVersion?: number): Promise ``` -Refreshes the flag definitions from the server. - -###### Parameters +###### Parameters - @@ -1363,62 +1496,34 @@ Refreshes the flag definitions from the server. `number` - -
Parameter TypeDescription
- -Optional flag state version to wait for before returning updated definitions. -
-###### Returns +###### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> -###### Remarks - -This triggers an on-demand refresh of the cached flag definitions. -Useful when you know flags have changed and don't want to wait for the next automatic refresh cycle. - -Note: updated flag rules take a few seconds to propagate to all servers. +###### Inherited from -Fetch starts are throttled to at most once per second. -Outside `in-request` mode, throttling only delays when the next fetch -begins: `refreshFlags(99)` still waits until the cache has applied flag -definitions from version `99` or newer before the promise resolves. -Concurrent callers are deduplicated and may share the same in-flight or -scheduled follow-up refresh. +[`ReflagClient`](globals.md#reflagclient).[`refreshFlags`](globals.md#refreshflags) -In `in-request` mode, delayed follow-up refreshes are not scheduled. On edge -runtimes like Cloudflare Workers, a call during the throttle window only -records pending refresh work, and the promise may resolve before that fetch -runs. The pending refresh is executed on the next request/access or -`refreshFlags()` call after the throttle window expires. - -###### Inherited from - -[`ReflagClient`](globals.md#reflagclient).[`refreshFlags`](globals.md#refreshflags-2) - -##### setFlagOverrides() +### setFlagOverrides() ```ts -setFlagOverrides(overrides: - | Partial> +setFlagOverrides(overrides: + | Partial> | FlagOverridesFn): void ``` -Replaces the base flag overrides used by the client. - -###### Parameters +###### Parameters - @@ -1430,54 +1535,33 @@ Replaces the base flag overrides used by the client. -
Parameter TypeDescription
- \| [`Partial`](https://www.typescriptlang.org/docs/handbook/utility-types.html#partialtype)\<[`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, [`FlagOverride`](globals.md#flagoverride)\>\> \| [`FlagOverridesFn`](globals.md#flagoverridesfn) - - - -The flag overrides. + \| [`Partial`](https://www.typescriptlang.org/docs/handbook/utility-types.html#partialtype)\<[`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, [`FlagValue`](globals.md#flagvalue)\>\> \| [`FlagOverridesFn`](globals.md#flagoverridesfn)
-###### Returns +###### Returns `void` -###### Remarks - -Base overrides are always applied before any temporary layers added through -`pushFlagOverrides()`. - -###### Example - -```ts -client.setFlagOverrides({ - "flag-1": true, - "flag-2": false, -}); -``` - -###### Inherited from +###### Inherited from -[`ReflagClient`](globals.md#reflagclient).[`setFlagOverrides`](globals.md#setflagoverrides-1) +[`ReflagClient`](globals.md#reflagclient).[`setFlagOverrides`](globals.md#setflagoverrides) -##### track() +### track() ```ts track( - userId: IdType, - event: string, + userId: IdType, + event: string, options?: TrackOptions & { companyId: IdType; }): Promise ``` -Tracks an event in Reflag. - -###### Parameters +###### Parameters @@ -1526,23 +1610,15 @@ Tracks an event in Reflag.
-###### Returns +###### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> -###### Throws - -An error if the user is not set or the event is invalid or the options are invalid. - -###### Remarks - -If the company is set, the event will be associated with the company. +###### Inherited from -###### Inherited from +[`ReflagClient`](globals.md#reflagclient).[`track`](globals.md#track) -[`ReflagClient`](globals.md#reflagclient).[`track`](globals.md#track-2) - -##### updateCompany() +### updateCompany() ```ts updateCompany(companyId: IdType, options?: TrackOptions & { @@ -1550,16 +1626,13 @@ updateCompany(companyId: IdType, options?: TrackOptions & { }): Promise ``` -Updates the associated company in Reflag. - -###### Parameters +###### Parameters - @@ -1573,11 +1646,6 @@ Updates the associated company in Reflag. [`IdType`](globals.md#idtype) - - @@ -1590,49 +1658,32 @@ The companyId of the company to update. [`TrackOptions`](globals.md#trackoptions) & \{ `userId`: [`IdType`](globals.md#idtype); \} - -
Parameter TypeDescription
- -The companyId of the company to update. -
- -The options for the company. -
-###### Returns +###### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> -###### Throws - -An error if the company is not set or the options are invalid. +###### Inherited from -###### Remarks +[`ReflagClient`](globals.md#reflagclient).[`updateCompany`](globals.md#updatecompany) -The company must be set using `withCompany` before calling this method. -If the user is set, the company will be associated with the user. - -###### Inherited from - -[`ReflagClient`](globals.md#reflagclient).[`updateCompany`](globals.md#updatecompany-1) - -##### updateUser() +### updateUser() ```ts updateUser(userId: IdType, options?: TrackOptions): Promise ``` -Updates the associated user in Reflag. - -###### Parameters +###### Parameters - @@ -1646,11 +1697,6 @@ Updates the associated user in Reflag. [`IdType`](globals.md#idtype) - - @@ -1663,80 +1709,44 @@ The userId of the user to update. [`TrackOptions`](globals.md#trackoptions) - -
Parameter TypeDescription
- -The userId of the user to update. -
- -The options for the user. -
-###### Returns +###### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> -###### Throws - -An error if the company is not set or the options are invalid. - -###### Remarks +###### Inherited from -The company must be set using `withCompany` before calling this method. -If the user is set, the company will be associated with the user. - -###### Inherited from - -[`ReflagClient`](globals.md#reflagclient).[`updateUser`](globals.md#updateuser-1) +[`ReflagClient`](globals.md#reflagclient).[`updateUser`](globals.md#updateuser) *** -### ReflagClient - -The SDK client. - -#### Remarks - -This is the main class for interacting with Reflag. -It is used to evaluate flags, update user and company contexts, and track events. - -#### Example - -```ts -// set the REFLAG_SECRET_KEY environment variable or pass the secret key to the constructor -const client = new ReflagClient(); +### ReflagClient -// evaluate a flag -const isFlagEnabled = client.getFlag("flag-key", { - user: { id: "user-id" }, - company: { id: "company-id" }, -}); -``` +V2 client: flag reads return values and immediately register checks. -#### Extended by +#### Extended by - [`EdgeClient`](globals.md#edgeclient) -#### Constructors +#### Constructors -##### new ReflagClient() +### new ReflagClient() ```ts new ReflagClient(options: ClientOptions): ReflagClient ``` -Creates a new SDK client. -See README for configuration options. - -###### Parameters +###### Parameters - @@ -1750,25 +1760,16 @@ See README for configuration options. [`ClientOptions`](globals.md#clientoptions) - -
Parameter TypeDescription
- -The options for the client or an existing client to clone. -
-###### Returns +###### Returns [`ReflagClient`](globals.md#reflagclient) -###### Throws - -An error if the options are invalid. - -#### Properties +#### Properties @@ -1776,7 +1777,6 @@ An error if the options are invalid. - @@ -1788,17 +1788,12 @@ An error if the options are invalid. - @@ -1815,35 +1810,30 @@ An error if the options are invalid. -
Property Modifier TypeDescription
-`public` - - - -[`HttpClient`](globals.md#httpclient-2) +`readonly` -‐ +[`HttpClient`](globals.md#httpclient)
-[`Logger`](globals.md#logger-2) - - - -Gets the logger associated with the client. +[`Logger`](globals.md#logger)
-#### Accessors +#### Accessors -##### flagOverrides +### flagOverrides -###### Set Signature +###### Set Signature ```ts -set flagOverrides(overrides: - | Partial> +set flagOverrides(overrides: + | Partial> | FlagOverridesFn): void ``` -###### Deprecated +###### Deprecated -Use `setFlagOverrides()` for replacing the base override set. +Use setFlagOverrides. -###### Parameters +###### Parameters @@ -1861,147 +1851,181 @@ Use `setFlagOverrides()` for replacing the base override set.
- \| [`Partial`](https://www.typescriptlang.org/docs/handbook/utility-types.html#partialtype)\<[`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, [`FlagOverride`](globals.md#flagoverride)\>\> \| [`FlagOverridesFn`](globals.md#flagoverridesfn) + \| [`Partial`](https://www.typescriptlang.org/docs/handbook/utility-types.html#partialtype)\<[`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, [`FlagValue`](globals.md#flagvalue)\>\> \| [`FlagOverridesFn`](globals.md#flagoverridesfn)
-###### Returns +###### Returns `void` -#### Methods +#### Methods -##### bindClient() +### bindClient() ```ts -bindClient(context: ContextWithTracking): BoundReflagClient +bindClient(options: ContextWithTracking): BoundReflagClient ``` -Returns a new BoundReflagClient with the user/company/otherContext -set to be used in subsequent calls. -For example, for evaluating flag targeting or tracking events. - -###### Parameters +###### Parameters - -
Parameter TypeDescription
-`context` +`options` [`ContextWithTracking`](globals.md#contextwithtracking) - - -The context to bind the client to. -
-###### Returns +###### Returns [`BoundReflagClient`](globals.md#boundreflagclient) -A new client bound with the arguments given. +### clearFlagOverrides() -###### Throws - -An error if the user/company is given but their ID is not a string. +```ts +clearFlagOverrides(): void +``` -###### Remarks +###### Returns -The `updateUser` / `updateCompany` methods will automatically be called when -the user/company is set respectively. +`void` -##### clearFlagOverrides() +### destroy() ```ts -clearFlagOverrides(): void +destroy(): void ``` -Clears the base flag overrides. - -###### Returns +###### Returns `void` -###### Remarks - -This does not affect temporary layers added with `pushFlagOverrides()`. - -###### Example +### flush() ```ts -client.clearFlagOverrides(); +flush(): Promise ``` -##### destroy() +###### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> + +### getFlag() + +###### Call Signature ```ts -destroy(): void +getFlag( + options: ContextWithTracking, + key: Key, + defaultValue?: undefined): boolean ``` -Destroys the client and cleans up all resources including timers and background processes. +Read a Boolean with an implicit false default, or supply an explicit value default. -###### Returns +###### Type Parameters -`void` + + + + + + + + + + + +
Type Parameter
-###### Remarks +`Key` *extends* `string` -After calling this method, the client should not be used anymore. -This is particularly useful in development environments with hot reloading to prevent -multiple background processes from running simultaneously. +
-##### flush() +###### Parameters -```ts -flush(): Promise -``` + + + + + + + + + + + + + + + + + + + + + +
ParameterType
-Flushes and completes any in-flight fetches in the flag cache. +`options` -###### Returns + -[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> +[`ContextWithTracking`](globals.md#contextwithtracking) + +
-###### Remarks +`key` + + + +`Key` + +
-It is recommended to call this method when the application is shutting down to ensure all events are sent -before the process exits. +`defaultValue`? -This method is automatically called on natural process exit (`beforeExit`) if -`batchOptions.flushOnExit` is `true` in the options (default). For signal-driven -shutdown or an explicit `process.exit()`, await this method in your application's -shutdown hook before exiting. The SDK does not install signal handlers. + -##### getFlag() +`undefined` + +
+ +###### Returns + +`boolean` + +###### Call Signature ```ts -getFlag(__namedParameters: ContextWithTracking, key: TKey): Flag +getFlag( + options: ContextWithTracking, + key: Key, +defaultValue: Default): FlagValueFromDefault ``` -Gets the evaluated flag for the current context which includes the user, company, and custom context. -Using the `isEnabled` property sends a `check` event to Reflag. +Read a Boolean with an implicit false default, or supply an explicit value default. -###### Type Parameters +###### Type Parameters @@ -2013,28 +2037,34 @@ Using the `isEnabled` property sends a `check` event to Reflag. + + +
-`TKey` *extends* `string` +`Key` *extends* `string` + +
+ +`Default` *extends* `object` \| [`FlagDefaultValue`](globals.md#flagdefaultvalue)
-###### Parameters +###### Parameters - + + - - + +
Parameter TypeDescription
-`__namedParameters` +`options` @@ -2042,71 +2072,171 @@ Using the `isEnabled` property sends a `check` event to Reflag. [`ContextWithTracking`](globals.md#contextwithtracking)
-‐ +`key`
-`key` +`Key`
-`TKey` +`defaultValue` -The key of the flag to get. +`Default`
-###### Returns +###### Returns -[`Flag`](globals.md#flagtconfig) +[`FlagValueFromDefault`](globals.md#flagvaluefromdefaultt)\<`Default`\> -The evaluated flag. +### getFlagDefinitions() -###### Remarks +```ts +getFlagDefinitions(): FlagCollection +``` + +Complete definitions, including segments needed for offline evaluation. + +###### Returns -Call `initialize` before calling this method to ensure the flag definitions are cached, no flags will be returned otherwise. +[`FlagCollection`](globals.md#flagcollection) -##### getFlagDefinitions() +### getFlagRemote() + +###### Call Signature ```ts -getFlagDefinitions(): FlagDefinition[] +getFlagRemote( + key: Key, + defaultValue?: undefined, + userId?: IdType, + companyId?: IdType, +context?: ContextWithTracking): Promise ``` -Gets the flag definitions, including all config values. -To evaluate which flags are enabled for a given user/company, use `getFlags`. +###### Type Parameters + + + + + + + + + + + + +
Type Parameter
+ +`Key` *extends* `string` + +
+ +###### Parameters + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ParameterType
+ +`key` + + + +`Key` + +
+ +`defaultValue`? + + + +`undefined` + +
+ +`userId`? + + + +[`IdType`](globals.md#idtype) + +
+ +`companyId`? + + + +[`IdType`](globals.md#idtype) + +
+ +`context`? + + + +[`ContextWithTracking`](globals.md#contextwithtracking) -###### Returns +
-[`FlagDefinition`](globals.md#flagdefinition)[] +###### Returns -The flags definitions. +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`boolean`\> -##### getFlagRemote() +###### Call Signature ```ts -getFlagRemote( - key: TKey, - userId?: IdType, - companyId?: IdType, -additionalContext?: Context): Promise +getFlagRemote( + key: Key, + defaultValue: Default, + userId?: IdType, + companyId?: IdType, +context?: ContextWithTracking): Promise> ``` -Gets evaluated flag with the usage of remote context. -This method triggers a network request every time it's called. - -###### Type Parameters +###### Type Parameters @@ -2118,21 +2248,27 @@ This method triggers a network request every time it's called. + + +
-`TKey` *extends* `string` +`Key` *extends* `string` + +
+ +`Default` *extends* `object` \| [`FlagDefaultValue`](globals.md#flagdefaultvalue)
-###### Parameters +###### Parameters - @@ -2144,29 +2280,31 @@ This method triggers a network request every time it's called. + + - - + + @@ -2180,55 +2318,42 @@ The userId of the user to get the flag for. [`IdType`](globals.md#idtype) - - -
Parameter TypeDescription
-`TKey` +`Key`
-The key of the flag to get. +`defaultValue`
-`userId`? +`Default`
-[`IdType`](globals.md#idtype) +`userId`? -The userId of the user to get the flag for. +[`IdType`](globals.md#idtype)
- -The companyId of the company to get the flag for. -
-`additionalContext`? - - - -[`Context`](globals.md#context-1) +`context`? -The additional context to get the flag for. +[`ContextWithTracking`](globals.md#contextwithtracking)
-###### Returns +###### Returns -[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<[`Flag`](globals.md#flagtconfig)\> +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<[`FlagValueFromDefault`](globals.md#flagvaluefromdefaultt)\<`Default`\>\> -evaluated flag - -##### getFlags() +### getFlags() ```ts -getFlags(options: ContextWithTracking): Record +getFlags(options: ContextWithTracking): Record ``` -Gets the evaluated flags for the current context which includes the user, company, and custom context. +Return all values and immediately register checks for the returned roots. -###### Parameters +###### Parameters - @@ -2242,43 +2367,30 @@ Gets the evaluated flags for the current context which includes the user, compan [`ContextWithTracking`](globals.md#contextwithtracking) - -
Parameter TypeDescription
- -The options for the context. -
-###### Returns - -[`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, [`Flag`](globals.md#flagtconfig)\> - -The evaluated flags. +###### Returns -###### Remarks +[`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, `undefined` \| [`FlagValue`](globals.md#flagvalue)\> -Call `initialize` before calling this method to ensure the flag definitions are cached, no flags will be returned otherwise. - -##### getFlagsForBootstrap() +### getFlagsForBootstrap() ```ts getFlagsForBootstrap(options: ContextWithTracking): BootstrappedFlags ``` -Gets the evaluated flags for the current context without wrapping them in getters. -This method returns raw flag data suitable for bootstrapping client-side applications. +Serialization is not a read by the browser; it must not emit check events. -###### Parameters +###### Parameters - @@ -2292,47 +2404,31 @@ This method returns raw flag data suitable for bootstrapping client-side applica [`ContextWithTracking`](globals.md#contextwithtracking) - -
Parameter TypeDescription
- -The options for the context. -
-###### Returns +###### Returns [`BootstrappedFlags`](globals.md#bootstrappedflags) -The evaluated raw flags and the context. - -###### Remarks - -Call `initialize` before calling this method to ensure the flag definitions are cached, no flags will be returned otherwise. -This method returns RawFlag objects without wrapping them in getters, making them suitable for serialization. - -##### getFlagsRemote() +### getFlagsRemote() ```ts getFlagsRemote( - userId?: IdType, - companyId?: IdType, -additionalContext?: Context): Promise> + userId?: IdType, + companyId?: IdType, +context?: ContextWithTracking): Promise> ``` -Gets evaluated flags with the usage of remote context. -This method triggers a network request every time it's called. - -###### Parameters +###### Parameters - @@ -2346,11 +2442,6 @@ This method triggers a network request every time it's called. [`IdType`](globals.md#idtype) - - @@ -2363,74 +2454,52 @@ The userId of the user to get the flags for. [`IdType`](globals.md#idtype) - - -
Parameter TypeDescription
- -The userId of the user to get the flags for. -
- -The companyId of the company to get the flags for. -
-`additionalContext`? - - - -[`Context`](globals.md#context-1) +`context`? -The additional context to get the flags for. +[`ContextWithTracking`](globals.md#contextwithtracking)
-###### Returns +###### Returns -[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<[`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, [`Flag`](globals.md#flagtconfig)\>\> +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<[`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, `undefined` \| [`FlagValue`](globals.md#flagvalue)\>\> -evaluated flags - -##### initialize() +### initialize() ```ts initialize(): Promise ``` -Initializes the client by caching the flags definitions. - -###### Returns +###### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> -###### Remarks - -Call this method before calling `getFlags` to ensure the flag definitions are cached. -The client will ignore subsequent calls to this method. - -##### pushFlagOverrides() +### pushFlagOverrides() ```ts -pushFlagOverrides(overrides: - | Partial> +pushFlagOverrides(overrides: + | Partial> | FlagOverridesFn): () => void ``` -Temporarily layers flag overrides on top of the current overrides. - -###### Parameters +###### Parameters - @@ -2442,64 +2511,34 @@ Temporarily layers flag overrides on top of the current overrides. -
Parameter TypeDescription
- \| [`Partial`](https://www.typescriptlang.org/docs/handbook/utility-types.html#partialtype)\<[`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, [`FlagOverride`](globals.md#flagoverride)\>\> \| [`FlagOverridesFn`](globals.md#flagoverridesfn) - - - -The flag overrides to apply for the scoped period. + \| [`Partial`](https://www.typescriptlang.org/docs/handbook/utility-types.html#partialtype)\<[`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, [`FlagValue`](globals.md#flagvalue)\>\> \| [`FlagOverridesFn`](globals.md#flagoverridesfn)
-###### Returns +###### Returns `Function` -A remove function that removes only this override layer. - -###### Returns +###### Returns `void` -###### Remarks - -This is intended for tests or other short-lived local overrides. The remove -function is idempotent and can safely be called multiple times. - -###### Example - -```ts -let remove: (() => void) | undefined; - -beforeEach(() => { - remove = client.pushFlagOverrides({ "flag-1": true }); -}); - -afterEach(() => { - remove?.(); - remove = undefined; -}); -``` - -##### refreshFlags() +### refreshFlags() ```ts refreshFlags(waitForVersion?: number): Promise ``` -Refreshes the flag definitions from the server. - -###### Parameters +###### Parameters - @@ -2513,58 +2552,30 @@ Refreshes the flag definitions from the server. `number` - -
Parameter TypeDescription
- -Optional flag state version to wait for before returning updated definitions. -
-###### Returns +###### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> -###### Remarks - -This triggers an on-demand refresh of the cached flag definitions. -Useful when you know flags have changed and don't want to wait for the next automatic refresh cycle. - -Note: updated flag rules take a few seconds to propagate to all servers. - -Fetch starts are throttled to at most once per second. -Outside `in-request` mode, throttling only delays when the next fetch -begins: `refreshFlags(99)` still waits until the cache has applied flag -definitions from version `99` or newer before the promise resolves. -Concurrent callers are deduplicated and may share the same in-flight or -scheduled follow-up refresh. - -In `in-request` mode, delayed follow-up refreshes are not scheduled. On edge -runtimes like Cloudflare Workers, a call during the throttle window only -records pending refresh work, and the promise may resolve before that fetch -runs. The pending refresh is executed on the next request/access or -`refreshFlags()` call after the throttle window expires. - -##### setFlagOverrides() +### setFlagOverrides() ```ts -setFlagOverrides(overrides: - | Partial> +setFlagOverrides(overrides: + | Partial> | FlagOverridesFn): void ``` -Replaces the base flag overrides used by the client. - -###### Parameters +###### Parameters - @@ -2576,50 +2587,29 @@ Replaces the base flag overrides used by the client. -
Parameter TypeDescription
- \| [`Partial`](https://www.typescriptlang.org/docs/handbook/utility-types.html#partialtype)\<[`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, [`FlagOverride`](globals.md#flagoverride)\>\> \| [`FlagOverridesFn`](globals.md#flagoverridesfn) - - - -The flag overrides. + \| [`Partial`](https://www.typescriptlang.org/docs/handbook/utility-types.html#partialtype)\<[`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, [`FlagValue`](globals.md#flagvalue)\>\> \| [`FlagOverridesFn`](globals.md#flagoverridesfn)
-###### Returns +###### Returns `void` -###### Remarks - -Base overrides are always applied before any temporary layers added through -`pushFlagOverrides()`. - -###### Example - -```ts -client.setFlagOverrides({ - "flag-1": true, - "flag-2": false, -}); -``` - -##### track() +### track() ```ts track( - userId: IdType, - event: string, + userId: IdType, + event: string, options?: TrackOptions & { companyId: IdType; }): Promise ``` -Tracks an event in Reflag. - -###### Parameters +###### Parameters @@ -2668,19 +2658,11 @@ Tracks an event in Reflag.
-###### Returns +###### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> -###### Throws - -An error if the user is not set or the event is invalid or the options are invalid. - -###### Remarks - -If the company is set, the event will be associated with the company. - -##### updateCompany() +### updateCompany() ```ts updateCompany(companyId: IdType, options?: TrackOptions & { @@ -2688,16 +2670,13 @@ updateCompany(companyId: IdType, options?: TrackOptions & { }): Promise ``` -Updates the associated company in Reflag. - -###### Parameters +###### Parameters - @@ -2711,11 +2690,6 @@ Updates the associated company in Reflag. [`IdType`](globals.md#idtype) - - @@ -2728,45 +2702,28 @@ The companyId of the company to update. [`TrackOptions`](globals.md#trackoptions) & \{ `userId`: [`IdType`](globals.md#idtype); \} - -
Parameter TypeDescription
- -The companyId of the company to update. -
- -The options for the company. -
-###### Returns +###### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> -###### Throws - -An error if the company is not set or the options are invalid. - -###### Remarks - -The company must be set using `withCompany` before calling this method. -If the user is set, the company will be associated with the user. - -##### updateUser() +### updateUser() ```ts updateUser(userId: IdType, options?: TrackOptions): Promise ``` -Updates the associated user in Reflag. - -###### Parameters +###### Parameters - @@ -2780,11 +2737,6 @@ Updates the associated user in Reflag. [`IdType`](globals.md#idtype) - - @@ -2797,47 +2749,30 @@ The userId of the user to update. [`TrackOptions`](globals.md#trackoptions) - -
Parameter TypeDescription
- -The userId of the user to update. -
- -The options for the user. -
-###### Returns +###### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> -###### Throws - -An error if the company is not set or the options are invalid. +## Interfaces -###### Remarks +### ContextWithTracking -The company must be set using `withCompany` before calling this method. -If the user is set, the company will be associated with the user. +#### Extends -## Interfaces +- [`Context`](globals.md#context) -### ContextWithTracking - -A context with tracking option. - -#### Extends - -- [`Context`](globals.md#context-1) - -#### Properties +#### Properties - @@ -2849,12 +2784,7 @@ A context with tracking option. - @@ -2868,11 +2798,6 @@ The company context. If no `id` key is set, the whole object is ignored. `string` - - @@ -2883,12 +2808,7 @@ The avatar URL of the company. - @@ -2902,11 +2822,6 @@ The identifier of the company. `string` - - @@ -2917,276 +2832,116 @@ The name of the company. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + - - -
Property TypeDescription
-\{ `[k: string]`: `any`; `avatar`: `string`; `id`: `undefined` \| `string` \| `number`; `name`: `string`; \} - - - -The company context. If no `id` key is set, the whole object is ignored. +\{ `[key: string]`: `any`; `avatar`: `string`; `id`: `undefined` \| [`IdType`](globals.md#idtype); `name`: `string`; \}
- -The avatar URL of the company. -
-`undefined` \| `string` \| `number` - - - -The identifier of the company. +`undefined` \| [`IdType`](globals.md#idtype)
- -The name of the company. -
-`boolean` - - - -Enable tracking for the context. -If set to `false`, tracking will be disabled for the context. Default is `true`. - -
- - `meta?` - - - -[`TrackingMeta`](globals.md#trackingmeta) - - - -The meta context used to update the user or company when syncing is required during -feature retrieval. - -
- - `other?` - - - -[`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, `any`\> - - - -The other context. This is used for any additional context that is not related to user or company. - -
- - `user?` - - - -\{ `[k: string]`: `any`; `avatar`: `string`; `email`: `string`; `id`: `undefined` \| `string` \| `number`; `name`: `string`; \} - - - -The user context. If no `id` key is set, the whole object is ignored. - -
- -`user.avatar?` - - - -`string` - - - -The avatar URL of the user. - -
- -`user.email?` - - - -`string` - - - -The email of the user. - -
- -`user.id` - - - -`undefined` \| `string` \| `number` - - - -The identifier of the user. +`boolean`
-`user.name?` + `meta?` -`string` +[`TrackingMeta`](globals.md#trackingmeta)
-The name of the user. + `other?`
- -*** - -### Flag\ - -Describes a feature +
-#### Type Parameters +[`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, `any`\> - - - - - + - - - -
Type ParameterDefault type
-`TConfig` *extends* [`FlagType`](globals.md#flagtype)\[`"config"`\] + `user?` -[`EmptyFlagRemoteConfig`](globals.md#emptyflagremoteconfig) +\{ `[key: string]`: `any`; `avatar`: `string`; `email`: `string`; `id`: `undefined` \| [`IdType`](globals.md#idtype); `name`: `string`; \}
- -#### Properties - - - - - - - - - - + + - - + + -
PropertyTypeDescription
- `config` +`user.avatar?` - \| [`EmptyFlagRemoteConfig`](globals.md#emptyflagremoteconfig) \| \{ `key`: `string`; \} & `TConfig` +`string`
-‐ +`user.email?`
- `isEnabled` +`string`
-`boolean` +`user.id` -If the feature is enabled. +`undefined` \| [`IdType`](globals.md#idtype)
- `key` +`user.name?` `string` - - -The key of the feature. -
-#### Methods - -##### track() - -```ts -track(): Promise -``` - -Track feature usage in Reflag. - -###### Returns - -[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> - *** -### Flags - -Describes a collection of evaluated features. - -#### Remarks +### Flags -You should extend the Flags interface to define the available features. +Augment this interface with flag keys and their returned value types. *** -### FlagsFallbackProvider +### FlagsFallbackProvider -Provider used to load and save raw flag definition snapshots. +#### Methods -#### Methods - -##### load() +### load() ```ts load(context: FlagsFallbackProviderContext): Promise ``` -Load a previously saved snapshot. - -###### Parameters +###### Parameters @@ -3211,19 +2966,17 @@ Load a previously saved snapshot.
-###### Returns +###### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`undefined` \| [`FlagsFallbackSnapshot`](globals.md#flagsfallbacksnapshot)\> -##### save() +### save() ```ts save(context: FlagsFallbackProviderContext, snapshot: FlagsFallbackSnapshot): Promise ``` -Persist a snapshot after a successful live fetch. - -###### Parameters +###### Parameters @@ -3260,35 +3013,26 @@ Persist a snapshot after a successful live fetch.
-###### Returns +###### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> *** -### HttpClient - -Defines the interface for an HTTP client. +### HttpClient -#### Remarks +#### Methods -This interface is used to abstract the HTTP client implementation from the SDK. -Define your own implementation of this interface to use a different HTTP client. - -#### Methods - -##### get() +### get() ```ts -get( - url: string, - headers: Record, -timeoutMs: number): Promise> +get( + url: string, + headers: Record, +timeoutMs: number): Promise> ``` -Sends a GET request to the specified URL. - -###### Type Parameters +###### Type Parameters @@ -3300,21 +3044,20 @@ Sends a GET request to the specified URL.
-`TResponse` +`Response`
-###### Parameters +###### Parameters - @@ -3328,11 +3071,6 @@ Sends a GET request to the specified URL. `string` - - @@ -3345,11 +3083,6 @@ The URL to send the request to. [`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, `string`\> - - @@ -3362,34 +3095,25 @@ The headers to include in the request. `number` - -
Parameter TypeDescription
- -The URL to send the request to. -
- -The headers to include in the request. -
- -‐ -
-###### Returns - -[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<[`HttpClientResponse`](globals.md#httpclientresponsetresponse)\<`TResponse`\>\> +###### Returns -The response from the server. +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<[`HttpClientResponse`](globals.md#httpclientresponseresponse)\<`Response`\>\> -##### post() +### post() ```ts -post( - url: string, - headers: Record, -body: TBody): Promise> +post( + url: string, + headers: Record, +body: Body): Promise> ``` -Sends a POST request to the specified URL. - -###### Type Parameters +###### Type Parameters @@ -3401,28 +3125,27 @@ Sends a POST request to the specified URL.
-`TBody` +`Body`
-`TResponse` +`Response`
-###### Parameters +###### Parameters - @@ -3436,11 +3159,6 @@ Sends a POST request to the specified URL. `string` - - @@ -3453,11 +3171,6 @@ The URL to send the request to. [`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, `string`\> - - @@ -3468,268 +3181,222 @@ The headers to include in the request. -
Parameter TypeDescription
- -The URL to send the request to. -
- -The headers to include in the request. -
-`TBody` - - - -The body of the request. +`Body`
-###### Returns +###### Returns -[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<[`HttpClientResponse`](globals.md#httpclientresponsetresponse)\<`TResponse`\>\> - -The response from the server. +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<[`HttpClientResponse`](globals.md#httpclientresponseresponse)\<`Response`\>\> *** -### Logger +### Logger + +#### Methods -Logger interface for logging messages +### debug() + +```ts +debug(message: string, data?: any): void +``` -#### Properties +###### Parameters - + - - - - - - - - - - - - -
PropertyParameter TypeDescription
- `debug` - - - -(`message`: `string`, `data`?: `any`) => `void` - - - -Log a debug messages - -
- - `error` - - - -(`message`: `string`, `data`?: `any`) => `void` - - - -Log an error messages - -
- - `info` - - - -(`message`: `string`, `data`?: `any`) => `void` +`message` -Log an info messages +`string`
- `warn` - - - -(`message`: `string`, `data`?: `any`) => `void` +`data`? -Log a warning messages +`any`
-*** +###### Returns + +`void` -### RawFlag +### error() -Describes a feature. +```ts +error(message: string, data?: any): void +``` -#### Properties +###### Parameters - + - - - - - +
PropertyParameter TypeDescription
- `config?` - - - -[`RawFlagRemoteConfig`](globals.md#rawflagremoteconfig) +`message` -The remote configuration value for the feature. +`string`
- `evaluationErrors?` - - - -`EvaluationError`[] +`data`? -Non-fatal diagnostics produced while evaluating targeting rules. +`any`
+
- `isEnabled` +###### Returns -
+`void` -`boolean` +### info() - +```ts +info(message: string, data?: any): void +``` -If the feature is enabled. +###### Parameters -
+ + + + + + - - + +
ParameterType
- `key` +`message` `string` - - -The key of the feature. -
- ~~`missingContextFields?`~~ +`data`? -`string`[] +`any` +
-The missing fields in the evaluation context (optional). +###### Returns -**Deprecated** +`void` -Use `evaluationErrors` and check for `MISSING_CONTEXT_FIELD`. +### warn() -
+```ts +warn(message: string, data?: any): void +``` - `ruleEvaluationResults?` +###### Parameters -
+ + + + + + + + -
ParameterType
-`boolean`[] +`message` -The rule results of the evaluation (optional). +`string`
- `targetingVersion?` - - - -`number` +`data`? -The version of the targeting used to evaluate if the feature is enabled (optional). +`any`
-## Type Aliases +###### Returns -### Attributes +`void` + +## Type Aliases + +### Attributes ```ts type Attributes = Record; ``` -Describes the attributes of a user, company or event. - *** -### BatchBufferOptions\ +### BatchBufferOptions\ ```ts type BatchBufferOptions = { @@ -3741,15 +3408,12 @@ type BatchBufferOptions = { }; ``` -Options for configuring the BatchBuffer. - -#### Type Parameters +#### Type Parameters - @@ -3758,17 +3422,12 @@ Options for configuring the BatchBuffer. `T` - -
Type ParameterDescription
- -The type of items in the buffer. -
-#### Type declaration +#### Type declaration @@ -3792,7 +3451,7 @@ The type of items in the buffer. @@ -3809,10 +3468,8 @@ A function that handles flushing the items in the buffer. @@ -3829,11 +3486,7 @@ shutdown hook before exiting. @@ -3845,12 +3498,12 @@ If `0`, the buffer is flushed only when `maxSize` is reached. @@ -3867,7 +3520,7 @@ The logger to use for logging (optional). @@ -3876,19 +3529,18 @@ The maximum size of the buffer before it is flushed. *** -### BootstrappedFlags +### BootstrappedFlags ```ts type BootstrappedFlags = { context: Context; flags: RawFlags; flagStateVersion: number; + protocolVersion: 2; }; ``` -Describes a collection of evaluated raw flags and the context for bootstrapping. - -#### Type declaration +#### Type declaration
-A function that handles flushing the items in the buffer. +‐
-Whether to flush the buffer on natural process exit (`beforeExit`). -This does not install signal handlers. For signal-driven shutdown or an -explicit `process.exit()`, await `client.flush()` in your application's -shutdown hook before exiting. +Flush on natural process exit (beforeExit), without installing signal handlers. +For signals or process.exit(), await client.flush() in the application hook.
-The interval in milliseconds at which the buffer is flushed. - -**Remarks** - -If `0`, the buffer is flushed only when `maxSize` is reached. +‐
-[`Logger`](globals.md#logger-2) +[`Logger`](globals.md#logger) -The logger to use for logging (optional). +‐
-The maximum size of the buffer before it is flushed. +‐
@@ -3906,7 +3558,7 @@ Describes a collection of evaluated raw flags and the context for bootstrapping. @@ -3932,6 +3584,18 @@ Describes a collection of evaluated raw flags and the context for bootstrapping. `number` + + + + + @@ -3939,7 +3603,7 @@ Describes a collection of evaluated raw flags and the context for bootstrapping. *** -### CacheStrategy +### CacheStrategy ```ts type CacheStrategy = "periodically-update" | "in-request"; @@ -3947,7 +3611,7 @@ type CacheStrategy = "periodically-update" | "in-request"; *** -### ClientOptions +### ClientOptions ```ts type ClientOptions = { @@ -3957,10 +3621,10 @@ type ClientOptions = { configFile: string; emitEvaluationEvents: boolean; fallbackFlags: | TypedFlagKey[] - | Record>; + | FlagOverrides; fetchTimeoutMs: number; flagOverrides: | FlagOverrides - | (context: Context) => FlagOverrides; + | FlagOverridesFn; flagsFallbackProvider: FlagsFallbackProvider; flagsFetchRetries: number; flagsPushUrl: string; @@ -3974,9 +3638,7 @@ type ClientOptions = { }; ``` -Defines the options for the SDK client. - -#### Type declaration +#### Type declaration
-[`Context`](globals.md#context-1) +[`Context`](globals.md#context)
+ + `protocolVersion` + + + +`2` +
@@ -4000,7 +3662,7 @@ Defines the options for the SDK client. @@ -4017,8 +3679,7 @@ The host to send requests to (optional). @@ -4037,7 +3698,7 @@ If not provided, the default options are used. **Deprecated** -Use `flagsSyncMode`. +Use flagsSyncMode. @@ -4054,9 +3715,7 @@ Use `flagsSyncMode`. @@ -4073,11 +3732,9 @@ set through the environment variable REFLAG_CONFIG_FILE. @@ -4090,20 +3747,12 @@ This option has no effect and will be removed in the next major version. @@ -4120,8 +3769,7 @@ Use `flagsFallbackProvider` instead. @@ -4133,16 +3781,13 @@ Default is 10000 ms. @@ -4159,8 +3804,7 @@ and should return a record of flag keys and boolean or object values. @@ -4177,8 +3821,7 @@ Ignored in offline mode. @@ -4195,7 +3838,7 @@ Default is 3 times. @@ -4207,16 +3850,12 @@ Push endpoint used when `flagsSyncMode` is `"push"`. @@ -4235,7 +3874,7 @@ How flag definitions are synchronized. **Deprecated** -Use `apiBaseUrl` instead. +Use apiBaseUrl. @@ -4247,12 +3886,12 @@ Use `apiBaseUrl` instead. @@ -4264,12 +3903,12 @@ The HTTP client to use for sending requests (optional). Default is the built-in @@ -4281,12 +3920,12 @@ The logger to use for logging (optional). Default is info level logging to conso @@ -4303,9 +3942,7 @@ Use the console logger, but set a log level. Ineffective if a custom logger is p @@ -4322,7 +3959,7 @@ This is useful for testing or development. @@ -4331,36 +3968,32 @@ The secret key used to authenticate with the Reflag API. *** -### Context +### Context ```ts type Context = { company: { - [k: string]: any; avatar: string; - id: string | number | undefined; + [key: string]: any; avatar: string; + id: IdType | undefined; name: string; }; other: Record; user: { - [k: string]: any; avatar: string; + [key: string]: any; avatar: string; email: string; - id: string | number | undefined; + id: IdType | undefined; name: string; }; }; ``` -Describes the current user context, company context, and other context. -This is used to determine if feature targeting matches and to track events. - -#### Type declaration +#### Type declaration
-The host to send requests to (optional). +‐
-The options for the batch buffer (optional). -If not provided, the default options are used. +‐
-The path to the config file. If supplied, the config file will be loaded. -Defaults to `reflag.config.json` when NODE_ENV is not production. Can also be -set through the environment variable REFLAG_CONFIG_FILE. +‐
-Deprecated: evaluation events are no longer emitted. - **Deprecated** -This option has no effect and will be removed in the next major version. +Evaluation events are not emitted.
\| [`TypedFlagKey`](globals.md#typedflagkey)[] - \| [`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<[`TypedFlagKey`](globals.md#typedflagkey), [`Exclude`](https://www.typescriptlang.org/docs/handbook/utility-types.html#excludeuniontype-excludedmembers)\<[`FlagOverride`](globals.md#flagoverride), `false`\>\> + \| [`FlagOverrides`](globals.md#flagoverrides) -The features to "enable" as fallbacks when the API is unavailable (optional). -Can be an array of feature keys, or a record of feature keys and boolean or object values. - -If a record is supplied instead of array, the values of each key are either the -configuration values or the boolean value `true`. - -**Deprecated** - -Use `flagsFallbackProvider` instead. +Value-only startup fallbacks. Prefer a complete saved collection.
-The timeout in milliseconds for fetching feature targeting data (optional). -Default is 10000 ms. +‐
- \| [`FlagOverrides`](globals.md#flagoverrides-3) - \| (`context`: [`Context`](globals.md#context-1)) => [`FlagOverrides`](globals.md#flagoverrides-3) + \| [`FlagOverrides`](globals.md#flagoverrides) + \| [`FlagOverridesFn`](globals.md#flagoverridesfn) -Local flag overrides for testing or development. - -If a function is specified, the function will be called with the context -and should return a record of flag keys and boolean or object values. +Applied after evaluation; overrides do not change dependency results.
-Optional provider used to load and save raw flag definitions for fallback startup. -Ignored in offline mode. +‐
-Number of times to retry fetching feature definitions (optional). -Default is 3 times. +‐
-Push endpoint used when `flagsSyncMode` is `"push"`. +‐
-[`FlagsSyncMode`](globals.md#flagssyncmode-1) +[`FlagsSyncMode`](globals.md#flagssyncmode) -How flag definitions are synchronized. - -- `push` (default): live updates over SSE keep flag definitions up to date. -- `polling`: periodic background refresh. -- `in-request`: stale refresh is triggered during request handling. +‐
-[`HttpClient`](globals.md#httpclient-2) +[`HttpClient`](globals.md#httpclient) -The HTTP client to use for sending requests (optional). Default is the built-in fetch client. +‐
-[`Logger`](globals.md#logger-2) +[`Logger`](globals.md#logger) -The logger to use for logging (optional). Default is info level logging to console. +‐
-[`LogLevel`](globals.md#loglevel-1) +[`LogLevel`](globals.md#loglevel) -Use the console logger, but set a log level. Ineffective if a custom logger is provided. +‐
-In offline mode, no data is sent or fetched from the the Reflag API, -and `flagsFallbackProvider` is not used. -This is useful for testing or development. +‐
-The secret key used to authenticate with the Reflag API. +‐
- @@ -4373,16 +4006,11 @@ This is used to determine if feature targeting matches and to track events. - @@ -4395,11 +4023,6 @@ The company context. If no `id` key is set, the whole object is ignored. `string` - - @@ -4410,12 +4033,7 @@ The avatar URL of the company. - @@ -4429,11 +4047,6 @@ The identifier of the company. `string` - - @@ -4446,11 +4059,6 @@ The name of the company. [`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, `any`\> - - @@ -4462,17 +4070,12 @@ The other context. This is used for any additional context that is not related t - @@ -4485,11 +4088,6 @@ The user context. If no `id` key is set, the whole object is ignored. `string` - - @@ -4502,11 +4100,6 @@ The avatar URL of the user. `string` - - @@ -4517,12 +4110,7 @@ The email of the user. - @@ -4536,11 +4124,6 @@ The identifier of the user. `string` - - @@ -4548,7 +4131,7 @@ The name of the user. *** -### EdgeClientOptions +### EdgeClientOptions ```ts type EdgeClientOptions = Omit; @@ -4556,46 +4139,39 @@ type EdgeClientOptions = Omit ```ts -type EmptyFlagRemoteConfig = { - key: undefined; - payload: undefined; +type FileFallbackProviderOptions = { + directory: string; }; ``` -#### Type declaration +#### Type declaration
Name TypeDescription
\{ -`[k: string]`: `any`; `avatar`: `string`; - `id`: `string` \| `number` \| `undefined`; +`[key: string]`: `any`; `avatar`: `string`; + `id`: [`IdType`](globals.md#idtype) \| `undefined`; `name`: `string`; \} - - -The company context. If no `id` key is set, the whole object is ignored. -
- -The avatar URL of the company. -
-`string` \| `number` \| `undefined` - - - -The identifier of the company. +[`IdType`](globals.md#idtype) \| `undefined`
- -The name of the company. -
- -The other context. This is used for any additional context that is not related to user or company. -
\{ -`[k: string]`: `any`; `avatar`: `string`; +`[key: string]`: `any`; `avatar`: `string`; `email`: `string`; - `id`: `string` \| `number` \| `undefined`; + `id`: [`IdType`](globals.md#idtype) \| `undefined`; `name`: `string`; \} - - -The user context. If no `id` key is set, the whole object is ignored. -
- -The avatar URL of the user. -
- -The email of the user. -
-`string` \| `number` \| `undefined` - - - -The identifier of the user. +[`IdType`](globals.md#idtype) \| `undefined`
- -The name of the user. -
+ - - - @@ -4604,39 +4180,33 @@ type EmptyFlagRemoteConfig = { *** -### FileFallbackProviderOptions +### FlagCollection ```ts -type FileFallbackProviderOptions = { - directory: string; +type FlagCollection = CompiledCollection & { + segments: NonNullable; }; ``` -#### Type declaration +#### Type declaration
Name TypeDescription
- `key` - - - -`undefined` + `directory`?
- `payload` +`string` -`undefined` +Directory where per-environment snapshots are stored.
- - @@ -4645,204 +4215,91 @@ Directory where per-environment snapshots are stored. *** -### FlagAPIResponse +### FlagDefaultFor\ ```ts -type FlagAPIResponse = { - config: { - variants: FlagConfigVariant[]; - version: number; - }; - description: string | null; - key: string; - targeting: { - rules: { - filter: RuleFilter; - }[]; - version: number; - }; -}; +type FlagDefaultFor = keyof Registry extends never ? FlagDefaultValue | object : Key extends keyof Registry ? ReadonlyFlagValue | null : never; ``` -**`Internal`** +Registered defaults match the value schema; null explicitly requests arbitrary JSON. -(Internal) Describes a specific feature in the API response. - -#### Type declaration +#### Type Parameters
Name TypeDescription
- `directory`? - - - -`string` +`segments` -Directory where per-environment snapshots are stored. +[`NonNullable`](https://www.typescriptlang.org/docs/handbook/utility-types.html#nonnullabletype)\<`CompiledCollection`\[`"segments"`\]\>
- - - + - - - - - - - - - - - - - - - - - - - - - - - - - - - - +
NameTypeDescriptionType Parameter
- `config`? - - - -\{ - `variants`: [`FlagConfigVariant`](globals.md#flagconfigvariant)[]; - `version`: `number`; - \} - - - -The remote configuration for the feature. - -
- -`config.variants` - - - -[`FlagConfigVariant`](globals.md#flagconfigvariant)[] - - - -The variants of the remote configuration. - -
- -`config.version` - - - -`number` - - - -The version of the remote configuration. - -
- - `description` - - - -`string` \| `null` - - - -Description of the feature. - -
- - `key` - - - -`string` - - - -The key of the feature. +`Registry`
- `targeting` - - - -\{ - `rules`: \{ - `filter`: `RuleFilter`; - \}[]; - `version`: `number`; - \} - - - -The targeting rules for the feature. +`Key` *extends* `PropertyKey`
- -`targeting.rules` - - - -\{ - `filter`: `RuleFilter`; - \}[] - - - -The targeting rules. +
-
+*** -`targeting.version` +### FlagDefaultValue - +```ts +type FlagDefaultValue = + | null + | boolean + | number + | string + | readonly FlagDefaultValue[] +| {}; +``` -`number` +JSON defaults may be readonly; returned values are independent mutable copies. - +*** -The version of the targeting rules. +### FlagDefinition -
+```ts +type FlagDefinition = CompiledFlag; +``` *** -### FlagConfigVariant +### FlagEvent ```ts -type FlagConfigVariant = { - filter: RuleFilter; +type FlagEvent = { + action: "check"; + evalContext: Record; + evalErrors: ( + | EvaluationError + | { + code: "CLIENT_NOT_INITIALIZED"; + field: string; + message: string; + })[]; + evalMissingFields: string[]; + evalResult: string; + evalRuleResults: boolean[]; + flagStateVersion: number; key: string; - payload: any; + sourceVersionId: string; }; ``` -Describes a remote feature config variant. +A check records the selected variant key, never its JSON payload. -#### Type declaration +#### Type declaration @@ -4856,224 +4313,151 @@ Describes a remote feature config variant. - - - - - - - - - - - -
- `filter` - - - -`RuleFilter` - - - -The filter for the variant. - -
- - `key` - - - -`string` - - - -The key of the variant. - -
- - `payload` + `action` -`any` +`"check"` -The optional user-supplied payload data. +‐
- -*** - -### FlagDefinition - -```ts -type FlagDefinition = { - config: { - variants: FlagConfigVariant[]; - version: number; - }; - description: string | null; - flag: { - rules: { - filter: RuleFilter; - }[]; - version: number; - }; - key: string; -}; -``` - -Describes a feature definition. - -#### Type declaration - - - - - - - - - - @@ -5092,38 +4476,21 @@ The key of the feature. *** -### FlagOverride - -```ts -type FlagOverride = - | FlagType & { - config: { - key: string; - }; - isEnabled: boolean; - } - | boolean; -``` - -*** - -### FlagOverrides +### FlagOverrides ```ts -type FlagOverrides = Partial : { [FlagKey in keyof Flags]: Flags[FlagKey] extends FlagOverride ? Flags[FlagKey] : Exclude }>; +type FlagOverrides = Partial : { [Key in keyof Flags]: Flags[Key] }>; ``` -Describes the feature overrides. - *** -### FlagOverridesFn() +### FlagOverridesFn() ```ts type FlagOverridesFn = (context: Context) => FlagOverrides; ``` -#### Parameters +#### Parameters
NameTypeDescription
- `config`? + `evalContext`? -\{ - `variants`: [`FlagConfigVariant`](globals.md#flagconfigvariant)[]; - `version`: `number`; - \} +[`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, `unknown`\> -The remote configuration for the feature. +‐
-`config.variants` + `evalErrors`? -[`FlagConfigVariant`](globals.md#flagconfigvariant)[] +( + \| `EvaluationError` + \| \{ + `code`: `"CLIENT_NOT_INITIALIZED"`; + `field`: `string`; + `message`: `string`; + \})[] -The variants of the remote configuration. +‐
-`config.version` + `evalMissingFields`? -`number` +`string`[] -The version of the remote configuration. +**Deprecated** + +Use evalErrors and check for MISSING_CONTEXT_FIELD.
- `description` + `evalResult`? -`string` \| `null` +`string` -Description of the feature. +‐
- `flag` + `evalRuleResults`? -\{ - `rules`: \{ - `filter`: `RuleFilter`; - \}[]; - `version`: `number`; - \} +`boolean`[] -The targeting rules for the feature. +‐
-`flag.rules` + `flagStateVersion`? -\{ - `filter`: `RuleFilter`; - \}[] +`number` -The targeting rules. +‐
-`flag.version` + `key` -`number` +`string` -The version of the targeting rules. +‐
- `key` + `sourceVersionId`? @@ -5083,7 +4467,7 @@ The version of the targeting rules. -The key of the feature. +‐
@@ -5141,145 +4508,59 @@ type FlagOverridesFn = (context: Context) => FlagOverrides;
-[`Context`](globals.md#context-1) +[`Context`](globals.md#context)
-#### Returns - -[`FlagOverrides`](globals.md#flagoverrides-3) - -*** - -### FlagRemoteConfig - -```ts -type FlagRemoteConfig = - | { - key: string; - payload: any; - } - | EmptyFlagRemoteConfig; -``` - -A remotely managed configuration value for a feature. - -#### Type declaration - -\{ - `key`: `string`; - `payload`: `any`; - \} - - - - - - - - - - - - - - - - - - - - - -
NameTypeDescription
- -`key` - - - -`string` - - - -The key of the matched configuration value. - -
- -`payload` - - - -`any` - - - -The optional user-supplied payload data. - -
+#### Returns -[`EmptyFlagRemoteConfig`](globals.md#emptyflagremoteconfig) +[`FlagOverrides`](globals.md#flagoverrides) *** -### FlagsAPIResponse +### FlagsAPIResponse ```ts -type FlagsAPIResponse = { - features: FlagAPIResponse[]; +type FlagsAPIResponse = FlagCollection & { flagStateVersion: number; + protocolVersion: 2; }; ``` -**`Internal`** - -(Internal) Describes the response of the features endpoint. - -#### Type declaration +#### Type declaration - - - @@ -5288,7 +4569,7 @@ should be treated as unknown by consumers. *** -### FlagsFallbackProviderContext +### FlagsFallbackProviderContext ```ts type FlagsFallbackProviderContext = { @@ -5296,17 +4577,13 @@ type FlagsFallbackProviderContext = { }; ``` -Non-secret context passed to fallback providers so they can derive -storage keys without access to the raw secret key. - -#### Type declaration +#### Type declaration
Name TypeDescription
- `features` - - - -[`FlagAPIResponse`](globals.md#flagapiresponse)[] +`flagStateVersion` -The feature definitions. +`number`
- `flagStateVersion`? - - - -`number` +`protocolVersion` -Optional for backward compatibility; when absent, the snapshot version -should be treated as unknown by consumers. +`2`
- @@ -5320,11 +4597,6 @@ storage keys without access to the raw secret key. `string` - - @@ -5332,50 +4604,45 @@ Deterministic hash of the configured secret key. *** -### FlagsFallbackSnapshot +### FlagsFallbackSnapshot ```ts -type FlagsFallbackSnapshot = { - flags: FlagAPIResponse[]; +type FlagsFallbackSnapshot = FlagCollection & { + flagStateVersion: number; savedAt: string; - version: number; + source: "static"; + version: 2; }; ``` -Snapshot of flag definitions used for fallback initialization. +V1 snapshots cannot be evaluated by the collection evaluator. -#### Type declaration +#### Type declaration
Name TypeDescription
- -Deterministic hash of the configured secret key. -
- - + + - - + + @@ -5411,7 +4680,7 @@ Snapshot schema version. *** -### FlagsSyncMode +### FlagsSyncMode ```ts type FlagsSyncMode = "polling" | "in-request" | "push"; @@ -5419,49 +4688,41 @@ type FlagsSyncMode = "polling" | "in-request" | "push"; *** -### FlagType +### FlagValue ```ts -type FlagType = { - config: { - payload: any; - }; -}; +type FlagValue = + | null + | boolean + | number + | string + | FlagValue[] +| {}; ``` -#### Type declaration +*** + +### FlagValueFromDefault\ + +```ts +type FlagValueFromDefault = T extends null ? FlagValue : T extends boolean ? boolean : T extends number ? number : T extends string ? string : T extends readonly infer Element[] ? [Element] extends [never] ? FlagValue[] : FlagValueFromDefault[] : T extends object ? { -readonly [Key in keyof T]: FlagValueFromDefault } : never; +``` + +Infer values from defaults, widening literals. Null explicitly requests arbitrary JSON. + +#### Type Parameters
Name TypeDescription
- `flags` - - - -[`FlagAPIResponse`](globals.md#flagapiresponse)[] +`flagStateVersion`? -Raw flag definitions as returned by the API. +`number`
- `savedAt` +`savedAt` @@ -5383,26 +4650,28 @@ Raw flag definitions as returned by the API. `string`
-ISO timestamp indicating when the snapshot was saved. +`source`?
- `version` +`"static"`
-`number` +`version` -Snapshot schema version. +`2`
- - + - - - - - @@ -5470,17 +4731,17 @@ type FlagType = { *** -### GCSFallbackProviderClient +### GCSFallbackProviderClient ```ts -type GCSFallbackProviderClient = +type GCSFallbackProviderClient = | GCSLegacyClient | GCSGoogleApisClient; ``` *** -### GCSFallbackProviderOptions +### GCSFallbackProviderOptions ```ts type GCSFallbackProviderOptions = { @@ -5490,7 +4751,7 @@ type GCSFallbackProviderOptions = { }; ``` -#### Type declaration +#### Type declaration
NameTypeType Parameter
- `config`? - - - -\{ - `payload`: `any`; - \} - -
- -`config.payload` - - - -`any` +`T`
@@ -5562,7 +4823,7 @@ Prefix for generated per-environment keys. *** -### GCSGoogleApisClient +### GCSGoogleApisClient ```ts type GCSGoogleApisClient = { @@ -5575,7 +4836,7 @@ type GCSGoogleApisClient = { }; ``` -#### Type declaration +#### Type declaration
@@ -5633,7 +4894,7 @@ type GCSGoogleApisClient = { *** -### GCSLegacyClient +### GCSLegacyClient ```ts type GCSLegacyClient = { @@ -5647,7 +4908,7 @@ type GCSLegacyClient = { }; ``` -#### Type declaration +#### Type declaration
@@ -5680,45 +4941,37 @@ type GCSLegacyClient = { *** -### HttpClientResponse\ +### HttpClientResponse\ ```ts -type HttpClientResponse = { - body: TResponse | undefined; +type HttpClientResponse = { + body: Response | undefined; etag: string; ok: boolean; status: number; }; ``` -Describes the response of a HTTP client. - -#### Type Parameters +#### Type Parameters
- -
Type ParameterDescription
-`TResponse` - - - -The type of the response body. +`Response`
-#### Type declaration +#### Type declaration @@ -5737,12 +4990,12 @@ The type of the response body. @@ -5759,8 +5012,7 @@ The body of the response if available. @@ -5777,7 +5029,7 @@ conditional flag-definition refreshes with a custom HTTP client. @@ -5794,7 +5046,7 @@ Indicates that the request succeeded. @@ -5803,7 +5055,7 @@ The status code of the response. *** -### IdType +### IdType ```ts type IdType = string | number; @@ -5811,7 +5063,7 @@ type IdType = string | number; *** -### LogLevel +### LogLevel ```ts type LogLevel = typeof LOG_LEVELS[number]; @@ -5819,135 +5071,59 @@ type LogLevel = typeof LOG_LEVELS[number]; *** -### RawFlagRemoteConfig +### RawFlag ```ts -type RawFlagRemoteConfig = { - evaluationErrors: EvaluationError[]; - key: string; - missingContextFields: string[]; - payload: any; - ruleEvaluationResults: boolean[]; - targetingVersion: number; +type RawFlag = Omit, "sourceVersionId" | "value" | "resolved"> & { + resolved: boolean; + sourceVersionId: string; + value: FlagValue | undefined; }; ``` -A remotely managed configuration value for a feature. - -#### Type declaration +#### Type declaration
-`TResponse` \| `undefined` +`Response` \| `undefined` -The body of the response if available. +‐
-The response's ETag, if available. Return its exact value to enable -conditional flag-definition refreshes with a custom HTTP client. +Exact response ETag for conditional definition refreshes, when available.
-Indicates that the request succeeded. +‐
-The status code of the response. +‐
- - - - - - - - - - - - - - - - - - - @@ -5956,17 +5132,15 @@ The version of the targeting rules used to select the config value. *** -### RawFlags +### RawFlags ```ts -type RawFlags = Record; +type RawFlags = Record; ``` -Describes a collection of evaluated raw flags. - *** -### RedisFallbackProviderOptions +### RedisFallbackProviderOptions ```ts type RedisFallbackProviderOptions = { @@ -5978,7 +5152,7 @@ type RedisFallbackProviderOptions = { }; ``` -#### Type declaration +#### Type declaration
Name TypeDescription
- `evaluationErrors`? +`resolved` -`EvaluationError`[] - - - -Non-fatal diagnostics produced while evaluating targeting rules. +`boolean`
- `key` +`sourceVersionId`? `string` - - -The key of the matched configuration value. - -
- - `missingContextFields`? - - - -`string`[] - - - -The missing fields in the evaluation context (optional). - -**Deprecated** - -Use `evaluationErrors` and check for `MISSING_CONTEXT_FIELD`. - -
- - `payload` - - - -`any` - - - -The optional user-supplied payload data. - -
- - `ruleEvaluationResults`? - - - -`boolean`[] - - - -The rule results of the evaluation (optional). -
- `targetingVersion`? - - - -`number` +`value` -The version of the targeting rules used to select the config value. +[`FlagValue`](globals.md#flagvalue) \| `undefined`
@@ -6065,7 +5239,7 @@ Prefix for generated per-environment keys. *** -### S3FallbackProviderOptions +### S3FallbackProviderOptions ```ts type S3FallbackProviderOptions = { @@ -6077,7 +5251,7 @@ type S3FallbackProviderOptions = { }; ``` -#### Type declaration +#### Type declaration
@@ -6163,15 +5337,15 @@ Prefix for generated per-environment keys. *** -### StaticFallbackProviderOptions +### StaticFallbackProviderOptions ```ts type StaticFallbackProviderOptions = { - flags: Record; + flags: Record; }; ``` -#### Type declaration +#### Type declaration
@@ -6185,12 +5359,12 @@ type StaticFallbackProviderOptions = {
- `flags` + `flags` -[`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, `boolean`\> +[`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, [`FlagValue`](globals.md#flagvalue)\> @@ -6204,7 +5378,7 @@ Static fallback flags keyed by flag key. *** -### TrackingMeta +### TrackingMeta ```ts type TrackingMeta = { @@ -6212,16 +5386,13 @@ type TrackingMeta = { }; ``` -Describes the meta context associated with tracking. - -#### Type declaration +#### Type declaration - @@ -6235,11 +5406,6 @@ Describes the meta context associated with tracking. `boolean` - - @@ -6247,7 +5413,7 @@ Whether the user or company is active. *** -### TrackOptions +### TrackOptions ```ts type TrackOptions = { @@ -6256,16 +5422,13 @@ type TrackOptions = { }; ``` -Defines the options for tracking of entities. - -#### Type declaration +#### Type declaration
Name TypeDescription
- -Whether the user or company is active. -
- @@ -6279,11 +5442,6 @@ Defines the options for tracking of entities. [`Attributes`](globals.md#attributes) - - @@ -6296,11 +5454,6 @@ The attributes associated with the event. [`TrackingMeta`](globals.md#trackingmeta) - - @@ -6308,30 +5461,23 @@ The meta context associated with the event. *** -### TypedFlagKey +### TypedFlagKey ```ts -type TypedFlagKey = keyof TypedFlags; +type TypedFlagKey = keyof Flags extends never ? string : Extract; ``` *** -### TypedFlags +### TypedFlags ```ts -type TypedFlags = keyof Flags extends never ? Record : { [FlagKey in keyof Flags]: Flags[FlagKey] extends FlagType ? Flag : Flag }; +type TypedFlags = keyof Flags extends never ? Record : { [Key in keyof Flags]: Flags[Key] | undefined }; ``` -Describes a collection of evaluated feature. +## Variables -#### Remarks - -This types falls back to a generic Record if the Flags interface -has not been extended. - -## Variables - -### fallbackProviders +### fallbackProviders ```ts const fallbackProviders: { @@ -6343,7 +5489,7 @@ const fallbackProviders: { }; ``` -#### Type declaration +#### Type declaration
Name TypeDescription
- -The attributes associated with the event. -
- -The meta context associated with the event. -
@@ -6442,10 +5588,4 @@ createStaticFallbackProvider
-*** - -### LOG\_LEVELS - -```ts -const LOG_LEVELS: readonly ["DEBUG", "INFO", "WARN", "ERROR"]; -``` +Using v1? [Legacy docs](../../legacy/v1/node-sdk/globals.md) · [Upgrade guide](../migrating-from-v1.md). diff --git a/supported-languages/overview.md b/supported-languages/overview.md index 15164c9..2795221 100644 --- a/supported-languages/overview.md +++ b/supported-languages/overview.md @@ -6,6 +6,10 @@ description: >- # Overview +Use a Reflag SDK to read feature flags, manage configuration, and track usage in your application. Choose your language or framework below. + +Upgrading from v1? Read [Migrating from v1](migrating-from-v1.md). Documentation for the v1 SDKs is in [Legacy SDKs](../legacy/v1/README.md). + ## Official SDKs These SDKs are crafted and maintained by the Reflag team. diff --git a/supported-languages/react-native-sdk/README.md b/supported-languages/react-native-sdk/README.md index 91f4442..a55236e 100644 --- a/supported-languages/react-native-sdk/README.md +++ b/supported-languages/react-native-sdk/README.md @@ -1,51 +1,39 @@ --- +layout: + visible: true title: visible: true +description: + visible: false tableOfContents: visible: true outline: visible: true pagination: visible: true -layout: - width: default - title: - visible: true - description: - visible: true - tableOfContents: - visible: true - outline: - visible: true - pagination: - visible: true - metadata: - visible: true - tags: - visible: true - actions: - visible: true - anchors: - visible: true --- -# React Native SDK (beta) +{% hint style="info" %} +**Independent SDK compatibility.** This React Native release uses React/Browser protocol v1. Follow the [matching React documentation](../../legacy/v1/react-sdk/README.md) and use a [matching Node SDK](../../legacy/v1/node-sdk/README.md) for bootstrap. Do not pass protocol-v2 bootstrap into a v1 consumer. +{% endhint %} + +# Reflag React Native SDK A thin React Native wrapper around `@reflag/react-sdk`. -For more usage details, see the [React SDK README](../../sdk/documents/react-sdk/). +For more usage details, see the [React SDK README](../../legacy/v1/react-sdk/README.md). -An Expo example app lives in [packages/react-native-sdk/dev/expo](https://github.com/reflagcom/javascript/tree/main/packages/react-native-sdk/dev/expo). +An Expo example app lives in [packages/react-native-sdk/dev/expo](https://github.com/reflagcom/javascript/tree/b4fe5b3d9386b87c6546175c323862d9878e1430/packages/react-native-sdk/dev/expo). -## Get started +## Get started -### Install +### Install ```shell npm i @reflag/react-native-sdk ``` -### 1. Add the ReflagProvider +### 1. Add the ReflagProvider Wrap your app with the provider from `@reflag/react-native-sdk`: @@ -63,7 +51,7 @@ import { ReflagProvider } from "@reflag/react-native-sdk"; ; ``` -### 2. Use `useFlag()` +### 2. Use `useFlag()` ```tsx import { useFlag } from "@reflag/react-native-sdk"; @@ -77,26 +65,27 @@ function StartHuddleButton() { } ``` -See the [React SDK README](../../sdk/documents/react-sdk/) for more details. +See the [React SDK README](../../legacy/v1/react-sdk/README.md) for more details. -## React Native differences +## React Native differences -* The Reflag toolbar is web-only and is not available in React Native. -* Built-in feedback UI is web-only. In React Native, use your own UI and call `useSendFeedback` or `client.feedback` when you're ready to send feedback. -* Live flag updates work out of the box. The React Native SDK bundles an SSE transport via `react-native-sse`, so no global `EventSource` shim is required. -* If you need custom SSE behavior, you can still override the transport by passing `eventSourceFactory` to `ReflagProvider` or `ReflagBootstrappedProvider`. +- The Reflag toolbar is web-only and is not available in React Native. +- Built-in feedback UI is web-only. In React Native, use your own UI and call `useSendFeedback` or `client.feedback` when you're ready to send feedback. +- Live flag updates work out of the box. The React Native SDK bundles an SSE transport via `react-native-sse`, so no global `EventSource` shim is required. +- If you need custom SSE behavior, you can still override the transport by passing `eventSourceFactory` to `ReflagProvider` or `ReflagBootstrappedProvider`. -## Reference +## Reference The React Native SDK shares its API with the React SDK. Use the React SDK reference for full types and details: -[React SDK Reference](../../sdk/documents/react-sdk/) +[React SDK Reference](../../legacy/v1/react-sdk/README.md) -## Cookbook +## Cookbook -### Refresh flags when the app returns to the foreground +### Refresh flags when the app returns to the foreground -Flags are updated if the context passed to `` changes, but you might also want to update them when the app comes to the foreground. See this snippet: +Flags are updated if the context passed to `` changes, but you might also want to update them when the app comes to the foreground. +See this snippet: ```tsx import React, { useEffect, useRef } from "react"; @@ -134,7 +123,7 @@ export function App() { } ``` -## Suspense loading +## Suspense loading Enable `` support by setting the `suspense` prop on the provider and wrap components that call `useFlag` in a Suspense boundary: @@ -152,12 +141,13 @@ import { ReflagProvider } from "@reflag/react-native-sdk"; You can also override the behavior for one call with `useFlag("huddle", { suspense: true })`. -## Bootstrapping +## Bootstrapping -You can use `` in React Native when you already have pre-fetched flags and want to avoid an initial fetch. Pass the full object returned by the Node SDK's `getFlagsForBootstrap()` directly as the provider's `flags` prop; it includes `context`, evaluated `flags`, and an optional `flagStateVersion`. +You can use `` in React Native when you already have pre-fetched flags and want to avoid an initial fetch. +Pass the full object returned by the Node SDK's `getFlagsForBootstrap()` directly as the provider's `flags` prop; it includes `context`, evaluated `flags`, and an optional `flagStateVersion`. If you want live flag updates to continue working after bootstrapping, use a recent `@reflag/node-sdk` so `getFlagsForBootstrap()` includes `flagStateVersion`. After bootstrapping, any live flag updates are fetched directly by the client SDK from Reflag using the client-visible context. If your bootstrapped snapshot depends on server-only or secret context that is not available in the app, later live refreshes may differ. In that case, keep `enableLiveFlagUpdates` disabled. -For bootstrap usage patterns and options, see the [React SDK bootstrapping docs](../../sdk/documents/react-sdk/). +For bootstrap usage patterns and options, see the [React SDK bootstrapping docs](../../legacy/v1/react-sdk/README.md). diff --git a/supported-languages/react-native-sdk/globals.md b/supported-languages/react-native-sdk/globals.md index 9849dbb..4c309eb 100644 --- a/supported-languages/react-native-sdk/globals.md +++ b/supported-languages/react-native-sdk/globals.md @@ -1,101 +1,367 @@ --- +layout: + visible: true title: visible: true +description: + visible: false tableOfContents: visible: true outline: visible: true pagination: visible: true -layout: - width: default - title: - visible: true - description: - visible: true - tableOfContents: - visible: true - outline: - visible: true - pagination: - visible: true - metadata: - visible: true - tags: - visible: true - actions: - visible: true - anchors: - visible: true --- -# Reference +{% hint style="info" %} +**Independent SDK compatibility.** This React Native release uses React/Browser protocol v1. Follow the [matching React documentation](../../legacy/v1/react-sdk/README.md) and use a [matching Node SDK](../../legacy/v1/node-sdk/README.md) for bootstrap. Do not pass protocol-v2 bootstrap into a v1 consumer. +{% endhint %} -## Interfaces +# @reflag/react-native-sdk -### CheckEvent +## Interfaces + +### CheckEvent Event representing checking the flag evaluation result -#### Properties +#### Properties + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyTypeDescription
+ + `action` + + + +`"check-is-enabled"` \| `"check-config"` + + + +`check-is-enabled` means `isEnabled` was checked, `check-config` means `config` was checked. + +
+ + `evaluationErrors?` + + + +\{ `code`: `string`; `field`: `string`; `message`: `string`; `operator`: `string`; \}[] + + + +Non-fatal diagnostics produced while evaluating the flag. + +
+ + `key` + + + +`string` + + + +Flag key. + +
+ + ~~`missingContextFields?`~~ + + + +`string`[] + + + +Missing context fields. + +**Deprecated** + +Use `evaluationErrors` and check for `MISSING_CONTEXT_FIELD`. + +
+ + `ruleEvaluationResults?` + + + +`boolean`[] + + + +Rule evaluation results. + +
+ + `value?` + + + + \| `boolean` \| \{ `key`: `string`; `payload`: `any`; \} + + + +Result of flag or configuration evaluation. +If `action` is `check-is-enabled`, this is the result of the flag evaluation and `value` is a boolean. +If `action` is `check-config`, this is the result of the configuration evaluation. + +
+ + `version?` + + + +`number` + + -| Property | Type | Description | -| --------------------------- | -------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `action` | `"check-is-enabled"` \| `"check-config"` | `check-is-enabled` means `isEnabled` was checked, `check-config` means `config` was checked. | -| `evaluationErrors?` | { `code`: `string`; `field`: `string`; `message`: `string`; `operator`: `string`; }\[] | Non-fatal diagnostics produced while evaluating the flag. | -| `key` | `string` | Flag key. | -| ~~`missingContextFields?`~~ | `string`\[] |

Missing context fields.

Deprecated

Use evaluationErrors and check for MISSING_CONTEXT_FIELD.

| -| `ruleEvaluationResults?` | `boolean`\[] | Rule evaluation results. | -| `value?` | \| `boolean` \| { `key`: `string`; `payload`: `any`; } | Result of flag or configuration evaluation. If `action` is `check-is-enabled`, this is the result of the flag evaluation and `value` is a boolean. If `action` is `check-config`, this is the result of the configuration evaluation. | -| `version?` | `number` | Version of targeting rules. | +Version of targeting rules. + +
*** -### CompanyContext +### CompanyContext -Context is a set of key-value pairs. This is used to determine if feature targeting matches and to track events. Id should always be present so that it can be referenced to an existing company. +Context is a set of key-value pairs. +This is used to determine if feature targeting matches and to track events. +Id should always be present so that it can be referenced to an existing company. -#### Indexable +#### Indexable ```ts [key: string]: ContextValue ``` -#### Properties +#### Properties + + + + + + + + + + + + + + + + + + + + + +
PropertyTypeDescription
+ + `id` + + + +`undefined` \| `string` \| `number` + + + +Company id + +
+ + `name?` + + + +`string` + + -| Property | Type | Description | -| -------- | ----------------------------------- | ------------ | -| `id` | `undefined` \| `string` \| `number` | Company id | -| `name?` | `string` | Company name | +Company name + +
*** -### Flag\ +### Flag\ Describes a feature -#### Type Parameters +#### Type Parameters + + + + + + + + + + + + + + +
Type ParameterDefault type
+ +`TConfig` *extends* [`FlagType`](globals.md#flagtype)\[`"config"`\] + + + +[`EmptyFlagRemoteConfig`](globals.md#emptyflagremoteconfig) + +
+ +#### Properties + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyTypeDescription
+ + `config` + + + + \| [`EmptyFlagRemoteConfig`](globals.md#emptyflagremoteconfig) \| \{ `key`: `string`; \} & `TConfig` + + + +‐ + +
+ + `isEnabled` + + + +`boolean` + + + +If the feature is enabled. + +
+ + `isLoading` + + + +`boolean` + + + +If the feature is loading. + +
+ + `key` + + + +`string` + + + +The key of the feature. -| Type Parameter | Default type | -| ------------------------------------------------------------------ | ----------------------------------------------------------- | -| `TConfig` _extends_ [`FlagType`](globals.md#flagtype)\[`"config"`] | [`EmptyFlagRemoteConfig`](globals.md#emptyflagremoteconfig) | +
-#### Properties + `requestFeedback` -| Property | Type | Description | -| ----------------- | -------------------------------------------------------------------------------------------------- | ------------------------------- | -| `config` | \| [`EmptyFlagRemoteConfig`](globals.md#emptyflagremoteconfig) \| { `key`: `string`; } & `TConfig` | ‐ | -| `isEnabled` | `boolean` | If the feature is enabled. | -| `isLoading` | `boolean` | If the feature is loading. | -| `key` | `string` | The key of the feature. | -| `requestFeedback` | (`opts`: [`RequestFeedbackOptions`](globals.md#requestfeedbackoptions)) => `void` | Request feedback from the user. | + -#### Methods +(`opts`: [`RequestFeedbackOptions`](globals.md#requestfeedbackoptions)) => `void` -**track()** + + +Request feedback from the user. + +
+ +#### Methods + +### track() ```ts -track(): +track(): | undefined | Promise< | undefined @@ -104,37 +370,99 @@ track(): Track feature usage in Reflag. -**Returns** +###### Returns -\| `undefined` | [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)< | `undefined` | [`Response`](https://developer.mozilla.org/docs/Web/API/Response)> + \| `undefined` + \| [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\< + \| `undefined` + \| [`Response`](https://developer.mozilla.org/docs/Web/API/Response)\> *** -### Flags +### Flags *** -### UserContext +### UserContext -Context is a set of key-value pairs. This is used to determine if feature targeting matches and to track events. Id should always be present so that it can be referenced to an existing user. +Context is a set of key-value pairs. +This is used to determine if feature targeting matches and to track events. +Id should always be present so that it can be referenced to an existing user. -#### Indexable +#### Indexable ```ts [key: string]: ContextValue ``` -#### Properties +#### Properties + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyTypeDescription
+ + `email?` + + + +`string` + + + +User email + +
+ + `id` -| Property | Type | Description | -| -------- | ----------------------------------- | ----------- | -| `email?` | `string` | User email | -| `id` | `undefined` \| `string` \| `number` | User id | -| `name?` | `string` | User name | + -## Type Aliases +`undefined` \| `string` \| `number` -### BootstrappedFlags + + +User id + +
+ + `name?` + + + +`string` + + + +User name + +
+ +## Type Aliases + +### BootstrappedFlags ```ts type BootstrappedFlags = BootstrappedState & { @@ -142,15 +470,34 @@ type BootstrappedFlags = BootstrappedState & { }; ``` -#### Type declaration +#### Type declaration + + + + + + + + + + + + + + +
NameType
-| Name | Type | -| ------- | ------------------------------------------------ | -| `flags` | [`RawFlags`](../browser-sdk/globals.md#rawflags) | +`flags` + + + +[`RawFlags`](../../legacy/v1/browser-sdk/globals.md#rawflags) + +
*** -### EmptyFlagRemoteConfig +### EmptyFlagRemoteConfig ```ts type EmptyFlagRemoteConfig = { @@ -159,16 +506,46 @@ type EmptyFlagRemoteConfig = { }; ``` -#### Type declaration +#### Type declaration + + + + + + + + + + + + + + + + + + +
NameType
+ + `key` + + -| Name | Type | -| --------- | ----------- | -| `key` | `undefined` | -| `payload` | `undefined` | +`undefined` + +
+ + `payload` + + + +`undefined` + +
*** -### FlagKey +### FlagKey ```ts type FlagKey = keyof TypedFlags; @@ -176,10 +553,10 @@ type FlagKey = keyof TypedFlags; *** -### FlagRemoteConfig +### FlagRemoteConfig ```ts -type FlagRemoteConfig = +type FlagRemoteConfig = | { key: string; payload: any; @@ -189,20 +566,64 @@ type FlagRemoteConfig = A remotely managed configuration value for a feature. -#### Type declaration +#### Type declaration + +\{ + `key`: `string`; + `payload`: `any`; + \} + + + + + + + + + + + + + + + + + + + + + +
NameTypeDescription
+ +`key` + + + +`string` + + + +The key of the matched configuration value. + +
+ +`payload` + + + +`any` + + -{ `key`: `string`; `payload`: `any`; } +The optional user-supplied payload data. -| Name | Type | Description | -| --------- | -------- | ------------------------------------------- | -| `key` | `string` | The key of the matched configuration value. | -| `payload` | `any` | The optional user-supplied payload data. | +
[`EmptyFlagRemoteConfig`](globals.md#emptyflagremoteconfig) *** -### FlagType +### FlagType ```ts type FlagType = { @@ -212,36 +633,89 @@ type FlagType = { }; ``` -#### Type declaration +#### Type declaration -| Name | Type | -| ---------------- | --------------------- | -| `config`? | { `payload`: `any`; } | -| `config.payload` | `any` | + + + + + + + + + + + + + + + + + +
NameType
+ + `config`? + + + +\{ + `payload`: `any`; + \} + +
+ +`config.payload` + + + +`any` + +
*** -### OptInFlag +### OptInFlag ```ts -type OptInFlag = Omit & { +type OptInFlag = Omit & { key: FlagKey; }; ``` An opt-in-enabled flag for the generated React SDK flag definitions. -Includes all fields from [BrowserOptInFlag](../browser-sdk/globals.md#optinflag): `name`, `description`, `isEnabled`, `userOptedIn`, `companyOptedIn`, and `isOptedIn`. Only `key` is narrowed to the generated [FlagKey](globals.md#flagkey) type. +Includes all fields from [BrowserOptInFlag](../../legacy/v1/browser-sdk/globals.md#optinflag): `name`, `description`, +`isEnabled`, `userOptedIn`, `companyOptedIn`, and `isOptedIn`. +Only `key` is narrowed to the generated [FlagKey](globals.md#flagkey) type. + +#### Type declaration + + + + + + + + + + + + + + +
NameType
+ +`key` + + -#### Type declaration +[`FlagKey`](globals.md#flagkey) -| Name | Type | -| ----- | ------------------------------- | -| `key` | [`FlagKey`](globals.md#flagkey) | +
*** -### RawFlags +### RawFlags ```ts type RawFlags = Record; @@ -251,7 +725,7 @@ Describes a collection of evaluated raw flags. *** -### ReflagBootstrappedProps +### ReflagBootstrappedProps ```ts type ReflagBootstrappedProps = ReflagPropsBase & ReflagInitOptionsBase & { @@ -261,15 +735,41 @@ type ReflagBootstrappedProps = ReflagPropsBase & ReflagInitOptionsBase & { Props for the ReflagBootstrappedProvider. -#### Type declaration +#### Type declaration -| Name | Type | Description | -| ------- | --------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ | -| `flags` | [`BootstrappedFlags`](globals.md#bootstrappedflags) | Pre-fetched flags used for the initial render. The browser client fetches opt-in metadata on demand when opt-in flags are requested. | + + + + + + + + + + + + + + + +
NameTypeDescription
+ +`flags` + + + +[`BootstrappedFlags`](globals.md#bootstrappedflags) + + + +Pre-fetched flags used for the initial render. The browser client fetches opt-in +metadata on demand when opt-in flags are requested. + +
*** -### ReflagClientProviderProps +### ReflagClientProviderProps ```ts type ReflagClientProviderProps = Omit & { @@ -279,18 +779,37 @@ type ReflagClientProviderProps = Omit & { Props for the ReflagClientProvider. -#### Type declaration +#### Type declaration -| Name | Type | -| -------- | -------------------------------------------------------- | -| `client` | [`ReflagClient`](../browser-sdk/globals.md#reflagclient) | + + + + + + + + + + + + + +
NameType
+ +`client` + + + +[`ReflagClient`](../../legacy/v1/browser-sdk/globals.md#reflagclient) + +
*** -### ReflagInitOptionsBase +### ReflagInitOptionsBase ```ts -type ReflagInitOptionsBase = Omit ```ts type ReflagProps = ReflagPropsBase & ReflagInitOptionsBase & { @@ -319,18 +838,105 @@ type ReflagProps = ReflagPropsBase & ReflagInitOptionsBase & { Props for the ReflagProvider. -#### Type declaration +#### Type declaration + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameTypeDescription
+ +`company`? + + + +[`CompanyContext`](globals.md#companycontext) + + + +Company related context. If you provide `id` Reflag will enrich the evaluation context with +company attributes on Reflag servers. + +**Deprecated** + +Use `context` instead, this property will be removed in the next major version + +
+ +`context`? + + + +[`ReflagContext`](../../legacy/v1/browser-sdk/globals.md#reflagcontext) + + + +The context to use for the ReflagClient containing user, company, and other context. + +
+ +`otherContext`? + + + +[`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, `string` \| `number` \| `undefined`\> + + + +Context which is not related to a user or a company. + +**Deprecated** + +Use `context` instead, this property will be removed in the next major version + +
+ +`user`? -| Name | Type | Description | -| --------------- | ------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `company`? | [`CompanyContext`](globals.md#companycontext) |

Company related context. If you provide id Reflag will enrich the evaluation context with company attributes on Reflag servers.

Deprecated

Use context instead, this property will be removed in the next major version

| -| `context`? | [`ReflagContext`](../browser-sdk/globals.md#reflagcontext) | The context to use for the ReflagClient containing user, company, and other context. | -| `otherContext`? | [`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)<`string`, `string` \| `number` \| `undefined`> |

Context which is not related to a user or a company.

Deprecated

Use context instead, this property will be removed in the next major version

| -| `user`? | [`UserContext`](globals.md#usercontext) |

User related context. If you provide id Reflag will enrich the evaluation context with user attributes on Reflag servers.

Deprecated

Use context instead, this property will be removed in the next major version

| +
+ +[`UserContext`](globals.md#usercontext) + + + +User related context. If you provide `id` Reflag will enrich the evaluation context with +user attributes on Reflag servers. + +**Deprecated** + +Use `context` instead, this property will be removed in the next major version + +
*** -### ReflagPropsBase +### ReflagPropsBase ```ts type ReflagPropsBase = { @@ -347,20 +953,129 @@ type ReflagPropsBase = { Base props for the ReflagProvider and ReflagBootstrappedProvider. -#### Type declaration +#### Type declaration + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameTypeDescription
+ + `children`? + + + +`ReactNode` + + + +The children to render after the client is initialized. + +
+ + `debug`? + + + +`boolean` + + + +Set to `true` to enable debug logging to the console, + +
+ + `initialLoading`? + + + +`boolean` -| Name | Type | Description | -| ------------------- | ---------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `children`? | `ReactNode` | The children to render after the client is initialized. | -| `debug`? | `boolean` | Set to `true` to enable debug logging to the console, | -| `initialLoading`? | `boolean` | Set to `true` to show the loading component while the client is initializing. | -| `loadingComponent`? | `ReactNode` | A React component to show while the client is initializing. | -| `logger`? | [`Logger`](../browser-sdk/globals.md#logger-1) | A custom logger to use for SDK logs. Use this for advanced control or filtering of SDK logs. If both `logger` and `debug` are provided, `logger` takes precedence. | -| `suspense`? | `boolean` | Set to `true` to make `useFlag` and `useOptInFlags` suspend while their required flag data is loading. Components that call either hook must be wrapped in a React `` boundary. | + + +Set to `true` to show the loading component while the client is initializing. + +
+ + `loadingComponent`? + + + +`ReactNode` + + + +A React component to show while the client is initializing. + +
+ + `logger`? + + + +[`Logger`](../../legacy/v1/browser-sdk/globals.md#logger) + + + +A custom logger to use for SDK logs. +Use this for advanced control or filtering of SDK logs. +If both `logger` and `debug` are provided, `logger` takes precedence. + +
+ + `suspense`? + + + +`boolean` + + + +Set to `true` to make `useFlag` and `useOptInFlags` suspend while their +required flag data is loading. Components that call either hook must be +wrapped in a React `` boundary. + +
*** -### RequestFeedbackOptions +### RequestFeedbackOptions ```ts type RequestFeedbackOptions = Omit; @@ -368,27 +1083,68 @@ type RequestFeedbackOptions = Omit *** -### SetOptInOptions +### SetOptInOptions ```ts type SetOptInOptions = { optedIn: boolean; - scope: "user" | "company"; + scope?: "user" | "company"; }; ``` Options for changing the current user or company's opt-in membership. -#### Type declaration +#### Type declaration + + + + + + + + + + + + + + + + + + + + + +
NameTypeDescription
+ + `optedIn` -| Name | Type | Description | -| --------- | ----------------------- | -------------------------------------------------------------------------- | -| `optedIn` | `boolean` | Whether the scoped subject has opted in. | -| `scope`? | `"user"` \| `"company"` | Whether to update the current user or current company. Defaults to `user`. | + + +`boolean` + + + +Whether the scoped subject has opted in. + +
+ + `scope`? + + + +`"user"` \| `"company"` + + + +Whether to update the current user or current company. Defaults to `user`. + +
*** -### StorageAdapter +### StorageAdapter ```ts type StorageAdapter = { @@ -398,17 +1154,58 @@ type StorageAdapter = { }; ``` -#### Type declaration +#### Type declaration + + + + + + + + + + + + + + + + + + + + + + +
NameType
+ + `getItem()` + + + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`null` \| `string`\> + +
+ + `removeItem()`? + + + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> + +
+ + `setItem()` + + + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> -| Name | Type | -| --------------- | ------------------------------------------------------------------------------------------------------------------- | -| `getItem()` | [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<`null` \| `string`> | -| `removeItem()`? | [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<`void`> | -| `setItem()` | [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<`void`> | +
*** -### TrackEvent +### TrackEvent ```ts type TrackEvent = { @@ -420,18 +1217,71 @@ type TrackEvent = { }; ``` -#### Type declaration +#### Type declaration -| Name | Type | -| ------------- | ------------------------------------------------------------------------------------------------------------------------- | -| `attributes`? | \| [`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)<`string`, `any`> \| `null` | -| `company`? | [`CompanyContext`](globals.md#companycontext) | -| `eventName` | `string` | -| `user` | [`UserContext`](globals.md#usercontext) | + + + + + + + + + + + + + + + + + + + + + + + + + +
NameType
+ + `attributes`? + + + + \| [`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, `any`\> + \| `null` + +
+ + `company`? + + + +[`CompanyContext`](globals.md#companycontext) + +
+ + `eventName` + + + +`string` + +
+ + `user` + + + +[`UserContext`](globals.md#usercontext) + +
*** -### TypedFlags +### TypedFlags ```ts type TypedFlags = keyof Flags extends never ? Record : { [TypedFlagKey in keyof Flags]: Flags[TypedFlagKey] extends FlagType ? Flag : Flag }; @@ -439,13 +1289,14 @@ type TypedFlags = keyof Flags extends never ? Record : { [TypedFla Describes a collection of evaluated feature. -#### Remarks +#### Remarks -This types falls back to a generic Record\ if the Flags interface has not been extended. +This types falls back to a generic Record if the Flags interface +has not been extended. *** -### UseFlagOptions +### UseFlagOptions ```ts type UseFlagOptions = { @@ -453,69 +1304,152 @@ type UseFlagOptions = { }; ``` -#### Type declaration +#### Type declaration + + + + + + + + + + + + + + + + +
NameTypeDescription
+ + `suspense`? + + + +`boolean` + + + +Override the provider suspense setting for this `useFlag` call. +When true, `useFlag` throws a promise while flags are loading. -| Name | Type | Description | -| ----------- | --------- | ------------------------------------------------------------------------------------------------------------------------------ | -| `suspense`? | `boolean` | Override the provider suspense setting for this `useFlag` call. When true, `useFlag` throws a promise while flags are loading. | +
-## Functions +## Functions -### ReflagBootstrappedProvider() +### ReflagBootstrappedProvider() ```ts function ReflagBootstrappedProvider(props: ReflagBootstrappedProps): Element ``` -#### Parameters +#### Parameters -| Parameter | Type | -| --------- | --------------------------------------------------------------- | -| `props` | [`ReflagBootstrappedProps`](globals.md#reflagbootstrappedprops) | + + + + + + + + + + + + + +
ParameterType
-#### Returns +`props` + + + +[`ReflagBootstrappedProps`](globals.md#reflagbootstrappedprops) + +
+ +#### Returns `Element` *** -### ReflagClientProvider() +### ReflagClientProvider() ```ts function ReflagClientProvider(__namedParameters: ReflagClientProviderProps): React.JSX.Element ``` -#### Parameters +#### Parameters + + + + + + + + + + + + + + +
ParameterType
+ +`__namedParameters` -| Parameter | Type | -| ------------------- | ------------------------------------------------------------------- | -| `__namedParameters` | [`ReflagClientProviderProps`](globals.md#reflagclientproviderprops) | + -#### Returns +[`ReflagClientProviderProps`](globals.md#reflagclientproviderprops) + +
+ +#### Returns `React.JSX.Element` *** -### ReflagProvider() +### ReflagProvider() ```ts function ReflagProvider(props: ReflagProps): Element ``` -#### Parameters +#### Parameters + + + + + + + + + + + + + + +
ParameterType
+ +`props` + + + +[`ReflagProps`](globals.md#reflagprops) -| Parameter | Type | -| --------- | --------------------------------------- | -| `props` | [`ReflagProps`](globals.md#reflagprops) | +
-#### Returns +#### Returns `Element` *** -### useClient() +### useClient() ```ts function useClient(): ReflagClient @@ -525,13 +1459,13 @@ Returns the current `ReflagClient` used by the `ReflagProvider`. This is useful if you need to access the `ReflagClient` outside of the `ReflagProvider`. -#### Returns +#### Returns -[`ReflagClient`](../browser-sdk/globals.md#reflagclient) +[`ReflagClient`](../../legacy/v1/browser-sdk/globals.md#reflagclient) The `ReflagClient`. -#### Example +#### Example ```ts import { useClient } from '@reflag/react-sdk'; @@ -544,36 +1478,79 @@ function App() { *** -### ~~useFeature()~~ +### ~~useFeature()~~ ```ts function useFeature(key: TKey, options?: UseFlagOptions): Flag ``` -#### Type Parameters +#### Type Parameters -| Type Parameter | -| ------------------------- | -| `TKey` _extends_ `string` | + + + + + + + + + + + +
Type Parameter
-#### Parameters +`TKey` *extends* `string` -| Parameter | Type | -| ---------- | --------------------------------------------- | -| `key` | `TKey` | -| `options`? | [`UseFlagOptions`](globals.md#useflagoptions) | +
-#### Returns +#### Parameters -[`Flag`](globals.md#flagtconfig)<[`EmptyFlagRemoteConfig`](globals.md#emptyflagremoteconfig)> + + + + + + + + + + + + + + + + + +
ParameterType
-#### Deprecated +`key` + + + +`TKey` + +
+ +`options`? + + + +[`UseFlagOptions`](globals.md#useflagoptions) + +
+ +#### Returns + +[`Flag`](globals.md#flagtconfig)\<[`EmptyFlagRemoteConfig`](globals.md#emptyflagremoteconfig)\> + +#### Deprecated use `useFlag` instead *** -### useFlag() +### useFlag() ```ts function useFlag(key: TKey, options?: UseFlagOptions): TypedFlags[TKey] @@ -589,40 +1566,85 @@ function HuddleButton() { } ``` -#### Type Parameters +#### Type Parameters + + + + + + + + + + + + +
Type Parameter
-| Type Parameter | -| ------------------------- | -| `TKey` _extends_ `string` | +`TKey` *extends* `string` -#### Parameters +
-| Parameter | Type | -| ---------- | --------------------------------------------- | -| `key` | `TKey` | -| `options`? | [`UseFlagOptions`](globals.md#useflagoptions) | +#### Parameters -#### Returns + + + + + + + + + + + + + + + + + +
ParameterType
-[`TypedFlags`](globals.md#typedflags)\[`TKey`] +`key` + + + +`TKey` + +
+ +`options`? + + + +[`UseFlagOptions`](globals.md#useflagoptions) + +
+ +#### Returns + +[`TypedFlags`](globals.md#typedflags)\[`TKey`\] *** -### useIsLoading() +### useIsLoading() ```ts function useIsLoading(): boolean ``` -Returns a boolean indicating if the Reflag client is loading. You can use this to check if the Reflag client is loading at any point in your application. Initially, the value will be true until the client is initialized. +Returns a boolean indicating if the Reflag client is loading. +You can use this to check if the Reflag client is loading at any point in your application. +Initially, the value will be true until the client is initialized. -#### Returns +#### Returns `boolean` A boolean indicating if the Reflag client is loading. -#### Example +#### Example ```ts import { useIsLoading } from '@reflag/react-sdk'; @@ -634,36 +1656,106 @@ console.log(isLoading); *** -### useOnEvent() +### useOnEvent() ```ts function useOnEvent( - event: THookType, - handler: (arg0: HookArgs[THookType]) => void, + event: THookType, + handler: (arg0: HookArgs[THookType]) => void, client?: ReflagClient): void ``` Attach a callback handler to client events to act on changes. It automatically disposes itself on unmount. -#### Type Parameters +#### Type Parameters + + + + + + + + + + + + +
Type Parameter
+ +`THookType` *extends* keyof [`HookArgs`](../../legacy/v1/browser-sdk/globals.md#hookargs) + +
+ +#### Parameters + + + + + + + + + + + + + + + + + + + + + + + + + + +
ParameterTypeDescription
+ +`event` + + + +`THookType` + + + +The event to listen to. + +
+ +`handler` + + + +(`arg0`: [`HookArgs`](../../legacy/v1/browser-sdk/globals.md#hookargs)\[`THookType`\]) => `void` -| Type Parameter | -| ---------------------------------------------------------------------------- | -| `THookType` _extends_ keyof [`HookArgs`](../browser-sdk/globals.md#hookargs) | + -#### Parameters +The function to call when the event is triggered. -| Parameter | Type | Description | -| --------- | ---------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | -| `event` | `THookType` | The event to listen to. | -| `handler` | (`arg0`: [`HookArgs`](../browser-sdk/globals.md#hookargs)\[`THookType`]) => `void` | The function to call when the event is triggered. | -| `client`? | [`ReflagClient`](../browser-sdk/globals.md#reflagclient) | The Reflag client to listen to. If not provided, the client will be retrieved from the context. | +
-#### Returns +`client`? + + + +[`ReflagClient`](../../legacy/v1/browser-sdk/globals.md#reflagclient) + + + +The Reflag client to listen to. If not provided, the client will be retrieved from the context. + +
+ +#### Returns `void` -#### Example +#### Example ```ts import { useOnEvent } from '@reflag/react-sdk'; @@ -675,7 +1767,7 @@ useOnEvent("flagsUpdated", () => { *** -### useOptInFlags() +### useOptInFlags() ```ts function useOptInFlags(options?: UseOptInFlagsOptions): UseOptInFlagsResult @@ -683,31 +1775,56 @@ function useOptInFlags(options?: UseOptInFlagsOptions): UseOptInFlagsResult Returns opt-in-enabled flags and their loading state for the current context. -The loading state is only used with `ReflagBootstrappedProvider` while opt-in metadata is fetched on demand. Regular providers load opt-in metadata with the initial flags; use [useIsLoading](globals.md#useisloading) for their loading state. When suspense is enabled for the provider or this hook, it suspends instead of returning a loading result. A Suspense boundary alone does not enable it. +The loading state is only used with `ReflagBootstrappedProvider` while +opt-in metadata is fetched on demand. Regular providers load opt-in metadata +with the initial flags; use [useIsLoading](globals.md#useisloading) for their loading state. +When suspense is enabled for the provider or this hook, it suspends instead +of returning a loading result. A Suspense boundary alone does not enable it. -If fetching opt-in metadata fails, loading ends without exposing an error. Call `refresh()` on the client returned by [useClient](globals.md#useclient) to retry. +If fetching opt-in metadata fails, loading ends without exposing an error. +Call `refresh()` on the client returned by [useClient](globals.md#useclient) to retry. -#### Parameters +#### Parameters -| Parameter | Type | -| ---------- | ---------------------------------------------------------------------- | -| `options`? | [`UseOptInFlagsOptions`](../react-sdk/globals.md#useoptinflagsoptions) | + + + + + + + + + + + + + +
ParameterType
-#### Returns +`options`? -[`UseOptInFlagsResult`](../react-sdk/globals.md#useoptinflagsresult) + + +[`UseOptInFlagsOptions`](../../legacy/v1/react-sdk/globals.md#useoptinflagsoptions) + +
+ +#### Returns + +[`UseOptInFlagsResult`](../../legacy/v1/react-sdk/globals.md#useoptinflagsresult) *** -### useRequestFeedback() +### useRequestFeedback() ```ts function useRequestFeedback(): (options: RequestFeedbackData) => void ``` -Returns a function to open up the feedback form Note: When calling `useRequestFeedback`, user/company must already be set. +Returns a function to open up the feedback form +Note: When calling `useRequestFeedback`, user/company must already be set. -See [link](../../sdk/browser-sdk/FEEDBACK.md#reflagclientrequestfeedback-options) for more information +See [link](https://github.com/reflagcom/javascript/blob/b4fe5b3d9386b87c6546175c323862d9878e1430/browser-sdk/FEEDBACK.md#reflagclientrequestfeedback-options) for more information ```ts const requestFeedback = useRequestFeedback(); @@ -717,23 +1834,42 @@ reflag.requestFeedback({ }); ``` -#### Returns +#### Returns `Function` -**Parameters** +### Parameters + + + + + + + + + + + + + + +
ParameterType
+ +`options` -| Parameter | Type | -| --------- | ---------------------------------------------------------------------- | -| `options` | [`RequestFeedbackData`](../browser-sdk/globals.md#requestfeedbackdata) | + -**Returns** +[`RequestFeedbackData`](../../legacy/v1/browser-sdk/globals.md#requestfeedbackdata) + +
+ +### Returns `void` *** -### useSendFeedback() +### useSendFeedback() ```ts function useSendFeedback(): (opts: UnassignedFeedback) => Promise< @@ -741,9 +1877,10 @@ function useSendFeedback(): (opts: UnassignedFeedback) => Promise< | undefined> ``` -Returns a function to manually send feedback collected from a user. Note: When calling `useSendFeedback`, user/company must already be set. +Returns a function to manually send feedback collected from a user. +Note: When calling `useSendFeedback`, user/company must already be set. -See [link](../../sdk/browser-sdk/FEEDBACK.md#using-your-own-ui-to-collect-feedback) for more information +See [link](https://github.com/reflagcom/javascript/blob/b4fe5b3d9386b87c6546175c323862d9878e1430/browser-sdk/FEEDBACK.md#using-your-own-ui-to-collect-feedback) for more information ```ts const sendFeedback = useSendFeedback(); @@ -755,23 +1892,44 @@ sendFeedback({ }); ``` -#### Returns +#### Returns `Function` -**Parameters** +### Parameters + + + + + + + + + + + + + + +
ParameterType
+ +`opts` + + + +[`UnassignedFeedback`](../../legacy/v1/browser-sdk/globals.md#unassignedfeedback) -| Parameter | Type | -| --------- | -------------------------------------------------------------------- | -| `opts` | [`UnassignedFeedback`](../browser-sdk/globals.md#unassignedfeedback) | +
-**Returns** +### Returns -[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)< | [`Response`](https://developer.mozilla.org/docs/Web/API/Response) | `undefined`> +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\< + \| [`Response`](https://developer.mozilla.org/docs/Web/API/Response) + \| `undefined`\> *** -### useSetOptIn() +### useSetOptIn() ```ts function useSetOptIn(): (key: FlagKey, options: SetOptInOptions) => Promise< @@ -781,99 +1939,192 @@ function useSetOptIn(): (key: FlagKey, options: SetOptInOptions) => Promise< Returns a function to set whether the current user or company has opted into a flag. -Check the returned Response's `ok` property and catch promise rejections. HTTP failures return a non-OK Response; offline mode, invalid arguments, or missing scoped context return undefined. Confirmation failures can reject after the membership changed remotely. See [ReflagClient.setOptIn](../browser-sdk/globals.md#setoptin). +Check the returned Response's `ok` property and catch promise rejections. +HTTP failures return a non-OK Response; offline mode, invalid arguments, or +missing scoped context return undefined. Confirmation failures can reject +after the membership changed remotely. See [ReflagClient.setOptIn](../../legacy/v1/browser-sdk/globals.md#setoptin). -#### Returns +#### Returns `Function` -**Parameters** +### Parameters + + + + + + + + + + + + + + + + + + +
ParameterType
+ +`key` + + + +[`FlagKey`](globals.md#flagkey) + +
-| Parameter | Type | -| --------- | ----------------------------------------------- | -| `key` | [`FlagKey`](globals.md#flagkey) | -| `options` | [`SetOptInOptions`](globals.md#setoptinoptions) | +`options` -**Returns** + -[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)< | [`Response`](https://developer.mozilla.org/docs/Web/API/Response) | `undefined`> +[`SetOptInOptions`](globals.md#setoptinoptions) + +
+ +### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\< + \| [`Response`](https://developer.mozilla.org/docs/Web/API/Response) + \| `undefined`\> *** -### useTrack() +### useTrack() ```ts -function useTrack(): (eventName: string, attributes?: +function useTrack(): (eventName: string, attributes?: | Record | null) => Promise< | Response | undefined> ``` -Returns a function to send an event when a user performs an action Note: When calling `useTrack`, user/company must already be set. +Returns a function to send an event when a user performs an action +Note: When calling `useTrack`, user/company must already be set. ```ts const track = useTrack(); track("Started Huddle", { button: "cta" }); ``` -#### Returns +#### Returns `Function` -**Parameters** +### Parameters + + + + + + + + + + + + + + + + + + +
ParameterType
+ +`eventName` + + -| Parameter | Type | -| ------------- | ------------------------------------------------------------------------------------------------------------------------- | -| `eventName` | `string` | -| `attributes`? | \| [`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)<`string`, `any`> \| `null` | +`string` -**Returns** +
-[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)< | [`Response`](https://developer.mozilla.org/docs/Web/API/Response) | `undefined`> +`attributes`? + + + + \| [`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, `any`\> \| `null` + +
+ +### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\< + \| [`Response`](https://developer.mozilla.org/docs/Web/API/Response) + \| `undefined`\> *** -### useUpdateCompany() +### useUpdateCompany() ```ts function useUpdateCompany(): (opts: {}) => Promise ``` -Returns a function to update the current company's information. For example, if the company changed plan or opted into a beta-feature. +Returns a function to update the current company's information. +For example, if the company changed plan or opted into a beta-feature. -The method returned is a function which returns a promise that resolves when after the features have been updated as a result of the company update. +The method returned is a function which returns a promise that +resolves when after the features have been updated as a result +of the company update. ```ts const updateCompany = useUpdateCompany(); updateCompany({ plan: "enterprise" }).then(() => console.log("Flags updated")); ``` -#### Returns +#### Returns `Function` -**Parameters** +### Parameters + + + + + + + + + + + + + + +
ParameterType
-| Parameter | Type | -| --------- | ---- | -| `opts` | {} | +`opts` -**Returns** + -[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<`void`> +\{\} + +
+ +### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> *** -### useUpdateOtherContext() +### useUpdateOtherContext() ```ts function useUpdateOtherContext(): (opts: {}) => Promise ``` -Returns a function to update the "other" context information. For example, if the user changed workspace, you can set the workspace id here. +Returns a function to update the "other" context information. +For example, if the user changed workspace, you can set the workspace id here. -The method returned is a function which returns a promise that resolves when after the features have been updated as a result of the update to the "other" context. +The method returned is a function which returns a promise that +resolves when after the features have been updated as a result +of the update to the "other" context. ```ts const updateOtherContext = useUpdateOtherContext(); @@ -881,47 +2132,88 @@ updateOtherContext({ workspaceId: newWorkspaceId }) .then(() => console.log("Flags updated")); ``` -#### Returns +#### Returns `Function` -**Parameters** +### Parameters + + + + + + + + + + + + + + +
ParameterType
+ +`opts` + + -| Parameter | Type | -| --------- | ---- | -| `opts` | {} | +\{\} -**Returns** +
-[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<`void`> +### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> *** -### useUpdateUser() +### useUpdateUser() ```ts function useUpdateUser(): (opts: {}) => Promise ``` -Returns a function to update the current user's information. For example, if the user changed role or opted into a beta-feature. +Returns a function to update the current user's information. +For example, if the user changed role or opted into a beta-feature. -The method returned is a function which returns a promise that resolves when after the features have been updated as a result of the user update. +The method returned is a function which returns a promise that +resolves when after the features have been updated as a result +of the user update. ```ts const updateUser = useUpdateUser(); updateUser({ optInHuddles: "true" }).then(() => console.log("Flags updated")); ``` -#### Returns +#### Returns `Function` -**Parameters** +### Parameters + + + + + + + + + + + + + + +
ParameterType
+ +`opts` + + + +\{\} -| Parameter | Type | -| --------- | ---- | -| `opts` | {} | +
-**Returns** +### Returns -[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<`void`> +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> diff --git a/supported-languages/react-sdk/README.md b/supported-languages/react-sdk/README.md index f9d2c2a..02ffb0c 100644 --- a/supported-languages/react-sdk/README.md +++ b/supported-languages/react-sdk/README.md @@ -13,966 +13,211 @@ pagination: visible: true --- -# Reflag React SDK +# Reflag React SDK -React client side library for [Reflag.com](https://reflag.com) +Feature flags, remote configuration, usage tracking and feedback for React applications. Built on the [Browser SDK](../browser-sdk/README.md). -Reflag supports flag toggling, tracking flag usage, [requesting feedback](#userequestfeedback) on features, and [remotely configuring flags](#remote-config). +This page covers SDK v2. -The Reflag React SDK comes with a [built-in toolbar](https://docs.reflag.com/supported-languages/browser-sdk#toolbar) which appears on `localhost` by default. +## Get started -## Install +### 1. Add the provider -Install via npm: +Install the SDK: -```shell -npm i @reflag/react-sdk +```sh +npm install @reflag/react-sdk ``` -## Get started - -### 1. Add the `ReflagProvider` context provider - -Add the `ReflagProvider` context provider to your application: - -**Example:** +Wrap your application in `ReflagProvider` with your **publishable** key and the signed-in user's context: ```tsx import { ReflagProvider } from "@reflag/react-sdk"; } > - {/* children here are shown when loading finishes or immediately if no `loadingComponent` is given */} + ; ``` -### 2. Create a new flag and set up type safety +### 2. Create a flag -Install the Reflag CLI: +Install the Reflag CLI and create a flag: -```shell -npm i --save-dev @reflag/cli +```sh +npm install --save-dev @reflag/cli +npx reflag new ``` -Run `npx reflag new` to create your first flag! -On the first run, it will sign into Reflag and set up type generation for your project: - -```shell -❯ npx reflag new -Opened web browser to facilitate login: https://app.reflag.com/api/oauth/cli/authorize - -Welcome to ◪ Reflag! - -? Where should we generate the types? gen/flags.d.ts -? What is the output format? react -✔ Configuration created at reflag.config.json. - -Creating flag for app Slick app. -? New flag name: Huddle -? New flag key: huddle -✔ Created flag Huddle with key huddle (https://app.reflag.com/features/huddles) -✔ Generated react types in gen/flags.d.ts. -``` +The first time you run it, it signs you in to Reflag, saves its settings in `reflag.config.json` and generates types for your flags in `gen/flags.d.ts`. Choose `react` when asked for the output format, and make sure your `tsconfig.json` includes the generated file. You can also create flags in the Reflag app. -> [!Note] -> By default, types will be generated in `gen/flags.d.ts`. -> The default `tsconfig.json` file `include`s this file by default, but if your `tsconfig.json` is different, make sure the file is covered in the `include` property. +### 3. Read the flag -### 3. Use `useFlag()` to get flag status - -Using the `useFlag` hook from your components lets you toggle flags on/off and track flag usage: - -**Example:** +Use `useFlag()` in any component: ```tsx -function StartHuddleButton() { - const { - isEnabled, // boolean indicating if the flag is enabled - track, // track usage of the flag - } = useFlag("huddle"); - - if (!isEnabled) { - return null; - } +import { useFlag, useTrack } from "@reflag/react-sdk"; - return ; +function Huddles() { + const enabled = useFlag("huddles"); + const track = useTrack(); + if (!enabled) return null; + return ; } ``` -`useFlag` can help you do much more. See a full example for `useFlag` [see below](#useflag). - -## Setting context +## Read flags -Reflag determines which flags are active for a given `user`, `company`, or `other` context. -You can pass these to the `ReflagProvider` using the `context` prop. - -### Using the `context` prop +Pass a flag key to check whether the flag is enabled: ```tsx - - - {/* children here are shown when loading finishes */} - - -``` - -### Legacy individual props (deprecated) - -For backward compatibility, you can still use individual props, but these are deprecated and will be removed in the next major version: - -```tsx - - - {/* children here are shown when loading finishes */} - - -``` - -> [!Important] -> The `user`, `company`, and `otherContext` props are deprecated. Use the `context` prop instead, which provides the same functionality in a more structured way. - -### Context requirements - -If you supply `user` or `company` objects, they must include at least the `id` property otherwise they will be ignored in their entirety. -In addition to the `id`, you must also supply anything additional that you want to be able to evaluate flag targeting rules against. -Attributes which are not properties of the `user` or `company` can be supplied using the `other` property. - -Attributes cannot be nested (multiple levels) and must be either strings, numbers or booleans. -A number of special attributes exist: - -- `name` -- display name for `user`/`company`, -- `email` -- the email of the user, -- `avatar` -- the URL for `user`/`company` avatar image. - -To retrieve flags along with their targeting information, use `useFlag(key: string)` hook (described in a section below). - -Note that accessing `isEnabled` on the object returned by `useFlag()` automatically -generates a `check` event. - -## React Native - -For React Native, use `@reflag/react-native-sdk`, which is a thin wrapper around -`@reflag/react-sdk` and wires up AsyncStorage by default. - -An Expo example app lives at `packages/react-native-sdk/dev/expo`. - -## Remote config - -Remote config is a dynamic and flexible approach to configuring flag behavior outside of your app – without needing to re-deploy it. - -Similar to `isEnabled`, each flag accessed using the `useFlag()` hook, has a `config` property. This configuration is managed from within Reflag. It is managed similar to the way access to flags is managed, but instead of the -binary `isEnabled` you can have multiple configuration values which are given to different user/companies. - -### Get started with Remote config - -1. Update your flag definitions: - -```typescript -import "@reflag/react-sdk"; - -// Define your flags by extending the `Flags` interface in @reflag/react-sdk -declare module "@reflag/react-sdk" { - interface Flags { - huddle: { - // change from `boolean` to an object which sets - // a type for the remote config for `questionnaire` - maxTokens: number; - model: string; - }; - } -} -``` - -```ts -const { - isEnabled, - config: { key, payload }, -} = useFlag("huddles"); - -// isEnabled: true, -// key: "gpt-3.5", -// payload: { maxTokens: 10000, model: "gpt-3.5-beta1" } -``` - -`key` is mandatory for a config, but if a flag has no config or no config value was matched against the context, the `key` will be `undefined`. Make sure to check against this case when trying to use the configuration in your application. `payload` is an optional JSON value for arbitrary configuration needs. - -Note that, similar to `isEnabled`, accessing `config` on the object returned by `useFlag()` automatically -generates a `check` event. - -## Toolbar - -The Reflag Toolbar is great for toggling flags on/off for yourself to ensure that everything works both when a flag is on and when it's off. - -Toolbar - -The toolbar will automatically appear on `localhost`. However, it can also be incredibly useful in production. You have full control over when it appears through the `toolbar` configuration option passed to the ReflagProvider. - -You can pass a simple boolean to force the toolbar to appear/disappear: - -```ts -` component is a specialized version of `ReflagProvider` designed for server-side rendering, preloaded flag scenarios, and high-reliability setups. It uses pre-fetched evaluated state for the initial render, resulting in faster initial page loads, better SSR compatibility, and a more resilient startup path for React applications. +To read a configuration value, pass a default as the second argument. You get back a value of the same type as the default: ```tsx -import { useState, useEffect } from "react"; -import { BootstrappedFlags } from "@reflag/react-sdk"; - -interface BootstrapData { - user: User; - flags: BootstrappedFlags; -} - -function useBootstrap() { - const [data, setData] = useState(null); - - useEffect(() => { - fetch("/bootstrap") - .then((res) => res.json()) - .then(setData); - }, []); - - return data; -} - -// Usage in your app -function App() { - const { user, flags } = useBootstrap(); - - return ( - - - - - - ); -} -``` - -### Server-side endpoint setup - -Create an endpoint that provides bootstrap data to your client application: - -```typescript -// server.js or your Express app -import { ReflagClient as ReflagNodeClient } from "@reflag/node-sdk"; - -const reflagClient = new ReflagNodeClient({ - secretKey: process.env.REFLAG_SECRET_KEY, -}); -await reflagClient.initialize(); - -app.get("/bootstrap", (req, res) => { - const user = getUser(req); // Get user from your auth system - const company = getCompany(req); // Get company from your auth system - - const flags = reflagClient.getFlagsForBootstrap({ - user: { id: "user123", name: "John Doe", email: "john@acme.com" }, - company: { id: "company456", name: "Acme Inc", plan: "enterprise" }, - other: { source: "web" }, - }); - - res.status(200).json({ - user, - flags, - }); -}); -``` - -The `flags` object returned by `getFlagsForBootstrap()` contains the full bootstrapped state package: - -- `context`: the evaluation context used on the server -- `flags`: the evaluated raw flags -- `flagStateVersion`: an optional version used to avoid redundant live-update refreshes immediately after bootstrapping - -If you want live flag updates to continue working after bootstrapping, use a recent `@reflag/node-sdk` so `getFlagsForBootstrap()` includes `flagStateVersion`. - -### Next.js Page Router SSR example - -For Next.js applications using server-side rendering, you can pre-fetch flags in `getServerSideProps`: - -```typescript -// pages/index.tsx -import { GetServerSideProps } from "next"; -import { ReflagClient as ReflagNodeClient } from "@reflag/node-sdk"; -import { ReflagBootstrappedProvider, BootstrappedFlags, useFlag } from "@reflag/react-sdk"; - -interface PageProps { - bootstrapData: BootstrappedFlags; -} - -export const getServerSideProps: GetServerSideProps = async (context) => { - const serverClient = new ReflagNodeClient({ - secretKey: process.env.REFLAG_SECRET_KEY - }); - await serverClient.initialize(); - - const user = await getUserFromSession(context.req); - const company = await getCompanyFromUser(user); - - const bootstrapData = serverClient.getFlagsForBootstrap({ - user: { id: "user123", name: "John Doe", email: "john@acme.com" }, - company: { id: "company456", name: "Acme Inc", plan: "enterprise" }, - other: { page: "homepage" } - }); - - return { props: { bootstrapData } }; -}; - -export default function HomePage({ bootstrapData }: PageProps) { - return ( - - - - ); -} - -function HuddleFeature() { - const { isEnabled, track, config } = useFlag("huddle"); - - if (!isEnabled) return null; - - return ( -
-

Start a Huddle

-

Max participants: {config.payload?.maxParticipants ?? 10}

-

Video quality: {config.payload?.videoQuality ?? "standard"}

- -
- ); -} -``` - -This approach eliminates loading states and removes the initial render's dependency on the flags API. - -### Next.js App Router example - -For Next.js applications using the App Router (Next.js 13+), you can pre-fetch flags in Server Components and pass them to client components: - -```typescript -// app/layout.tsx (Server Component) -import { ReflagClient as ReflagNodeClient } from "@reflag/node-sdk"; -import { ClientProviders } from "./providers"; - -async function getBootstrapData() { - const serverClient = new ReflagNodeClient({ - secretKey: process.env.REFLAG_SECRET_KEY! - }); - await serverClient.initialize(); - - // In a real app, you'd get user/company from your auth system - const bootstrapData = serverClient.getFlagsForBootstrap({ - user: { id: "user123", name: "John Doe", email: "john@acme.com" }, - company: { id: "company456", name: "Acme Inc", plan: "enterprise" }, - other: { source: "web" } - }); - - return bootstrapData; -} - -export default async function RootLayout({ - children, -}: { - children: React.ReactNode; -}) { - const bootstrapData = await getBootstrapData(); - - return ( - - - - {children} - - - - ); -} -``` - -```typescript -// app/providers.tsx (Client Component) -"use client"; - -import { ReflagBootstrappedProvider, BootstrappedFlags } from "@reflag/react-sdk"; - -interface ClientProvidersProps { - children: React.ReactNode; - bootstrapData: BootstrappedFlags; -} - -export function ClientProviders({ children, bootstrapData }: ClientProvidersProps) { - return ( - - {children} - - ); -} -``` - -```typescript -// app/page.tsx (Server Component) -import { HuddleFeature } from "./huddle-feature"; - -export default function HomePage() { - return ( -
-

My App

- -
- ); -} +const model = useFlag("model", "quick"); // string +const settings = useFlag("huddle-settings", { maxParticipants: 10 }); // { maxParticipants: number } ``` -```typescript -// app/huddle-feature.tsx (Client Component) -"use client"; +While flags are loading, if the flag doesn't exist, or if its value has a different type, you get `false`, or your default if you passed one. Pass `null` as the default to accept any JSON value and narrow it yourself. -import { useFlag } from "@reflag/react-sdk"; +The SDK checks only the top-level type of a value. If your application depends on nested fields, validate them. -export function HuddleFeature() { - const { isEnabled, track, config } = useFlag("huddle"); +Each read records a check, which Reflag uses for launch monitoring. - if (!isEnabled) return null; +## Loading states and Suspense - return ( -
-

Start a Huddle

-

Max participants: {config.payload?.maxParticipants ?? 10}

-

Video quality: {config.payload?.videoQuality ?? "standard"}

- -
- ); -} -``` - -This App Router approach leverages Server Components for server-side flag fetching while using Client Components only where React state and hooks are needed. - -## `` component - -The `` is a lower-level component that accepts a `ReflagClient` instance. This is useful for advanced use cases where you need full control over client initialization or want to share a client instance across multiple parts of your application. - -In most cases you should initialize the client before rendering this provider. If you pass an idle client and enable `suspense`, a `useFlag()` call that suspends can initialize the client on demand; without Suspense, you must initialize the client yourself. - -### Usage +`useFlag()` returns immediately and never suspends. To show a loading UI, use `useIsLoading()` or the provider's `loadingComponent` prop: ```tsx -import { ReflagClient } from "@reflag/browser-sdk"; -import { ReflagClientProvider } from "@reflag/react-sdk"; - -// Initialize the client yourself -const client = new ReflagClient({ - publishableKey: "your-publishable-key", - user: { id: "user123", name: "John Doe" }, - company: { id: "company456", name: "Acme Inc" }, - // ... other configuration options -}); - -// Initialize the client -await client.initialize(); - -function App() { - return ( - }> - - - ); -} +} +> + + ``` -### Props - -The `ReflagClientProvider` accepts the following props: - -- `client`: A `ReflagClient` instance. Prefer passing an already-initialized client; idle clients are initialized on demand only by suspense-enabled `useFlag()` calls. -- `loadingComponent`: Optional React component to show while the client is initializing (same as `ReflagProvider`) -- `suspense`: Optional. Set to `true` to make `useFlag()` suspend while the client is loading - -> [!Note] -> Most applications should use `ReflagProvider` or `ReflagBootstrappedProvider` instead of `ReflagClientProvider`. Only use this component when you need the advanced control it provides. - -## `` component - -The `` initializes the Reflag SDK, fetches flags and starts listening for automated feedback survey events. The component can be configured using a number of props: - -- `publishableKey` is used to connect the provider to an _environment_ on Reflag. Find your `publishableKey` under [environment settings](https://app.reflag.com/env-current/settings/app-environments) in Reflag, -- `context` (recommended): An object containing `user`, `company`, and `other` properties that make up the evaluation context used to determine if a flag is enabled or not. `company` and `user` contexts are automatically transmitted to Reflag servers so the Reflag app can show you which companies have access to which flags etc. -- `company`, `user` and `other` (deprecated): Individual props for context. These are deprecated in favor of the `context` prop and will be removed in the next major version. - > [!Note] - > If you specify `company` and/or `user` they must have at least the `id` property, otherwise they will be ignored in their entirety. You should also supply anything additional you want to be able to evaluate flag targeting against, -- `fallbackFlags`: A list of strings which specify which flags to consider enabled if the SDK is unable to fetch flags. Can be provided in two formats: - - ```ts - // Simple array of flag keys - fallbackFlags={["flag1", "flag2"]} - - // Or with configuration overrides - fallbackFlags: { - "flag1": true, // just enable the flag - "flag2": { // enable with configuration - key: "variant-a", - payload: { - limit: 100, - mode: "test" - } - } - } - ``` - -- `timeoutMs`: Timeout in milliseconds when fetching flags from the server. -- `staleWhileRevalidate`: If set to `true`, stale flags will be returned while refetching flags in the background. -- `expireTimeMs`: If set, flags will be cached between page loads for this duration (in milliseconds). -- `staleTimeMs`: Maximum time (in milliseconds) that stale flags will be returned if `staleWhileRevalidate` is true and new flags cannot be fetched. -- `offline`: Provide this option when testing or in local development environments to avoid contacting Reflag servers. -- `loadingComponent` lets you specify an React component to be rendered instead of the children while the Reflag provider is initializing. If you want more control over loading screens, `useFlag()` and `useIsLoading` returns `isLoading` which you can use to customize the loading experience. -- `suspense`: Set to `true` to make `useFlag()` suspend while the provider is loading and `useOptInFlags()` suspend while required opt-in metadata is loading. Wrap components that call these hooks in React `` boundaries and omit `loadingComponent` if you want Suspense fallbacks to control loading UI. -- `enableTracking`: Set to `false` to stop sending tracking events and user/company updates to Reflag. Useful when you're impersonating a user (defaults to `true`), -- `enableLiveFlagUpdates`: Enables live flag updates over SSE. Defaults to `true` in the React SDK. -- `apiBaseUrl`: Optional base URL for the Reflag API. This also controls the SSE origin used for live flag updates and automated feedback, -- `credentials`: Optional fetch credentials mode. Set to `"include"` when proxying through your backend and authenticating with cookies; this also enables credentials for live-update SSE connections. -- `appBaseUrl`: Optional base URL for the Reflag application. Use this to override the default app URL, - -- `logger`: Optional custom logger implementation (`debug`, `info`, `warn`, `error`) used by the underlying client, -- `debug`: Set to `true` to enable debug logging to the console. If both `logger` and `debug` are provided, `logger` takes precedence, -- `toolbar`: Optional [configuration](https://docs.reflag.com/supported-languages/browser-sdk/globals#toolbaroptions) for the Reflag toolbar, -- `feedback`: Optional configuration for feedback collection - -## `` component - -The `` is a specialized version of the `ReflagProvider` that uses pre-fetched flag data for the initial render. This is ideal for server-side rendering scenarios. - -The component accepts the following props: - -- `flags`: Pre-fetched bootstrapped state of type `BootstrappedFlags` obtained from the Node SDK's `getFlagsForBootstrap()` method. This contains the context (`flags.context`), the evaluated flags (`flags.flags`), and an optional `flags.flagStateVersion`. -- All other props available in [`ReflagProvider`](#reflagprovider-component) are supported except `context`, `user`, `company`, and `other` (which are extracted from `flags.context`). - -**Example:** +To wait for flags with React Suspense, use `useFlagSuspense()`. It takes the same arguments as `useFlag()`: ```tsx -import { - ReflagBootstrappedProvider, - BootstrappedFlags, -} from "@reflag/react-sdk"; +import { Suspense } from "react"; +import { useFlagSuspense } from "@reflag/react-sdk"; -interface AppProps { - bootstrapData: BootstrappedFlags; +function Model() { + const model = useFlagSuspense("model", "quick"); + return {model}; } -function App({ bootstrapData }: AppProps) { - return ( - } - debug={process.env.NODE_ENV === "development"} - > - - - ); -} +Loading flags…}> + +; ``` -> [!Note] -> When using `ReflagBootstrappedProvider`, pass the entire object returned by `getFlagsForBootstrap()` directly as the `flags` prop. The context is extracted from `flags.context`, and `flags.flagStateVersion` is used when present. -> -> With `ReflagBootstrappedProvider`, `useOptInFlags()` requests a flags refresh on first use. It returns `isLoading: true` (or suspends) until that refresh settles. -> -> If you want live flag updates to continue working after bootstrapping, use a recent `@reflag/node-sdk` so `getFlagsForBootstrap()` includes `flagStateVersion`. -> -> After bootstrapping, any live flag updates are fetched directly by the browser SDK from Reflag using the browser-visible context. If your bootstrapped snapshot depends on server-only or secret context that is not available in the browser, later live refreshes may differ. In that case, keep `enableLiveFlagUpdates` disabled. -> -> Requesting opt-in flags also triggers a browser-side refresh, even when `enableLiveFlagUpdates` is disabled. - -## Hooks - -### `useFlag()` - -Returns the state of a given flag for the current context. The hook provides type-safe access to flags and their configurations. +## Track usage and feedback ```tsx -import { useFlag } from "@reflag/react-sdk"; -import { Loading } from "./Loading"; - -function StartHuddleButton() { - const { - isLoading, // true while flags are being loaded - isEnabled, // boolean indicating if the flag is enabled - config: { - // flag configuration - key, // string identifier for the config variant - payload, // type-safe configuration object - }, - track, // function to track flag usage - requestFeedback, // function to request feedback for this flag - } = useFlag("huddle"); - - if (isLoading) { - return ; - } +const track = useTrack(); +await track("Started huddle", { button: "cta" }); - if (!isEnabled) { - return null; - } - - return ( - <> - - - - ); -} -``` - -#### Suspense loading - -Enable `suspense` on the provider to have `useFlag()` throw a promise while `isLoading` is true. The nearest `` boundary will render its fallback until flags are ready. - -```tsx -import { Suspense } from "react"; -import { ReflagProvider } from "@reflag/react-sdk"; +const requestFeedback = useRequestFeedback(); +requestFeedback({ flagKey: "huddles", title: "How did it go?" }); - - }> - - -; +const sendFeedback = useSendFeedback(); +await sendFeedback({ flagKey: "huddles", score: 5 }); ``` -You can also opt in for a single call with `useFlag("huddle", { suspense: true })`, or opt out inside a suspense-enabled provider with `{ suspense: false }`. +Configure your flag's adoption rules to match the event names you send. See the [Browser feedback documentation](../browser-sdk/feedback.md) to configure feedback prompts and the feedback UI. -### `useOptInFlags()` and `useSetOptIn()` +## Update context -Use these hooks to build an end-user opt-in UI for flags where opt-in is enabled in Reflag. +`useUpdateUser()`, `useUpdateCompany()` and `useUpdateOtherContext()` return functions that merge new attributes into the current context. To replace the whole context, call `useClient().setContext(context)`. Flag values are refetched for the new context. -```tsx -import { - type OptInFlag, - useIsLoading, - useOptInFlags, - useSetOptIn, -} from "@reflag/react-sdk"; - -function OptInList() { - const isProviderLoading = useIsLoading(); - const { flags, isLoading } = useOptInFlags(); - const setOptIn = useSetOptIn(); - - async function toggleOptIn(flag: OptInFlag) { - try { - const response = await setOptIn(flag.key, { - optedIn: !flag.userOptedIn, - }); - if (!response?.ok) { - console.error("Could not update opt-in"); - } - } catch (error) { - console.error("Could not update opt-in", error); - } - } +## Bootstrap from the server - if (isProviderLoading || isLoading) { - return

Loading…

; - } +To render flags immediately, without waiting for a network request, evaluate them on your server with the **Node.js SDK**: - return flags.map((flag) => ( - - )); -} +```ts +const flags = serverClient.getFlagsForBootstrap(context); ``` -By default, `useSetOptIn()` changes the opt-in for the current user, so the current context must include a `user.id`. To manage the current company's opt-in instead, pass `scope: "company"`; the context must then include a `company.id`. - -User and company opt-ins are managed independently. Setting `optedIn` to `false` removes the opt-in only for the selected scope. For example, cancelling a user's opt-in does not change the company's opt-in for the same flag. - -`setOptIn` returns a promise so you can wait for the new membership state to be synchronized. On success, it resolves after the refreshed flag state has been applied locally, the requested membership change has been confirmed, and subscribers have been notified when flags change. React may not have committed the resulting render yet. - -The promise resolves to a `Response`, or `undefined` if skipped due to invalid input, offline mode etc. Check `response?.ok` for success. - -`useOptInFlags()` returns `{ flags, isLoading }`. With `ReflagBootstrappedProvider`, it fetches opt-in metadata on first use and reports `isLoading: true` until that refresh succeeds or fails. - -If fetching opt-in metadata fails, loading ends without exposing an error. Call `client.refresh()` on the client returned by `useClient()` to retry. - -With a regular `ReflagProvider`, opt-in metadata arrives as part of the normal initial flags request, so `useOptInFlags().isLoading` remains `false`. Use the general `useIsLoading()` hook or the provider's `loadingComponent` for that initial loading state. - -`useOptInFlags()` also supports Suspense. It respects the provider-level `suspense` option, or you can enable it for only this hook with `useOptInFlags({ suspense: true })`. While required opt-in metadata is loading, the nearest `` boundary renders its fallback: +Then pass the whole result to `ReflagBootstrappedProvider`, serialized with your framework's usual mechanism: ```tsx -import { Suspense } from "react"; +import { ReflagBootstrappedProvider } from "@reflag/react-sdk"; - - }> - - + + ; ``` -Opt-in metadata Suspense is primarily relevant with `ReflagBootstrappedProvider`. Use `useOptInFlags({ suspense: false })` to opt out for one call when Suspense is enabled on the provider. +Leave secrets and server-only attributes out of the context you bootstrap, because the browser can read it. Later refreshes evaluate flags using the browser's context. If values that depend on server-only attributes must not change, set `enableLiveFlagUpdates={false}`. -### `useTrack()` - -`useTrack()` lets you send custom events to Reflag. Use this whenever a user _uses_ a feature. These events can be used to analyze feature usage in Reflag. +## Let users opt in to flags ```tsx -import { useTrack } from "@reflag/react-sdk"; - -function StartHuddle() { - const { track } = useTrack(); -
- -
; -} -``` - -### `useRequestFeedback()` - -`useRequestFeedback()` returns a function that lets you open up a dialog to ask for feedback on a specific feature. This is useful for collecting targeted feedback about specific features as part of roll out. See [Automated Feedback Surveys](https://docs.reflag.com/product-handbook/live-satisfaction) for how to do this automatically, without code. +const { flags, isLoading } = useOptInFlags(); +const setOptIn = useSetOptIn(); -When using the `useRequestFeedback` you must pass the flag key to `requestFeedback`. -The example below shows how to use `position` to ensure the popover appears next to the "Give feedback!" button. - -```tsx -import { useRequestFeedback } from "@reflag/react-sdk"; - -function FeedbackButton() { - const requestFeedback = useRequestFeedback(); - return ( - - ); -} +await setOptIn("huddles", { optedIn: true }); +await setOptIn("huddles", { optedIn: false, scope: "company" }); ``` -See the [Feedback Documentation](https://github.com/reflagcom/javascript/blob/main/packages/browser-sdk/FEEDBACK.md#manual-feedback-collection) for more information on `requestFeedback` options. - -### `useSendFeedback()` - -Returns a function that lets you send feedback to Reflag. This is useful if you've manually collected feedback through your own UI and want to send it to Reflag. - -```tsx -import { useSendFeedback } from "@reflag/react-sdk"; - -function CustomFeedbackForm() { - const sendFeedback = useSendFeedback(); - - const handleSubmit = async (data: FormData) => { - await sendFeedback({ - flagKey: "reflag-flag-key", - score: parseInt(data.get("score") as string), - comment: data.get("comment") as string, - }); - }; +Each entry includes the flag's `key`, `name`, `description` and whether the user or company has opted in. User and company opt-ins are independent. Check `isLoading` before rendering an empty state. The provider's `suspense` prop, or `useOptInFlags({ suspense: true })`, makes this hook suspend instead. See [Beta feature opt-in](https://docs.reflag.com/guides/self-opt-in) for a complete example. - return
...
; -} -``` +## Overrides and toolbar -### `useUpdateUser()`, `useUpdateCompany()` and `useUpdateOtherContext()` - -These hooks return functions that let you update the attributes for the currently set user, company, or other context. Updates to user/company are stored remotely and affect flag targeting, while "other" context updates only affect the current session. +The toolbar shows on `localhost` by default and lets you toggle Boolean flags for yourself. Use the `toolbar` prop to show it elsewhere, for example to internal users in production: ```tsx -import { - useUpdateUser, - useUpdateCompany, - useUpdateOtherContext, -} from "@reflag/react-sdk"; - -function FlagOptIn() { - const updateUser = useUpdateUser(); - const updateCompany = useUpdateCompany(); - const updateOtherContext = useUpdateOtherContext(); - - const handleUserUpdate = async () => { - await updateUser({ - role: "admin", - betaFlags: "enabled", - }); - }; - - const handleCompanyUpdate = async () => { - await updateCompany({ - plan: "enterprise", - employees: 500, - }); - }; - - const handleContextUpdate = async () => { - await updateOtherContext({ - currentWorkspace: "workspace-123", - theme: "dark", - }); - }; - - return ( -
- - - -
- ); -} -``` - -### `useClient()` - -Returns the `ReflagClient` used by the `ReflagProvider`. The client offers more functionality that -is not directly accessible thorough the other hooks. - -```tsx -import { useClient } from "@reflag/react-sdk"; - -function LoggingWrapper({ children }: { children: ReactNode }) { - const client = useClient(); - - console.log(client.getContext()); - - return children; -} + + + ``` -### `useIsLoading()` +To override a flag from code, call `useClient().setFlagOverride(key, value)`. Pass `undefined` to remove the override. -Returns the loading state of the flags in the `ReflagClient`. -Initially, the value will be `true` if no bootstrap flags have been provided and the client has not be initialized. +## Type safety -```tsx -import { useIsLoading } from "@reflag/react-sdk"; -import { Spinner } from "./Spinner"; +Declaring your flags gives you autocompletion for keys and type checks for defaults. If you created a flag with `npx reflag new`, the declarations are already generated; run `npx reflag flags types` again when your flags change. A declaration looks like this: -function LoadingWrapper({ children }: { children: ReactNode }) { - const isLoading = useIsLoading(); +```ts +import "@reflag/react-sdk"; - if (isLoading) { - return ; +declare module "@reflag/react-sdk" { + interface Flags { + huddles: boolean; + "huddle-settings": { maxParticipants: number }; } - - return children; -} -``` - -### `useOnEvent()` - -Attach a callback handler to client events to act on changes. It automatically disposes itself on unmount. - -```tsx -import { useOnEvent } from "@reflag/react-sdk"; - -function LoggingWrapper({ children }: { children: ReactNode }) { - useOnEvent("flagsUpdated", (newFlags) => { - console.log(newFlags); - }); - - return children; } ``` -## Migrating from Bucket SDK - -If you have been using the Bucket SDKs, the following list will help you migrate to Reflag SDK: - -- `Bucket*` classes, and types have been renamed to `Reflag*` (e.g. `BucketClient` is now `ReflagClient`) -- `Feature*` classes, and types have been renamed to `Flag*` (e.g. `Feature` is now `Flag`, `RawFeatures` is now `RawFlags`) -- When using strongly-typed flags, the new `Flags` interface replaced `Features` interface -- All methods that contained `feature` in the name have been renamed to use the `flag` terminology (e.g. `getFeature` is `getFlag`) -- The `fallbackFeatures` property in client constructor and configuration files has been renamed to `fallbackFlags` -- `featureKey` has been renamed to `flagKey` in all methods that accepts that argument -- The SDKs will not emit `evaluate` and `evaluate-config` events anymore -- The new cookies that are stored in the client's browser are now `reflag-*` prefixed instead of `bucket-*` -- The `featuresUpdated` hook has been renamed to `flagsUpdated` -- The `checkIsEnabled` and `checkConfig` hooks have been removed, use `check` from now on - -To ease in transition to Reflag SDK, some of the old methods have been preserved as aliases to the new methods: +Declarations are checked at compile time only. See the [Reflag CLI](https://docs.reflag.com/api/cli) for more options. -- `getFeature` method is an alias for `getFlag` -- `getFeatures` method is an alias for `getFlags` -- `useFeature` method is an alias for `useFlag` -- `featuresUpdated` hook is an alias for `flagsUpdated` +## Use an existing client -If you are running with strict Content Security Policies active on your website, you will need change them as follows: +`useClient()` returns the underlying Browser SDK client. If you already create a Browser SDK client yourself, pass it to ``; your application is then responsible for initializing and stopping it. -- `connect-src https://front.bucket.co` to `connect-src https://front.reflag.com` +## Events -## Content Security Policy (CSP) +`useOnEvent(type, handler)` subscribes to [client events](../browser-sdk/README.md) and unsubscribes when the component unmounts. -See [CSP](https://github.com/reflagcom/javascript/blob/main/packages/browser-sdk/README.md#content-security-policy-csp) for info on using Reflag React SDK with CSP +## Configuration -## License +The provider accepts the Browser SDK's configuration options, such as `fallbackFlags`, `enableTracking`, `offline`, `feedback` and `logger`, as props. Live updates are on by default in React; set `enableLiveFlagUpdates={false}` to turn them off. Set `debug` to log to the console. -MIT License +For Content Security Policy requirements and the full list of options, see the [Browser SDK](../browser-sdk/README.md). -Copyright (c) 2025 Bucket ApS +Using v1? [Legacy docs](../../legacy/v1/react-sdk/README.md) · [Upgrade guide](../migrating-from-v1.md). diff --git a/supported-languages/react-sdk/globals.md b/supported-languages/react-sdk/globals.md index 625b4b7..859fa6a 100644 --- a/supported-languages/react-sdk/globals.md +++ b/supported-languages/react-sdk/globals.md @@ -1,140 +1,299 @@ --- +layout: + visible: true title: visible: true +description: + visible: false tableOfContents: visible: true outline: visible: true pagination: visible: true -layout: - width: default - title: - visible: true - description: - visible: true - tableOfContents: - visible: true - outline: - visible: true - pagination: - visible: true - metadata: - visible: true - tags: - visible: true - actions: - visible: true - anchors: - visible: true --- -# Reference +# @reflag/react-sdk + +This page covers SDK v2. + +## Interfaces + +### CheckEvent + +A root read records selection identity, never its JSON payload. + +#### Properties + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyType
+ + `action` + + + +`"check"` + +
+ + `evalContext?` + + + +[`ReflagContext`](../browser-sdk/globals.md#reflagcontext) + +
+ + `evalErrors?` + + + +[`EvaluationError`](../browser-sdk/globals.md#evaluationerror)[] + +
+ + `evalMissingFields?` + + + +`string`[] + +
+ + `evalResult?` + + + +`string` + +
+ + `evalRuleResults?` -## Interfaces + -### CheckEvent +`boolean`[] -Event representing checking the flag evaluation result +
-#### Properties + `flagStateVersion?` -| Property | Type | Description | -| --------------------------- | -------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `action` | `"check-is-enabled"` \| `"check-config"` | `check-is-enabled` means `isEnabled` was checked, `check-config` means `config` was checked. | -| `evaluationErrors?` | { `code`: `string`; `field`: `string`; `message`: `string`; `operator`: `string`; }\[] | Non-fatal diagnostics produced while evaluating the flag. | -| `key` | `string` | Flag key. | -| ~~`missingContextFields?`~~ | `string`\[] |

Missing context fields.

Deprecated

Use evaluationErrors and check for MISSING_CONTEXT_FIELD.

| -| `ruleEvaluationResults?` | `boolean`\[] | Rule evaluation results. | -| `value?` | \| `boolean` \| { `key`: `string`; `payload`: `any`; } | Result of flag or configuration evaluation. If `action` is `check-is-enabled`, this is the result of the flag evaluation and `value` is a boolean. If `action` is `check-config`, this is the result of the configuration evaluation. | -| `version?` | `number` | Version of targeting rules. | +
+ +`number` + +
+ + `key` + + + +`string` + +
+ + `sourceVersionId?` + + + +`string` + +
*** -### CompanyContext +### CompanyContext -Context is a set of key-value pairs. This is used to determine if feature targeting matches and to track events. Id should always be present so that it can be referenced to an existing company. +Context is a set of key-value pairs. +This is used to determine if feature targeting matches and to track events. +Id should always be present so that it can be referenced to an existing company. -#### Indexable +#### Indexable ```ts [key: string]: ContextValue ``` -#### Properties +#### Properties -| Property | Type | Description | -| -------- | ----------------------------------- | ------------ | -| `id` | `undefined` \| `string` \| `number` | Company id | -| `name?` | `string` | Company name | - -*** + + + + + + + + + + + + + + + + + + + + +
PropertyTypeDescription
-### Flag\ + `id` -Describes a feature + -#### Type Parameters +`undefined` \| `string` \| `number` -| Type Parameter | Default type | -| ------------------------------------------------------------------ | ----------------------------------------------------------- | -| `TConfig` _extends_ [`FlagType`](globals.md#flagtype)\[`"config"`] | [`EmptyFlagRemoteConfig`](globals.md#emptyflagremoteconfig) | + -#### Properties +Company id -| Property | Type | Description | -| ----------------- | -------------------------------------------------------------------------------------------------- | ------------------------------- | -| `config` | \| [`EmptyFlagRemoteConfig`](globals.md#emptyflagremoteconfig) \| { `key`: `string`; } & `TConfig` | ‐ | -| `isEnabled` | `boolean` | If the feature is enabled. | -| `isLoading` | `boolean` | If the feature is loading. | -| `key` | `string` | The key of the feature. | -| `requestFeedback` | (`opts`: [`RequestFeedbackOptions`](globals.md#requestfeedbackoptions)) => `void` | Request feedback from the user. | +
-#### Methods + `name?` -**track()** + -```ts -track(): - | undefined - | Promise< - | undefined -| Response> -``` +`string` -Track feature usage in Reflag. + -**Returns** +Company name -\| `undefined` | [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)< | `undefined` | [`Response`](https://developer.mozilla.org/docs/Web/API/Response)> +
*** -### Flags +### Flags + +Optional key/value registration; singular reads infer their type from defaults. *** -### UserContext +### UserContext -Context is a set of key-value pairs. This is used to determine if feature targeting matches and to track events. Id should always be present so that it can be referenced to an existing user. +Context is a set of key-value pairs. +This is used to determine if feature targeting matches and to track events. +Id should always be present so that it can be referenced to an existing user. -#### Indexable +#### Indexable ```ts [key: string]: ContextValue ``` -#### Properties +#### Properties + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyTypeDescription
+ + `email?` + + + +`string` + + + +User email + +
+ + `id` + + + +`undefined` \| `string` \| `number` + + + +User id -| Property | Type | Description | -| -------- | ----------------------------------- | ----------- | -| `email?` | `string` | User email | -| `id` | `undefined` \| `string` \| `number` | User id | -| `name?` | `string` | User name | +
-## Type Aliases + `name?` -### BootstrappedFlags + + +`string` + + + +User name + +
+ +## Type Aliases + +### BootstrappedFlags ```ts type BootstrappedFlags = BootstrappedState & { @@ -142,86 +301,99 @@ type BootstrappedFlags = BootstrappedState & { }; ``` -#### Type declaration +#### Type declaration -| Name | Type | -| ------- | ------------------------------------------------ | -| `flags` | [`RawFlags`](../browser-sdk/globals.md#rawflags) | + + + + + + + + + + + + + +
NameType
-*** +`flags` -### EmptyFlagRemoteConfig + -```ts -type EmptyFlagRemoteConfig = { - key: undefined; - payload: undefined; -}; -``` +[`RawFlags`](../browser-sdk/globals.md#rawflags) -#### Type declaration - -| Name | Type | -| --------- | ----------- | -| `key` | `undefined` | -| `payload` | `undefined` | +
*** -### FlagKey +### FlagDefaultValue ```ts -type FlagKey = keyof TypedFlags; +type FlagDefaultValue = + | null + | boolean + | number + | string + | readonly FlagDefaultValue[] +| {}; ``` *** -### FlagRemoteConfig +### FlagKey ```ts -type FlagRemoteConfig = - | { - key: string; - payload: any; - } - | EmptyFlagRemoteConfig; +type FlagKey = keyof Flags extends never ? string : Extract; ``` -A remotely managed configuration value for a feature. - -#### Type declaration - -{ `key`: `string`; `payload`: `any`; } +*** -| Name | Type | Description | -| --------- | -------- | ------------------------------------------- | -| `key` | `string` | The key of the matched configuration value. | -| `payload` | `any` | The optional user-supplied payload data. | +### FlagValue -[`EmptyFlagRemoteConfig`](globals.md#emptyflagremoteconfig) +```ts +type FlagValue = + | null + | boolean + | number + | string + | FlagValue[] +| {}; +``` *** -### FlagType +### FlagValueFromDefault\ ```ts -type FlagType = { - config: { - payload: any; - }; -}; +type FlagValueFromDefault = T extends null ? FlagValue : T extends boolean ? boolean : T extends number ? number : T extends string ? string : T extends readonly infer Element[] ? [Element] extends [never] ? FlagValue[] : FlagValueFromDefault[] : T extends object ? { -readonly [Key in keyof T]: FlagValueFromDefault } : never; ``` -#### Type declaration +Widen literals and return mutable copies. Null requests arbitrary JSON. -| Name | Type | -| ---------------- | --------------------- | -| `config`? | { `payload`: `any`; } | -| `config.payload` | `any` | +#### Type Parameters + + + + + + + + + + + + +
Type Parameter
+ +`T` + +
*** -### OptInFlag +### OptInFlag ```ts type OptInFlag = Omit & { @@ -231,27 +403,44 @@ type OptInFlag = Omit & { An opt-in-enabled flag for the generated React SDK flag definitions. -Includes all fields from [BrowserOptInFlag](../browser-sdk/globals.md#optinflag): `name`, `description`, `isEnabled`, `userOptedIn`, `companyOptedIn`, and `isOptedIn`. Only `key` is narrowed to the generated [FlagKey](globals.md#flagkey) type. +#### Type declaration + + + + + + + + + + + + + + +
NameType
-#### Type declaration +`key` -| Name | Type | -| ----- | ------------------------------- | -| `key` | [`FlagKey`](globals.md#flagkey) | + + +[`FlagKey`](globals.md#flagkey) + +
*** -### RawFlags +### RawFlags ```ts -type RawFlags = Record; +type RawFlags = RawFlags; ``` Describes a collection of evaluated raw flags. *** -### ReflagBootstrappedProps +### ReflagBootstrappedProps ```ts type ReflagBootstrappedProps = ReflagPropsBase & ReflagInitOptionsBase & { @@ -261,15 +450,41 @@ type ReflagBootstrappedProps = ReflagPropsBase & ReflagInitOptionsBase & { Props for the ReflagBootstrappedProvider. -#### Type declaration +#### Type declaration + + + + + + + + + + + + + + + + +
NameTypeDescription
+ +`flags` + + + +[`BootstrappedFlags`](globals.md#bootstrappedflags) + + -| Name | Type | Description | -| ------- | --------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ | -| `flags` | [`BootstrappedFlags`](globals.md#bootstrappedflags) | Pre-fetched flags used for the initial render. The browser client fetches opt-in metadata on demand when opt-in flags are requested. | +Pre-fetched flags used for the initial render. The browser client fetches opt-in +metadata on demand when opt-in flags are requested. + +
*** -### ReflagClientProviderProps +### ReflagClientProviderProps ```ts type ReflagClientProviderProps = Omit & { @@ -279,18 +494,37 @@ type ReflagClientProviderProps = Omit & { Props for the ReflagClientProvider. -#### Type declaration +#### Type declaration + + + + + + + + + + + + + + +
NameType
+ +`client` + + -| Name | Type | -| -------- | -------------------------------------------------------- | -| `client` | [`ReflagClient`](../browser-sdk/globals.md#reflagclient) | +[`ReflagClient`](../browser-sdk/globals.md#reflagclient) + +
*** -### ReflagInitOptionsBase +### ReflagInitOptionsBase ```ts -type ReflagInitOptionsBase = Omit ```ts type ReflagProps = ReflagPropsBase & ReflagInitOptionsBase & { @@ -319,18 +553,105 @@ type ReflagProps = ReflagPropsBase & ReflagInitOptionsBase & { Props for the ReflagProvider. -#### Type declaration +#### Type declaration + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameTypeDescription
+ +`company`? + + + +[`CompanyContext`](globals.md#companycontext) + + + +Company related context. If you provide `id` Reflag will enrich the evaluation context with +company attributes on Reflag servers. + +**Deprecated** + +Use `context` instead, this property will be removed in the next major version + +
+ +`context`? + + + +[`ReflagContext`](../browser-sdk/globals.md#reflagcontext) + + + +The context to use for the ReflagClient containing user, company, and other context. + +
+ +`otherContext`? + + + +[`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, `string` \| `number` \| `undefined`\> + + + +Context which is not related to a user or a company. + +**Deprecated** + +Use `context` instead, this property will be removed in the next major version + +
-| Name | Type | Description | -| --------------- | ------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `company`? | [`CompanyContext`](globals.md#companycontext) |

Company related context. If you provide id Reflag will enrich the evaluation context with company attributes on Reflag servers.

Deprecated

Use context instead, this property will be removed in the next major version

| -| `context`? | [`ReflagContext`](../browser-sdk/globals.md#reflagcontext) | The context to use for the ReflagClient containing user, company, and other context. | -| `otherContext`? | [`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)<`string`, `string` \| `number` \| `undefined`> |

Context which is not related to a user or a company.

Deprecated

Use context instead, this property will be removed in the next major version

| -| `user`? | [`UserContext`](globals.md#usercontext) |

User related context. If you provide id Reflag will enrich the evaluation context with user attributes on Reflag servers.

Deprecated

Use context instead, this property will be removed in the next major version

| +`user`? + +
+ +[`UserContext`](globals.md#usercontext) + + + +User related context. If you provide `id` Reflag will enrich the evaluation context with +user attributes on Reflag servers. + +**Deprecated** + +Use `context` instead, this property will be removed in the next major version + +
*** -### ReflagPropsBase +### ReflagPropsBase ```ts type ReflagPropsBase = { @@ -347,20 +668,128 @@ type ReflagPropsBase = { Base props for the ReflagProvider and ReflagBootstrappedProvider. -#### Type declaration +#### Type declaration + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameTypeDescription
+ + `children`? + + + +`ReactNode` + + + +The children to render after the client is initialized. + +
+ + `debug`? + + + +`boolean` + + + +Set to `true` to enable debug logging to the console, + +
+ + `initialLoading`? + + + +`boolean` + + + +Set to `true` to show the loading component while the client is initializing. + +
+ + `loadingComponent`? + + -| Name | Type | Description | -| ------------------- | ---------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `children`? | `ReactNode` | The children to render after the client is initialized. | -| `debug`? | `boolean` | Set to `true` to enable debug logging to the console, | -| `initialLoading`? | `boolean` | Set to `true` to show the loading component while the client is initializing. | -| `loadingComponent`? | `ReactNode` | A React component to show while the client is initializing. | -| `logger`? | [`Logger`](../browser-sdk/globals.md#logger-1) | A custom logger to use for SDK logs. Use this for advanced control or filtering of SDK logs. If both `logger` and `debug` are provided, `logger` takes precedence. | -| `suspense`? | `boolean` | Set to `true` to make `useFlag` and `useOptInFlags` suspend while their required flag data is loading. Components that call either hook must be wrapped in a React `` boundary. | +`ReactNode` + + + +A React component to show while the client is initializing. + +
+ + `logger`? + + + +[`Logger`](../browser-sdk/globals.md#logger) + + + +A custom logger to use for SDK logs. +Use this for advanced control or filtering of SDK logs. +If both `logger` and `debug` are provided, `logger` takes precedence. + +
+ + `suspense`? + + + +`boolean` + + + +Set to `true` to make `useOptInFlags` suspend while its metadata loads. +Use `useFlagSuspense` for suspending direct-value reads. + +
*** -### RequestFeedbackOptions +### RequestFeedbackOptions ```ts type RequestFeedbackOptions = Omit; @@ -368,7 +797,7 @@ type RequestFeedbackOptions = Omit *** -### SetOptInOptions +### SetOptInOptions ```ts type SetOptInOptions = { @@ -377,18 +806,59 @@ type SetOptInOptions = { }; ``` -Options for changing the current user or company's opt-in membership. +Represents a flag. + +#### Type declaration + + + + + + + + + + + + + + + + + + + + + +
NameTypeDescription
+ + `optedIn` + + + +`boolean` + + -#### Type declaration +Whether the scoped subject has opted in. -| Name | Type | Description | -| --------- | ----------------------- | -------------------------------------------------------------------------- | -| `optedIn` | `boolean` | Whether the scoped subject has opted in. | -| `scope`? | `"user"` \| `"company"` | Whether to update the current user or current company. Defaults to `user`. | +
+ + `scope`? + + + +`"user"` \| `"company"` + + + +Whether to update the current user or current company. Defaults to `user`. + +
*** -### StorageAdapter +### StorageAdapter ```ts type StorageAdapter = { @@ -398,17 +868,58 @@ type StorageAdapter = { }; ``` -#### Type declaration +#### Type declaration + + + + + + + + + + + + + + + + + + + + + + +
NameType
-| Name | Type | -| --------------- | ------------------------------------------------------------------------------------------------------------------- | -| `getItem()` | [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<`null` \| `string`> | -| `removeItem()`? | [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<`void`> | -| `setItem()` | [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<`void`> | + `getItem()` + + + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`null` \| `string`\> + +
+ + `removeItem()`? + + + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> + +
+ + `setItem()` + + + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> + +
*** -### TrackEvent +### TrackEvent ```ts type TrackEvent = { @@ -420,48 +931,79 @@ type TrackEvent = { }; ``` -#### Type declaration +#### Type declaration -| Name | Type | -| ------------- | ------------------------------------------------------------------------------------------------------------------------- | -| `attributes`? | \| [`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)<`string`, `any`> \| `null` | -| `company`? | [`CompanyContext`](globals.md#companycontext) | -| `eventName` | `string` | -| `user` | [`UserContext`](globals.md#usercontext) | + + + + + + + + + + + + + + + + + + + + + + + + + +
NameType
-*** + `attributes`? -### TypedFlags + -```ts -type TypedFlags = keyof Flags extends never ? Record : { [TypedFlagKey in keyof Flags]: Flags[TypedFlagKey] extends FlagType ? Flag : Flag }; -``` + \| [`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, `any`\> + \| `null` + +
-Describes a collection of evaluated feature. + `company`? -#### Remarks + -This types falls back to a generic Record\ if the Flags interface has not been extended. +[`CompanyContext`](globals.md#companycontext) + +
+ + `eventName` + + + +`string` + +
+ + `user` + + + +[`UserContext`](globals.md#usercontext) + +
*** -### UseFlagOptions +### TypedFlags ```ts -type UseFlagOptions = { - suspense: boolean; -}; +type TypedFlags = keyof Flags extends never ? Record : { [Key in keyof Flags]: Flags[Key] | undefined }; ``` -#### Type declaration - -| Name | Type | Description | -| ----------- | --------- | ------------------------------------------------------------------------------------------------------------------------------ | -| `suspense`? | `boolean` | Override the provider suspense setting for this `useFlag` call. When true, `useFlag` throws a promise while flags are loading. | - *** -### UseOptInFlagsOptions +### UseOptInFlagsOptions ```ts type UseOptInFlagsOptions = { @@ -469,15 +1011,41 @@ type UseOptInFlagsOptions = { }; ``` -#### Type declaration +#### Type declaration + + + + + + + + + + + + + + + + +
NameTypeDescription
+ + `suspense`? -| Name | Type | Description | -| ----------- | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | -| `suspense`? | `boolean` | Override the provider suspense setting for this `useOptInFlags` call. When true, `useOptInFlags` throws a promise while opt-in flags are loading. | + + +`boolean` + + + +Override the provider suspense setting for this `useOptInFlags` call. +When true, `useOptInFlags` throws a promise while opt-in flags are loading. + +
*** -### UseOptInFlagsResult +### UseOptInFlagsResult ```ts type UseOptInFlagsResult = { @@ -486,16 +1054,57 @@ type UseOptInFlagsResult = { }; ``` -#### Type declaration +#### Type declaration + + + + + + + + + + + + + + + + + + + + + +
NameTypeDescription
+ + `flags` + + -| Name | Type | Description | -| ----------- | -------------------------------------- | ------------------------------------------------------------ | -| `flags` | [`OptInFlag`](globals.md#optinflag)\[] | Opt-in-enabled flags for the current context. | -| `isLoading` | `boolean` | Whether a bootstrapped provider is fetching opt-in metadata. | +[`OptInFlag`](globals.md#optinflag)[] + + + +Opt-in-enabled flags for the current context. + +
+ + `isLoading` + + + +`boolean` -## Functions + -### ReflagBootstrappedProvider() +Whether a bootstrapped provider is fetching opt-in metadata. + +
+ +## Functions + +### ReflagBootstrappedProvider() ```ts function ReflagBootstrappedProvider(__namedParameters: ReflagBootstrappedProps): Element @@ -503,37 +1112,75 @@ function ReflagBootstrappedProvider(__namedParameters: ReflagBootstrappedProps): Bootstrapped Provider for the ReflagClient using pre-fetched flags. -#### Parameters +#### Parameters + + + + + + + + + + + + + + +
ParameterType
+ +`__namedParameters` + + + +[`ReflagBootstrappedProps`](globals.md#reflagbootstrappedprops) -| Parameter | Type | -| ------------------- | --------------------------------------------------------------- | -| `__namedParameters` | [`ReflagBootstrappedProps`](globals.md#reflagbootstrappedprops) | +
-#### Returns +#### Returns `Element` *** -### ReflagClientProvider() +### ReflagClientProvider() ```ts function ReflagClientProvider(__namedParameters: ReflagClientProviderProps): Element ``` -#### Parameters +#### Parameters -| Parameter | Type | -| ------------------- | ------------------------------------------------------------------- | -| `__namedParameters` | [`ReflagClientProviderProps`](globals.md#reflagclientproviderprops) | + + + + + + + + + + + + + +
ParameterType
-#### Returns +`__namedParameters` + + + +[`ReflagClientProviderProps`](globals.md#reflagclientproviderprops) + +
+ +#### Returns `Element` *** -### ReflagProvider() +### ReflagProvider() ```ts function ReflagProvider(__namedParameters: ReflagProps): Element @@ -541,19 +1188,38 @@ function ReflagProvider(__namedParameters: ReflagProps): Element Provider for the ReflagClient. -#### Parameters +#### Parameters + + + + + + + + + + + + + + +
ParameterType
+ +`__namedParameters` + + -| Parameter | Type | -| ------------------- | --------------------------------------- | -| `__namedParameters` | [`ReflagProps`](globals.md#reflagprops) | +[`ReflagProps`](globals.md#reflagprops) -#### Returns +
+ +#### Returns `Element` *** -### useClient() +### useClient() ```ts function useClient(): ReflagClient @@ -563,13 +1229,13 @@ Returns the current `ReflagClient` used by the `ReflagProvider`. This is useful if you need to access the `ReflagClient` outside of the `ReflagProvider`. -#### Returns +#### Returns [`ReflagClient`](../browser-sdk/globals.md#reflagclient) The `ReflagClient`. -#### Example +#### Example ```ts import { useClient } from '@reflag/react-sdk'; @@ -582,85 +1248,627 @@ function App() { *** -### ~~useFeature()~~ +### ~~useFeature()~~ + +#### Deprecated + +Use useFlag. + +#### Call Signature + +```ts +function useFeature(key: string, defaultValue?: undefined): boolean +``` + +Boolean-first, non-suspending reads. Supply a positional default for JSON values. + +### Parameters + + + + + + + + + + + + + + + + + + +
ParameterType
+ +`key` + + + +`string` + +
+ +`defaultValue`? + + + +`undefined` + +
+ +### Returns + +`boolean` + +### Deprecated + +Use useFlag. + +#### Call Signature + +```ts +function useFeature(key: Key, defaultValue: Default): FlagValueFromDefault +``` + +Boolean-first, non-suspending reads. Supply a positional default for JSON values. + +### Type Parameters + + + + + + + + + + + + + + + +
Type Parameter
+ +`Key` *extends* `string` + +
+ +`Default` *extends* `object` \| [`FlagDefaultValue`](globals.md#flagdefaultvalue) + +
+ +### Parameters + + + + + + + + + + + + + + + + + + +
ParameterType
+ +`key` + + + +`Key` + +
+ +`defaultValue` + + + +`Default` + +
+ +### Returns + +[`FlagValueFromDefault`](globals.md#flagvaluefromdefaultt)\<`Default`\> + +### Deprecated + +Use useFlag. + +#### Call Signature ```ts -function useFeature(key: TKey, options?: UseFlagOptions): Flag +function useFeature(key: string, defaultValue: Default): FlagValueFromDefault ``` -#### Type Parameters +Boolean-first, non-suspending reads. Supply a positional default for JSON values. + +### Type Parameters + + + + + + + + + + + + +
Type Parameter
+ +`Default` *extends* `object` \| [`FlagDefaultValue`](globals.md#flagdefaultvalue) + +
+ +### Parameters + + + + + + + + + + + + + + + + + + +
ParameterType
+ +`key` + + + +`string` + +
+ +`defaultValue` -| Type Parameter | -| ------------------------- | -| `TKey` _extends_ `string` | + -#### Parameters +`Default` -| Parameter | Type | -| ---------- | --------------------------------------------- | -| `key` | `TKey` | -| `options`? | [`UseFlagOptions`](globals.md#useflagoptions) | +
-#### Returns +### Returns -[`Flag`](globals.md#flagtconfig) +[`FlagValueFromDefault`](globals.md#flagvaluefromdefaultt)\<`Default`\> -#### Deprecated +### Deprecated -use `useFlag` instead +Use useFlag. *** -### useFlag() +### useFlag() + +#### Call Signature ```ts -function useFlag(key: TKey, options: UseFlagOptions): TypedFlags[TKey] +function useFlag(key: string, defaultValue?: undefined): boolean ``` -Returns the state of a given feature for the current context, e.g. +Boolean-first, non-suspending reads. Supply a positional default for JSON values. + +### Parameters + + + + + + + + + + + + + + + + + + +
ParameterType
+ +`key` + + + +`string` + +
+ +`defaultValue`? + + + +`undefined` + +
+ +### Returns + +`boolean` + +#### Call Signature ```ts -function HuddleButton() { - const {isEnabled, config: { payload }, track} = useFlag("huddle"); - if (isEnabled) { - return ; -} +function useFlag(key: Key, defaultValue: Default): FlagValueFromDefault ``` -#### Type Parameters +Boolean-first, non-suspending reads. Supply a positional default for JSON values. + +### Type Parameters + + + + + + + + + + + + + + + +
Type Parameter
+ +`Key` *extends* `string` + +
+ +`Default` *extends* `object` \| [`FlagDefaultValue`](globals.md#flagdefaultvalue) + +
+ +### Parameters + + + + + + + + + + + + + + + + + + +
ParameterType
+ +`key` + + + +`Key` + +
+ +`defaultValue` + + -| Type Parameter | -| ------------------------- | -| `TKey` _extends_ `string` | +`Default` -#### Parameters +
-| Parameter | Type | -| --------- | --------------------------------------------- | -| `key` | `TKey` | -| `options` | [`UseFlagOptions`](globals.md#useflagoptions) | +### Returns -#### Returns +[`FlagValueFromDefault`](globals.md#flagvaluefromdefaultt)\<`Default`\> -[`TypedFlags`](globals.md#typedflags)\[`TKey`] +#### Call Signature + +```ts +function useFlag(key: string, defaultValue: Default): FlagValueFromDefault +``` + +Boolean-first, non-suspending reads. Supply a positional default for JSON values. + +### Type Parameters + + + + + + + + + + + + +
Type Parameter
+ +`Default` *extends* `object` \| [`FlagDefaultValue`](globals.md#flagdefaultvalue) + +
+ +### Parameters + + + + + + + + + + + + + + + + + + +
ParameterType
+ +`key` + + + +`string` + +
+ +`defaultValue` + + + +`Default` + +
+ +### Returns + +[`FlagValueFromDefault`](globals.md#flagvaluefromdefaultt)\<`Default`\> *** -### useIsLoading() +### useFlagSuspense() + +#### Call Signature + +```ts +function useFlagSuspense(key: string, defaultValue?: undefined): boolean +``` + +Wait for initialization, then read once. Missing flags use the default, not an endless suspension. + +### Parameters + + + + + + + + + + + + + + + + + + +
ParameterType
+ +`key` + + + +`string` + +
+ +`defaultValue`? + + + +`undefined` + +
+ +### Returns + +`boolean` + +#### Call Signature + +```ts +function useFlagSuspense(key: Key, defaultValue: Default): FlagValueFromDefault +``` + +Wait for initialization, then read once. Missing flags use the default, not an endless suspension. + +### Type Parameters + + + + + + + + + + + + + + + +
Type Parameter
+ +`Key` *extends* `string` + +
+ +`Default` *extends* `object` \| [`FlagDefaultValue`](globals.md#flagdefaultvalue) + +
+ +### Parameters + + + + + + + + + + + + + + + + + + +
ParameterType
+ +`key` + + + +`Key` + +
+ +`defaultValue` + + + +`Default` + +
+ +### Returns + +[`FlagValueFromDefault`](globals.md#flagvaluefromdefaultt)\<`Default`\> + +#### Call Signature + +```ts +function useFlagSuspense(key: string, defaultValue: Default): FlagValueFromDefault +``` + +Wait for initialization, then read once. Missing flags use the default, not an endless suspension. + +### Type Parameters + + + + + + + + + + + + +
Type Parameter
+ +`Default` *extends* `object` \| [`FlagDefaultValue`](globals.md#flagdefaultvalue) + +
+ +### Parameters + + + + + + + + + + + + + + + + + + +
ParameterType
+ +`key` + + + +`string` + +
+ +`defaultValue` + + + +`Default` + +
+ +### Returns + +[`FlagValueFromDefault`](globals.md#flagvaluefromdefaultt)\<`Default`\> + +*** + +### useIsLoading() ```ts function useIsLoading(): boolean ``` -Returns a boolean indicating if the Reflag client is loading. You can use this to check if the Reflag client is loading at any point in your application. Initially, the value will be true until the client is initialized. +Returns a boolean indicating if the Reflag client is loading. +You can use this to check if the Reflag client is loading at any point in your application. +Initially, the value will be true until the client is initialized. -#### Returns +#### Returns `boolean` A boolean indicating if the Reflag client is loading. -#### Example +#### Example ```ts import { useIsLoading } from '@reflag/react-sdk'; @@ -672,36 +1880,106 @@ console.log(isLoading); *** -### useOnEvent() +### useOnEvent() ```ts function useOnEvent( - event: THookType, - handler: (arg0: HookArgs[THookType]) => void, + event: THookType, + handler: (arg0: HookArgs[THookType]) => void, client?: ReflagClient): void ``` Attach a callback handler to client events to act on changes. It automatically disposes itself on unmount. -#### Type Parameters +#### Type Parameters + + + + + + + + + + + + +
Type Parameter
+ +`THookType` *extends* keyof [`HookArgs`](../browser-sdk/globals.md#hookargs) + +
-| Type Parameter | -| ---------------------------------------------------------------------------- | -| `THookType` _extends_ keyof [`HookArgs`](../browser-sdk/globals.md#hookargs) | +#### Parameters -#### Parameters + + + + + + + + + + + + + + + + + + + + + + + + + +
ParameterTypeDescription
-| Parameter | Type | Description | -| --------- | ---------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | -| `event` | `THookType` | The event to listen to. | -| `handler` | (`arg0`: [`HookArgs`](../browser-sdk/globals.md#hookargs)\[`THookType`]) => `void` | The function to call when the event is triggered. | -| `client`? | [`ReflagClient`](../browser-sdk/globals.md#reflagclient) | The Reflag client to listen to. If not provided, the client will be retrieved from the context. | +`event` -#### Returns + + +`THookType` + + + +The event to listen to. + +
+ +`handler` + + + +(`arg0`: [`HookArgs`](../browser-sdk/globals.md#hookargs)\[`THookType`\]) => `void` + + + +The function to call when the event is triggered. + +
+ +`client`? + + + +[`ReflagClient`](../browser-sdk/globals.md#reflagclient) + + + +The Reflag client to listen to. If not provided, the client will be retrieved from the context. + +
+ +#### Returns `void` -#### Example +#### Example ```ts import { useOnEvent } from '@reflag/react-sdk'; @@ -713,7 +1991,7 @@ useOnEvent("flagsUpdated", () => { *** -### useOptInFlags() +### useOptInFlags() ```ts function useOptInFlags(options: UseOptInFlagsOptions): UseOptInFlagsResult @@ -721,29 +1999,51 @@ function useOptInFlags(options: UseOptInFlagsOptions): UseOptInFlagsResult Returns opt-in-enabled flags and their loading state for the current context. -The loading state is only used with `ReflagBootstrappedProvider` while opt-in metadata is fetched on demand. Regular providers load opt-in metadata with the initial flags; use [useIsLoading](globals.md#useisloading) for their loading state. When suspense is enabled for the provider or this hook, it suspends instead of returning a loading result. A Suspense boundary alone does not enable it. +The loading state is only used with `ReflagBootstrappedProvider` while +opt-in metadata is fetched on demand. Regular providers load opt-in metadata +with the initial flags. +When suspense is enabled for the provider or this hook, it suspends instead +of returning a loading result. + +#### Parameters -If fetching opt-in metadata fails, loading ends without exposing an error. Call `refresh()` on the client returned by [useClient](globals.md#useclient) to retry. + + + + + + + + + + + + + +
ParameterType
-#### Parameters +`options` -| Parameter | Type | -| --------- | --------------------------------------------------------- | -| `options` | [`UseOptInFlagsOptions`](globals.md#useoptinflagsoptions) | + -#### Returns +[`UseOptInFlagsOptions`](globals.md#useoptinflagsoptions) + +
+ +#### Returns [`UseOptInFlagsResult`](globals.md#useoptinflagsresult) *** -### useRequestFeedback() +### useRequestFeedback() ```ts function useRequestFeedback(): (options: RequestFeedbackData) => void ``` -Returns a function to open up the feedback form Note: When calling `useRequestFeedback`, user/company must already be set. +Returns a function to open up the feedback form +Note: When calling `useRequestFeedback`, user/company must already be set. See [link](../browser-sdk/feedback.md) for more information @@ -755,23 +2055,42 @@ reflag.requestFeedback({ }); ``` -#### Returns +#### Returns `Function` -**Parameters** +### Parameters + + + + + + + + + + + + + + +
ParameterType
+ +`options` -| Parameter | Type | -| --------- | ---------------------------------------------------------------------- | -| `options` | [`RequestFeedbackData`](../browser-sdk/globals.md#requestfeedbackdata) | + -**Returns** +[`RequestFeedbackData`](../browser-sdk/globals.md#requestfeedbackdata) + +
+ +### Returns `void` *** -### useSendFeedback() +### useSendFeedback() ```ts function useSendFeedback(): (opts: UnassignedFeedback) => Promise< @@ -779,7 +2098,8 @@ function useSendFeedback(): (opts: UnassignedFeedback) => Promise< | Response> ``` -Returns a function to manually send feedback collected from a user. Note: When calling `useSendFeedback`, user/company must already be set. +Returns a function to manually send feedback collected from a user. +Note: When calling `useSendFeedback`, user/company must already be set. See [link](../browser-sdk/feedback.md) for more information @@ -793,23 +2113,44 @@ sendFeedback({ }); ``` -#### Returns +#### Returns `Function` -**Parameters** +### Parameters + + + + + + + + + + + + + + +
ParameterType
+ +`opts` -| Parameter | Type | -| --------- | -------------------------------------------------------------------- | -| `opts` | [`UnassignedFeedback`](../browser-sdk/globals.md#unassignedfeedback) | + -**Returns** +[`UnassignedFeedback`](../browser-sdk/globals.md#unassignedfeedback) -[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)< | `undefined` | [`Response`](https://developer.mozilla.org/docs/Web/API/Response)> +
+ +### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\< + \| `undefined` + \| [`Response`](https://developer.mozilla.org/docs/Web/API/Response)\> *** -### useSetOptIn() +### useSetOptIn() ```ts function useSetOptIn(): (key: string, options: SetOptInOptions) => Promise< @@ -819,99 +2160,187 @@ function useSetOptIn(): (key: string, options: SetOptInOptions) => Promise< Returns a function to set whether the current user or company has opted into a flag. -Check the returned Response's `ok` property and catch promise rejections. HTTP failures return a non-OK Response; offline mode, invalid arguments, or missing scoped context return undefined. Confirmation failures can reject after the membership changed remotely. See [ReflagClient.setOptIn](../browser-sdk/globals.md#setoptin). - -#### Returns +#### Returns `Function` -**Parameters** +### Parameters -| Parameter | Type | -| --------- | ----------------------------------------------- | -| `key` | `string` | -| `options` | [`SetOptInOptions`](globals.md#setoptinoptions) | + + + + + + + + + + + + + + + + + +
ParameterType
-**Returns** +`key` -[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)< | `undefined` | [`Response`](https://developer.mozilla.org/docs/Web/API/Response)> + + +`string` + +
+ +`options` + + + +[`SetOptInOptions`](globals.md#setoptinoptions) + +
+ +### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\< + \| `undefined` + \| [`Response`](https://developer.mozilla.org/docs/Web/API/Response)\> *** -### useTrack() +### useTrack() ```ts -function useTrack(): (eventName: string, attributes?: +function useTrack(): (eventName: string, attributes?: | null | Record) => Promise< | undefined | Response> ``` -Returns a function to send an event when a user performs an action Note: When calling `useTrack`, user/company must already be set. +Returns a function to send an event when a user performs an action +Note: When calling `useTrack`, user/company must already be set. ```ts const track = useTrack(); track("Started Huddle", { button: "cta" }); ``` -#### Returns +#### Returns `Function` -**Parameters** +### Parameters + + + + + + + + + + + + + + + + + + +
ParameterType
+ +`eventName` + + + +`string` + +
+ +`attributes`? + + -| Parameter | Type | -| ------------- | ------------------------------------------------------------------------------------------------------------------------- | -| `eventName` | `string` | -| `attributes`? | \| `null` \| [`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)<`string`, `any`> | + \| `null` \| [`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type)\<`string`, `any`\> -**Returns** +
-[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)< | `undefined` | [`Response`](https://developer.mozilla.org/docs/Web/API/Response)> +### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\< + \| `undefined` + \| [`Response`](https://developer.mozilla.org/docs/Web/API/Response)\> *** -### useUpdateCompany() +### useUpdateCompany() ```ts function useUpdateCompany(): (opts: {}) => Promise ``` -Returns a function to update the current company's information. For example, if the company changed plan or opted into a beta-feature. +Returns a function to update the current company's information. +For example, if the company changed plan or opted into a beta-feature. -The method returned is a function which returns a promise that resolves when after the features have been updated as a result of the company update. +The method returned is a function which returns a promise that +resolves when after the features have been updated as a result +of the company update. ```ts const updateCompany = useUpdateCompany(); updateCompany({ plan: "enterprise" }).then(() => console.log("Flags updated")); ``` -#### Returns +#### Returns `Function` -**Parameters** +### Parameters + + + + + + + + + + + + + + +
ParameterType
+ +`opts` + + -| Parameter | Type | -| --------- | ---- | -| `opts` | {} | +\{\} -**Returns** +
-[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<`void`> +### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> *** -### useUpdateOtherContext() +### useUpdateOtherContext() ```ts function useUpdateOtherContext(): (opts: {}) => Promise ``` -Returns a function to update the "other" context information. For example, if the user changed workspace, you can set the workspace id here. +Returns a function to update the "other" context information. +For example, if the user changed workspace, you can set the workspace id here. -The method returned is a function which returns a promise that resolves when after the features have been updated as a result of the update to the "other" context. +The method returned is a function which returns a promise that +resolves when after the features have been updated as a result +of the update to the "other" context. ```ts const updateOtherContext = useUpdateOtherContext(); @@ -919,47 +2348,90 @@ updateOtherContext({ workspaceId: newWorkspaceId }) .then(() => console.log("Flags updated")); ``` -#### Returns +#### Returns `Function` -**Parameters** +### Parameters + + + + + + + + + + + + + + +
ParameterType
+ +`opts` -| Parameter | Type | -| --------- | ---- | -| `opts` | {} | + -**Returns** +\{\} -[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<`void`> +
+ +### Returns + +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> *** -### useUpdateUser() +### useUpdateUser() ```ts function useUpdateUser(): (opts: {}) => Promise ``` -Returns a function to update the current user's information. For example, if the user changed role or opted into a beta-feature. +Returns a function to update the current user's information. +For example, if the user changed role or opted into a beta-feature. -The method returned is a function which returns a promise that resolves when after the features have been updated as a result of the user update. +The method returned is a function which returns a promise that +resolves when after the features have been updated as a result +of the user update. ```ts const updateUser = useUpdateUser(); updateUser({ optInHuddles: "true" }).then(() => console.log("Flags updated")); ``` -#### Returns +#### Returns `Function` -**Parameters** +### Parameters + + + + + + + + + + + + + + +
ParameterType
+ +`opts` + + + +\{\} + +
-| Parameter | Type | -| --------- | ---- | -| `opts` | {} | +### Returns -**Returns** +[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> -[`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<`void`> +Using v1? [Legacy docs](../../legacy/v1/react-sdk/globals.md) · [Upgrade guide](../migrating-from-v1.md). diff --git a/supported-languages/vue-sdk/README.md b/supported-languages/vue-sdk/README.md index 86b646b..d39851c 100644 --- a/supported-languages/vue-sdk/README.md +++ b/supported-languages/vue-sdk/README.md @@ -13,694 +13,170 @@ pagination: visible: true --- -# Reflag Vue SDK +# Reflag Vue SDK (beta) -Vue client side library for [Reflag.com](https://reflag.com) +Feature flags, remote configuration, usage tracking and feedback for Vue 3 applications. Built on the [Browser SDK](../browser-sdk/README.md). -Reflag supports flag toggling, tracking flag usage, requesting feedback on features and remotely configuring flags. +This page covers SDK v2. -The Reflag Vue SDK comes with the same built-in toolbar as the browser SDK which appears on `localhost` by default. +## Get started -## Install +### 1. Add the provider -Install via npm: +Install the SDK: -```shell -npm i @reflag/vue-sdk +```sh +npm install @reflag/vue-sdk ``` -## Migrating from Bucket SDK - -If you have been using the Bucket SDKs, the following list will help you migrate to Reflag SDK: - -- `Bucket*` classes, and types have been renamed to `Reflag*` (e.g. `BucketClient` is now `ReflagClient`) -- `Feature*` classes, and types have been renamed to `Feature*` (e.g. `Feature` is now `Flag`, `RawFeatures` is now `RawFlags`) -- All methods that contained `feature` in the name have been renamed to use the `flag` terminology (e.g. `getFeature` is `getFlag`) -- The `fallbackFeatures` property in client constructor and configuration files has been renamed to `fallbackFlags` -- `featureKey` has been renamed to `flagKey` in all methods that accepts that argument -- The SDKs will not emit `evaluate` and `evaluate-config` events anymore -- The new cookies that are stored in the client's browser are now `reflag-*` prefixed instead og `bucket-*` -- The `featuresUpdated` hook has been renamed to `flagsUpdated` -- The `checkIsEnabled` and `checkConfig` hooks have been removed, use `check` from now on - -To ease in transition to Reflag SDK, some of the old methods have been preserved as aliases to the new methods: - -- `getFeature` method is an alias for `getFlag` -- `getFeatures` method is an alias for `getFlags` -- `featuresUpdated` hook is an alias for `flagsUpdated` - -If you are running with strict Content Security Policies active on your website, you will need change them as follows: - -- `connect-src https://front.bucket.co` to `connect-src https://front.reflag.com` - -Finally, if you have customized the look & feel of the Feedback component, update `--bucket-feedback-*` CSS classes to `--reflag-feedback-*` - -## Get started - -### 1. Add the `ReflagProvider` context provider - -Add the `ReflagProvider` context provider to your application: - -**Example:** +Wrap your application in `ReflagProvider` with your **publishable** key and the signed-in user's context: ```vue - - - -``` - -If using Nuxt, wrap `` in ``. `` only renders client-side currently. - -### 2. Use `useFlag get flag status - -```vue - - - -``` - -See [useFlag()](#useflag) for a full example - -## Setting context - -Reflag determines which flags are active for a given `user`, `company`, or `other` context. -You can pass these to the `ReflagProvider` using the `context` prop. - -### Using the `context` prop - -```vue - - - -``` - -### Legacy individual props (deprecated) - -For backward compatibility, you can still use individual props, but these are deprecated and will be removed in the next major version: - -```vue - - - -``` - -> [!Important] -> The `user`, `company`, and `otherContext` props are deprecated. Use the `context` prop instead, which provides the same functionality in a more structured way. - -### Context requirements - -If you supply `user` or `company` objects, they must include at least the `id` property otherwise they will be ignored in their entirety. -In addition to the `id`, you must also supply anything additional that you want to be able to evaluate flag targeting rules against. -Attributes which are not properties of the `user` or `company` can be supplied using the `other` property. - -Attributes cannot be nested (multiple levels) and must be either strings, numbers or booleans. -A number of special attributes exist: - -- `name` -- display name for `user`/`company`, -- `email` -- the email of the user, -- `avatar` -- the URL for `user`/`company` avatar image. - -To retrieve flags along with their targeting information, use `useFlag(key: string)` hook (described in a section below). - -Note that accessing `isEnabled` on the object returned by `useFlag()` automatically -generates a `check` event. - -## Remote config - -Remote config is a dynamic and flexible approach to configuring flag behavior outside of your app – without needing to re-deploy it. - -Similar to `isEnabled`, each flag accessed using the `useFlag()` hook, has a `config` property. This configuration is managed from within Reflag. It is managed similar to the way access to flags is managed, but instead of the -binary `isEnabled` you can have multiple configuration values which are given to different user/companies. - -### Get started with Remote config - -```ts -const { - isEnabled, - config: { key, payload }, -} = useFlag("huddles"); - -// isEnabled: true, -// key: "gpt-3.5", -// payload: { maxTokens: 10000, model: "gpt-3.5-beta1" } -``` - -`key` is mandatory for a config, but if a flag has no config or no config value was matched against the context, the `key` will be `undefined`. Make sure to check against this case when trying to use the configuration in your application. `payload` is an optional JSON value for arbitrary configuration needs. - -Note that, similar to `isEnabled`, accessing `config` on the object returned by `useFlag()` automatically -generates a `check` event. - -## `` component - -The `` initializes the Reflag SDK, fetches flags and starts listening for automated feedback survey events. The component can be configured using a number of props: - -- `publishableKey` is used to connect the provider to an _environment_ on Reflag. Find your `publishableKey` under [environment settings](https://app.reflag.com/env-current/settings/app-environments) in Reflag, -- `context`: An object containing `user`, `company`, and `other` properties that make up the evaluation context used to determine if a flag is enabled or not. `company` and `user` contexts are automatically transmitted to Reflag servers so the Reflag app can show you which companies have access to which flags etc. -- `company`, `user` and `otherContext` (deprecated): Individual props for context. These are deprecated in favor of the `context` prop and will be removed in the next major version. - - > [!Note] - > If you specify `company` and/or `user` they must have at least the `id` property, otherwise they will be ignored in their entirety. You should also supply anything additional you want to be able to evaluate flag targeting against, - -- `timeoutMs`: Timeout in milliseconds when fetching flags from the server, -- `staleWhileRevalidate`: If set to `true`, stale flags will be returned while refetching flags in the background, -- `expireTimeMs`: If set, flags will be cached between page loads for this duration (in milliseconds), -- `staleTimeMs`: Maximum time (in milliseconds) that stale flags will be returned if `staleWhileRevalidate` is true and new flags cannot be fetched. - -- `enableTracking`: Set to `false` to stop sending tracking events and user/company updates to Reflag. Useful when you're impersonating a user (defaults to `true`), -- `apiBaseUrl`: Optional base URL for the Reflag API. This also controls the SSE origin used for live flag updates and automated feedback, -- `credentials`: Optional fetch credentials mode. Set to `"include"` when proxying through your backend and authenticating with cookies; this also enables credentials for live-update SSE connections. -- `appBaseUrl`: Optional base URL for the Reflag application. Use this to override the default app URL, - -- `debug`: Set to `true` to enable debug logging to the console. If both `logger` and `debug` are provided, `logger` takes precedence, -- `logger`: Optional custom logger implementation (`debug`, `info`, `warn`, `error`) used by the underlying client, -- `toolbar`: Optional [configuration](https://docs.reflag.com/supported-languages/browser-sdk/globals#toolbaroptions) for the Reflag toolbar, -- `feedback`: Optional configuration for feedback collection - -### Loading states - -ReflagProvider lets you define a template to be shown while ReflagProvider is initializing: - -```vue ``` -If you want more control over loading screens, `useIsLoading()` returns a `Ref` which you can use to customize the loading experience. +In Nuxt, wrap the provider in ``. -## `` component +### 2. Create a flag -The `` component is a specialized version of `ReflagProvider` designed for server-side rendering and preloaded flag scenarios. It uses pre-fetched flags for the initial render, resulting in faster initial page loads and better SSR compatibility. +Create a flag with the key `huddles` in the Reflag app. -### Usage +### 3. Read the flag -```vue - - - -``` - -### Getting bootstrapped flags - -You'll typically generate the `bootstrappedFlags` object on your server using the Node.js SDK or by fetching from the Reflag API. Pass the full object returned by `getFlagsForBootstrap()` directly to ``. It contains: - -- `context`: the evaluation context used on the server -- `flags`: the evaluated raw flags -- `flagStateVersion`: an optional version used to avoid redundant live-update refreshes immediately after bootstrapping - -If you want live flag updates to continue working after bootstrapping, use a recent `@reflag/node-sdk` so `getFlagsForBootstrap()` includes `flagStateVersion`. - -With `ReflagBootstrappedProvider`, `useOptInFlags()` requests a flags refresh on first use. It reports `isLoading: true` until that refresh settles. - -Here's an example using the Node.js SDK: - -```js -// server.js (Node.js/SSR) -import { ReflagClient } from "@reflag/node-sdk"; - -const client = new ReflagClient({ - secretKey: "your-secret-key", // Use secret key on server -}); -await client.initialize(); - -// Fetch flags for specific context -const context = { - user: { id: "user123", name: "John Doe", email: "john@acme.com" }, - company: { id: "company456", name: "Acme Inc", plan: "enterprise" }, -}; - -const bootstrappedFlags = client.getFlagsForBootstrap(context); - -// Pass to your Vue app -``` - -### ReflagBootstrappedProvider Props - -`ReflagBootstrappedProvider` accepts all the same props as `ReflagProvider` except: - -- `flags`: The pre-fetched bootstrapped state object containing `context`, evaluated `flags`, and an optional `flagStateVersion` -- All other props available in `ReflagProvider` are supported except `context`, `user`, `company`, and `otherContext` (which are extracted from `flags.context`) - -If the `flags` prop is not provided or is undefined, the provider will not initialize the client and will render in a non-loading state. - -{% hint style="info" %} -After bootstrapping, any live flag updates are fetched directly by the browser SDK from Reflag using the browser-visible context. If your bootstrapped snapshot depends on server-only or secret context that is not available in the browser, later live refreshes may differ. In that case, keep `enableLiveFlagUpdates` disabled. - -Requesting opt-in flags also triggers a browser-side refresh, even when `enableLiveFlagUpdates` is disabled. -{% endhint %} - -## `` component - -The `` is a lower-level component that accepts a pre-initialized `ReflagClient` instance. This is useful for advanced use cases where you need full control over client initialization or want to share a client instance across multiple parts of your application. - -### ReflagClientProvider Usage +Use `useFlag()` in any component: ```vue ``` -### ReflagClientProvider Props - -The `ReflagClientProvider` accepts the following props: +## Read flags -- `client`: A pre-initialized `ReflagClient` instance +`useFlag()` returns a ref that updates when the flag changes. Vue unwraps refs in templates; use `.value` in script. -### Slots - -- `loading`: Optional slot to show while the client is initializing (same as `ReflagProvider`) - -> [!Note] -> Most applications should use `ReflagProvider` or `ReflagBootstrappedProvider` instead of `ReflagClientProvider`. Only use this component when you need the advanced control it provides. - -## Hooks - -### `useFlag()` - -Returns the state of a given flag for the current context. The composable provides access to flags and their configurations. - -`useFlag()` returns an object with this shape: +Pass a flag key to check whether the flag is enabled: ```ts -{ - isEnabled: boolean, // is the flag enabled - track: () => void, // send a track event when the flag is used - requestFeedback: (...) => void // open up a feedback dialog - config: {key: string, payload: any}, // remote configuration for this flag - isLoading: boolean // if you want to manage loading state at the flag level -} -``` - -Example: - -```vue - - - +const enabled = useFlag("huddles"); // ref of true or false ``` -See the reference docs for details. - -### `useOptInFlags()` and `useSetOptIn()` +To read a configuration value, pass a default as the second argument. The ref holds a value of the same type as the default: -Use these composables to build an end-user opt-in UI for flags where opt-in is enabled in Reflag. - -```vue - - - +```ts +const model = useFlag("model", "quick"); // ref of string +const settings = useFlag("huddle-settings", { maxParticipants: 10 }); // ref of { maxParticipants: number } ``` -By default, `useSetOptIn()` changes the opt-in for the current user, so the current context must include a `user.id`. To manage the current company's opt-in instead, pass `scope: "company"`; the context must then include a `company.id`. - -User and company opt-ins are managed independently. Setting `optedIn` to `false` removes the opt-in only for the selected scope. For example, cancelling a user's opt-in does not change the company's opt-in for the same flag. - -`setOptIn` returns a promise so you can wait for the new membership state to be synchronized. On success, it resolves after the refreshed flag state has been applied locally, the requested membership change has been confirmed, and subscribers have been notified when flags change. Vue may not have committed the resulting render yet. - -The promise resolves to a `Response`, or `undefined` if skipped due to invalid input, offline mode etc. Check `response?.ok` for success. +While flags are loading, if the flag doesn't exist, or if its value has a different type, the ref holds `false`, or your default if you passed one. Pass `null` as the default to accept any JSON value and narrow it yourself. -`useOptInFlags()` returns `{ flags, isLoading }`, where both values are computed refs. With `ReflagBootstrappedProvider`, it fetches opt-in metadata on first use and reports `isLoading: true` until that refresh succeeds or fails. +The SDK checks only the top-level type of a value. If your application depends on nested fields, validate them. -If fetching opt-in metadata fails, loading ends without exposing an error. Call `client.refresh()` on the client returned by `useClient()` to retry. +Each read records a check, which Reflag uses for launch monitoring. -With a regular `ReflagProvider`, opt-in metadata arrives as part of the normal initial flags request, so `useOptInFlags().isLoading` remains `false`. Use the general `useIsLoading()` composable or the provider's loading slot for that initial loading state. +## Loading states -### `useTrack()` +`useIsLoading()` returns a Boolean ref that is `true` while the provider loads flags. You can also put loading content in the provider's `#loading` slot, as in the example above. -`useTrack()` returns a function which lets you send custom events to Reflag. It takes a string argument with the event name and optionally an object with properties to attach the event. - -Using `track` returned from `useFlag()` calls this track function with the flag key as the event name. - -```vue - - - -``` - -### `useRequestFeedback()` - -Returns a function that lets you open up a dialog to ask for feedback on a specific feature. This is useful for collecting targeted feedback about specific features. - -See [Automated Feedback Surveys](https://docs.reflag.com/product-handbook/live-satisfaction) for how to do this automatically, without code. - -When using the `useRequestFeedback` you must pass the flag key to `requestFeedback`. -The example below shows how to use `position` to ensure the popover appears next to the "Give feedback!" button. - -```vue - - - -``` - -See the [Feedback Documentation](https://github.com/reflagcom/javascript/blob/main/packages/browser-sdk/FEEDBACK.md#manual-feedback-collection) for more information on `requestFeedback` options. - -### `useSendFeedback()` - -Returns a function that lets you send feedback to Reflag. This is useful if you've manually collected feedback through your own UI and want to send it to Reflag. - -```vue - - - +await sendFeedback({ flagKey: "huddles", score: 5 }); ``` -### `useUpdateUser()`, `useUpdateCompany()` and `useUpdateOtherContext()` +Configure your flag's adoption rules to match the event names you send. See the [Browser feedback documentation](../browser-sdk/feedback.md) to configure feedback prompts and the feedback UI. -These composables return functions that let you update the attributes for the currently set user, company, or other context. Updates to user/company are stored remotely and affect flag targeting, while "other" context updates only affect the current session. +## Update context -```vue - +`useUpdateUser()`, `useUpdateCompany()` and `useUpdateOtherContext()` return functions that merge new attributes into the current context. To replace the whole context, call `useClient().setContext(context)`. Flag values are refetched for the new context. - -``` +## Bootstrap from the server -Note: To change the `user.id` or `company.id`, you need to update the props passed to `ReflagProvider` instead of using these composables. +To render flags immediately, without waiting for a network request, evaluate them on your server with the **Node.js SDK**: -### `useClient()` +```ts +const flags = serverClient.getFlagsForBootstrap(context); +``` -Returns the `ReflagClient` used by the `ReflagProvider`. The client offers more functionality that -is not directly accessible through the other composables. +Then pass the whole result to `ReflagBootstrappedProvider`, serialized with your framework's usual mechanism: ```vue - - - + + + ``` -### `useIsLoading()` - -Returns a `Ref` to indicate if Reflag has finished loading. -Initially, the value will be `true` if no bootstrap flags have been provided and the client has not be initialized. +Leave secrets and server-only attributes out of the context you bootstrap, because the browser can read it. Later refreshes evaluate flags using the browser's context. If values that depend on server-only attributes must not change, set `:enable-live-flag-updates="false"`. -```vue - +```ts +const { flags, isLoading } = useOptInFlags(); +const setOptIn = useSetOptIn(); - +await setOptIn("huddles", { optedIn: true }); +await setOptIn("huddles", { optedIn: false, scope: "company" }); ``` -### `useOnEvent()` - -Vue composable for listening to Reflag client events. This composable automatically handles mounting and unmounting of event listeners. +Each entry includes the flag's `key`, `name`, `description` and whether the user or company has opted in. User and company opt-ins are independent. Check `isLoading` before rendering an empty state. -Available events include: +## Overrides and toolbar -- `flagsUpdated`: Triggered when flags are updated -- `track`: Triggered when tracking events are sent -- `feedback`: Triggered when feedback is sent +The toolbar shows on `localhost` by default and lets you toggle Boolean flags for yourself. Use the `toolbar` prop to show it elsewhere, for example to internal users in production: ```vue - - - + + + ``` -You can also provide a specific client instance if needed: - -```vue - +`useClient()` returns the underlying Browser SDK client. If you already create a Browser SDK client yourself, pass it to `ReflagClientProvider`; your application is then responsible for initializing and stopping it. - -``` +## Events -## Content Security Policy (CSP) +`useOnEvent(type, handler)` subscribes to [client events](../browser-sdk/README.md) and unsubscribes when the component unmounts. -See [CSP](https://github.com/reflagcom/javascript/blob/main/packages/browser-sdk/README.md#content-security-policy-csp) for info on using Reflag React SDK with CSP +## Configuration -## License +The provider accepts the Browser SDK's configuration options, such as `fallbackFlags`, `enableTracking`, `offline`, `feedback` and `logger`, as props. Live updates are on by default in Vue; set `:enable-live-flag-updates="false"` to turn them off. Set `debug` to log to the console. -MIT License +For Content Security Policy requirements and the full list of options, see the [Browser SDK](../browser-sdk/README.md). -Copyright (c) 2025 Bucket ApS +Using v1? [Legacy docs](../../legacy/v1/vue-sdk/README.md) · [Upgrade guide](../migrating-from-v1.md). diff --git a/supported-languages/vue-sdk/globals.md b/supported-languages/vue-sdk/globals.md index 0ae59b1..d2e14a6 100644 --- a/supported-languages/vue-sdk/globals.md +++ b/supported-languages/vue-sdk/globals.md @@ -13,22 +13,23 @@ pagination: visible: true --- -# @reflag/vue-sdk +# @reflag/vue-sdk -## Interfaces +This page covers SDK v2. -### CheckEvent +## Interfaces -Event representing checking the flag evaluation result +### CheckEvent -#### Properties +A root read records selection identity, never its JSON payload. + +#### Properties - @@ -40,53 +41,38 @@ Event representing checking the flag evaluation result - - - + + + - + + - - + + @@ -162,19 +146,19 @@ Version of targeting rules. *** -### CompanyContext +### CompanyContext Context is a set of key-value pairs. This is used to determine if feature targeting matches and to track events. Id should always be present so that it can be referenced to an existing company. -#### Indexable +#### Indexable ```ts [key: string]: ContextValue ``` -#### Properties +#### Properties
Property TypeDescription
-`"check-is-enabled"` \| `"check-config"` - - - -`check-is-enabled` means `isEnabled` was checked, `check-config` means `config` was checked. +`"check"`
- `evaluationErrors?` + `evalContext?` -\{ `code`: `string`; `field`: `string`; `message`: `string`; `operator`: `string`; \}[] - - - -Non-fatal diagnostics produced while evaluating the flag. +[`ReflagContext`](../browser-sdk/globals.md#reflagcontext)
- `key` - - - -`string` + `evalErrors?` -Flag key. +[`EvaluationError`](../browser-sdk/globals.md#evaluationerror)[]
- ~~`missingContextFields?`~~ + `evalMissingFields?` @@ -94,66 +80,64 @@ Flag key. `string`[]
-Missing context fields. + `evalResult?` -**Deprecated** + -Use `evaluationErrors` and check for `MISSING_CONTEXT_FIELD`. +`string`
- `ruleEvaluationResults?` + `evalRuleResults?` `boolean`[] - - -Rule evaluation results. -
- `value?` + `flagStateVersion?` - \| `boolean` \| \{ `key`: `string`; `payload`: `any`; \} +`number`
-Result of flag or configuration evaluation. -If `action` is `check-is-enabled`, this is the result of the flag evaluation and `value` is a boolean. -If `action` is `check-config`, this is the result of the configuration evaluation. + `key`
- `version?` +`string`
-`number` + `sourceVersionId?` -Version of targeting rules. +`string`
@@ -224,144 +208,23 @@ Company name *** -### Flag\ - -#### Type Parameters - -
- - - - - - - - - - - - -
Type ParameterDefault type
- -`TConfig` *extends* [`FlagType`](globals.md#flagtype)\[`"config"`\] - - - -[`EmptyFlagRemoteConfig`](globals.md#emptyflagremoteconfig) - -
- -#### Properties - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
PropertyType
- - `config` - - - -`Ref`\< \| [`EmptyFlagRemoteConfig`](globals.md#emptyflagremoteconfig) \| \{ `key`: `string`; \} & `TConfig`, \| [`EmptyFlagRemoteConfig`](globals.md#emptyflagremoteconfig) \| \{ `key`: `string`; \} & `TConfig`\> - -
- - `isEnabled` - - - -`Ref`\<`boolean`, `boolean`\> - -
- - `isLoading` - - - -`Ref`\<`boolean`, `boolean`\> - -
- - `key` - - - -`string` - -
- - `requestFeedback` - - - -(`opts`: [`RequestFlagFeedbackOptions`](globals.md#requestflagfeedbackoptions)) => `void` - -
- -#### Methods - -##### track() - -```ts -track(): - | undefined - | Promise< - | undefined -| Response> -``` - -###### Returns - - \| `undefined` - \| [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\< - \| `undefined` - \| [`Response`](https://developer.mozilla.org/docs/Web/API/Response)\> +### Flags *** -### Flags - -*** - -### UserContext +### UserContext Context is a set of key-value pairs. This is used to determine if feature targeting matches and to track events. Id should always be present so that it can be referenced to an existing user. -#### Indexable +#### Indexable ```ts [key: string]: ContextValue ``` -#### Properties +#### Properties @@ -426,142 +289,73 @@ User name
-## Type Aliases +## Type Aliases -### BootstrappedFlags +### BootstrappedFlags ```ts -type BootstrappedFlags = BootstrappedState & { - flags: RawFlags; -}; +type BootstrappedFlags = BootstrappedState; ``` -#### Type declaration - - - - - - - - - - - - - - -
NameType
- -`flags` - - - -[`RawFlags`](../browser-sdk/globals.md#rawflags) - -
- *** -### EmptyFlagRemoteConfig +### FlagDefaultValue ```ts -type EmptyFlagRemoteConfig = { - key: undefined; - payload: undefined; -}; +type FlagDefaultValue = + | null + | boolean + | number + | string + | readonly FlagDefaultValue[] +| {}; ``` -#### Type declaration - - - - - - - - - - - - - - - - - - -
NameType
- - `key` - - - -`undefined` - -
- - `payload` - - +*** -`undefined` +### FlagKey -
+```ts +type FlagKey = keyof Flags extends never ? string : Extract; +``` *** -### FlagKey +### FlagValue ```ts -type FlagKey = keyof TypedFlags; +type FlagValue = + | null + | boolean + | number + | string + | FlagValue[] +| {}; ``` *** -### FlagType +### FlagValueFromDefault\ ```ts -type FlagType = { - config: { - payload: any; - }; -}; +type FlagValueFromDefault = T extends null ? FlagValue : T extends boolean ? boolean : T extends number ? number : T extends string ? string : T extends readonly infer Element[] ? [Element] extends [never] ? FlagValue[] : FlagValueFromDefault[] : T extends object ? { -readonly [Key in keyof T]: FlagValueFromDefault } : never; ``` -#### Type declaration +Widen literals and return mutable copies. Null requests arbitrary JSON. + +#### Type Parameters - - + - - - - - @@ -570,7 +364,7 @@ type FlagType = { *** -### OptInFlag +### OptInFlag ```ts type OptInFlag = Omit & { @@ -578,13 +372,7 @@ type OptInFlag = Omit & { }; ``` -An opt-in-enabled flag for the generated Vue SDK flag definitions. - -Includes all fields from [BrowserOptInFlag](../browser-sdk/globals.md#optinflag): `name`, `description`, -`isEnabled`, `userOptedIn`, `companyOptedIn`, and `isOptedIn`. -Only `key` is narrowed to the generated [FlagKey](globals.md#flagkey) type. - -#### Type declaration +#### Type declaration
NameTypeType Parameter
- `config`? - - - -\{ - `payload`: `any`; - \} - -
- -`config.payload` - - - -`any` +`T`
@@ -611,7 +399,7 @@ Only `key` is narrowed to the generated [FlagKey](globals.md#flagkey) type. *** -### ReflagBaseProps +### ReflagBaseProps ```ts type ReflagBaseProps = { @@ -625,7 +413,7 @@ type ReflagBaseProps = { Base props for the ReflagProvider and ReflagBootstrappedProvider. -#### Type declaration +#### Type declaration
@@ -678,7 +466,7 @@ Set to `true` to show the loading component while the client is initializing.
-[`Logger`](../browser-sdk/globals.md#logger-1) +[`Logger`](../browser-sdk/globals.md#logger) @@ -694,7 +482,7 @@ If both `logger` and `debug` are provided, `logger` takes precedence. *** -### ReflagBootstrappedProps +### ReflagBootstrappedProps ```ts type ReflagBootstrappedProps = ReflagInitOptionsBase & ReflagBaseProps & { @@ -704,7 +492,7 @@ type ReflagBootstrappedProps = ReflagInitOptionsBase & ReflagBaseProps & { Props for the ReflagBootstrappedProvider. -#### Type declaration +#### Type declaration @@ -738,7 +526,7 @@ metadata on demand when opt-in flags are requested. *** -### ReflagClientProviderProps +### ReflagClientProviderProps ```ts type ReflagClientProviderProps = Omit & { @@ -748,7 +536,7 @@ type ReflagClientProviderProps = Omit & { Props for the ReflagClientProvider. -#### Type declaration +#### Type declaration
@@ -781,10 +569,10 @@ A pre-initialized ReflagClient to use. *** -### ReflagInitOptionsBase +### ReflagInitOptionsBase ```ts -type ReflagInitOptionsBase = Omit ```ts type ReflagProps = ReflagInitOptionsBase & ReflagBaseProps & { @@ -813,7 +601,7 @@ type ReflagProps = ReflagInitOptionsBase & ReflagBaseProps & { Props for the ReflagProvider. -#### Type declaration +#### Type declaration
@@ -911,7 +699,7 @@ Use `context` instead, this property will be removed in the next major version *** -### RequestFlagFeedbackOptions +### RequestFlagFeedbackOptions ```ts type RequestFlagFeedbackOptions = Omit; @@ -919,7 +707,7 @@ type RequestFlagFeedbackOptions = Omit ```ts type SetOptInOptions = { @@ -928,9 +716,9 @@ type SetOptInOptions = { }; ``` -Options for changing the current user or company's opt-in membership. +Represents a flag. -#### Type declaration +#### Type declaration
@@ -980,7 +768,7 @@ Whether to update the current user or current company. Defaults to `user`. *** -### TrackEvent +### TrackEvent ```ts type TrackEvent = { @@ -992,7 +780,7 @@ type TrackEvent = { }; ``` -#### Type declaration +#### Type declaration
@@ -1056,15 +844,15 @@ type TrackEvent = { *** -### TypedFlags +### TypedFlags ```ts -type TypedFlags = keyof Flags extends never ? Record : { [TypedFlagKey in keyof Flags]: Flags[TypedFlagKey] extends FlagType ? Flag : Flag }; +type TypedFlags = keyof Flags extends never ? Record : { [Key in keyof Flags]: Flags[Key] | undefined }; ``` *** -### UseOptInFlagsResult +### UseOptInFlagsResult ```ts type UseOptInFlagsResult = { @@ -1073,7 +861,7 @@ type UseOptInFlagsResult = { }; ``` -#### Type declaration +#### Type declaration
@@ -1098,7 +886,7 @@ type UseOptInFlagsResult = {
- `isLoading` + `isLoading` @@ -1110,9 +898,9 @@ type UseOptInFlagsResult = {
-## Variables +## Variables -### default +### default ```ts default: { @@ -1120,7 +908,7 @@ default: { }; ``` -#### Type declaration +#### Type declaration @@ -1147,15 +935,15 @@ default: { *** -### ReflagBootstrappedProvider +### ReflagBootstrappedProvider ```ts const ReflagBootstrappedProvider: DefineComponent, Record, unknown>; ``` -## Functions +## Functions -### useClient() +### useClient() ```ts function useClient(): ReflagClient @@ -1166,13 +954,13 @@ Vue composable for getting the Reflag client. This composable returns the Reflag client. You can use this to get the Reflag client at any point in your application. -#### Returns +#### Returns [`ReflagClient`](../browser-sdk/globals.md#reflagclient) The Reflag client. -#### Example +#### Example ```ts import { useClient } from '@reflag/vue-sdk'; @@ -1184,17 +972,66 @@ console.log(client.getContext()); *** -### useFlag() +### useFlag() + +#### Call Signature ```ts -function useFlag(key: TKey): TypedFlags[TKey] +function useFlag(key: string, defaultValue?: undefined): ShallowRef ``` -Vue composable for getting the state of a given flag for the current context. +Reactive direct values: Boolean/false by default, or infer a positional JSON default. + +### Parameters + +
+ + + + + + + + + + + + + + + + +
ParameterType
+ +`key` + + + +`string` + +
+ +`defaultValue`? + + + +`undefined` -This composable returns an object with the state of the flag for the current context. +
-#### Type Parameters +### Returns + +`ShallowRef`\<`boolean`\> + +#### Call Signature + +```ts +function useFlag(key: Key, defaultValue: Default): ShallowRef> +``` + +Reactive direct values: Boolean/false by default, or infer a positional JSON default. + +### Type Parameters @@ -1206,21 +1043,27 @@ This composable returns an object with the state of the flag for the current con + + +
-`TKey` *extends* `string` +`Key` *extends* `string` + +
+ +`Default` *extends* `object` \| [`FlagDefaultValue`](globals.md#flagdefaultvalue)
-#### Parameters +### Parameters - @@ -1232,41 +1075,100 @@ This composable returns an object with the state of the flag for the current con + + +
Parameter TypeDescription
-`TKey` +`Key` + +
+ +`defaultValue` -The key of the flag to get the state of. +`Default`
-#### Returns - -[`TypedFlags`](globals.md#typedflags)\[`TKey`\] +### Returns -An object with the state of the flag. +`ShallowRef`\<[`FlagValueFromDefault`](globals.md#flagvaluefromdefaultt)\<`Default`\>\> -#### Example +#### Call Signature ```ts -import { useFlag } from '@reflag/vue-sdk'; +function useFlag(key: string, defaultValue: Default): ShallowRef> +``` -const { isEnabled, config, track, requestFeedback } = useFlag("huddles"); +Reactive direct values: Boolean/false by default, or infer a positional JSON default. -function StartHuddlesButton() { - const { isEnabled, config: { payload }, track } = useFlag("huddles"); - if (isEnabled) { - return ; -} -``` +### Type Parameters + + + + + + + + + + + + +
Type Parameter
+ +`Default` *extends* `object` \| [`FlagDefaultValue`](globals.md#flagdefaultvalue) + +
+ +### Parameters + + + + + + + + + + + + + + + + + + +
ParameterType
+ +`key` + + + +`string` + +
+ +`defaultValue` + + + +`Default` + +
+ +### Returns + +`ShallowRef`\<[`FlagValueFromDefault`](globals.md#flagvaluefromdefaultt)\<`Default`\>\> *** -### useIsLoading() +### useIsLoading() ```ts function useIsLoading(): Ref @@ -1278,11 +1180,11 @@ This composable returns a boolean value that indicates whether the Reflag client You can use this to check if the Reflag client is loading at any point in your application. Initially, the value will be true until the client is initialized. -#### Returns +#### Returns `Ref`\<`boolean`, `boolean`\> -#### Example +#### Example ```ts import { useIsLoading } from '@reflag/vue-sdk'; @@ -1294,18 +1196,18 @@ console.log(isLoading); *** -### useOnEvent() +### useOnEvent() ```ts function useOnEvent( - event: THookType, - handler: (arg0: HookArgs[THookType]) => void, + event: THookType, + handler: (arg0: HookArgs[THookType]) => void, client?: ReflagClient): void ``` Vue composable for listening to Reflag client events. -#### Type Parameters +#### Type Parameters @@ -1324,7 +1226,7 @@ Vue composable for listening to Reflag client events.
-#### Parameters +#### Parameters @@ -1389,11 +1291,11 @@ The Reflag client to listen to. If not provided, the client will be retrieved fr
-#### Returns +#### Returns `void` -#### Example +#### Example ```ts import { useOnEvent } from '@reflag/vue-sdk'; @@ -1405,7 +1307,7 @@ useOnEvent("flagsUpdated", () => { *** -### useOptInFlags() +### useOptInFlags() ```ts function useOptInFlags(): UseOptInFlagsResult @@ -1416,18 +1318,15 @@ the current context. The loading state is only used with `ReflagBootstrappedProvider` while opt-in metadata is fetched on demand. Regular providers load opt-in metadata -with the initial flags; use [useIsLoading](globals.md#useisloading) for their loading state. - -If fetching opt-in metadata fails, loading ends without exposing an error. -Call `refresh()` on the client returned by [useClient](globals.md#useclient) to retry. +with the initial flags. -#### Returns +#### Returns [`UseOptInFlagsResult`](globals.md#useoptinflagsresult) *** -### useRequestFeedback() +### useRequestFeedback() ```ts function useRequestFeedback(): (options: RequestFeedbackData) => void @@ -1439,14 +1338,14 @@ This composable returns a function that can be used to trigger the feedback collection flow with the Reflag SDK. You can use this to prompt users for feedback at any point in your application. -#### Returns +#### Returns `Function` A function that requests feedback from the user. The function accepts: - `options`: An object containing feedback request options. -##### Parameters +### Parameters @@ -1471,11 +1370,11 @@ A function that requests feedback from the user. The function accepts:
-##### Returns +### Returns `void` -#### Example +#### Example ```ts import { useRequestFeedback } from '@reflag/vue-sdk'; @@ -1491,7 +1390,7 @@ requestFeedback({ *** -### useSendFeedback() +### useSendFeedback() ```ts function useSendFeedback(): (opts: UnassignedFeedback) => Promise< @@ -1504,14 +1403,14 @@ Vue composable for sending feedback. This composable returns a function that can be used to send feedback to the Reflag SDK. You can use this to send feedback from your application. -#### Returns +#### Returns `Function` A function that sends feedback to the Reflag SDK. The function accepts: - `options`: An object containing feedback options. -##### Parameters +### Parameters @@ -1536,13 +1435,13 @@ A function that sends feedback to the Reflag SDK. The function accepts:
-##### Returns +### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\< \| `undefined` \| [`Response`](https://developer.mozilla.org/docs/Web/API/Response)\> -#### Example +#### Example ```ts import { useSendFeedback } from '@reflag/vue-sdk'; @@ -1558,7 +1457,7 @@ sendFeedback({ *** -### useSetOptIn() +### useSetOptIn() ```ts function useSetOptIn(): (key: string, options: SetOptInOptions) => Promise< @@ -1568,16 +1467,11 @@ function useSetOptIn(): (key: string, options: SetOptInOptions) => Promise< Vue composable for setting whether the current user or company has opted into a flag. -Check the returned Response's `ok` property and catch promise rejections. -HTTP failures return a non-OK Response; offline mode, invalid arguments, or -missing scoped context return undefined. Confirmation failures can reject -after the membership changed remotely. See [ReflagClient.setOptIn](../browser-sdk/globals.md#setoptin). - -#### Returns +#### Returns `Function` -##### Parameters +### Parameters @@ -1614,7 +1508,7 @@ after the membership changed remotely. See [ReflagClient.setOptIn](../browser-sd
-##### Returns +### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\< \| `undefined` @@ -1622,10 +1516,10 @@ after the membership changed remotely. See [ReflagClient.setOptIn](../browser-sd *** -### useTrack() +### useTrack() ```ts -function useTrack(): (eventName: string, attributes?: +function useTrack(): (eventName: string, attributes?: | null | Record) => Promise< | undefined @@ -1637,7 +1531,7 @@ Vue composable for tracking custom events. This composable returns a function that can be used to track custom events with the Reflag SDK. -#### Returns +#### Returns `Function` @@ -1645,7 +1539,7 @@ A function that tracks an event. The function accepts: - `eventName`: The name of the event to track. - `attributes`: (Optional) Additional attributes to associate with the event. -##### Parameters +### Parameters @@ -1682,13 +1576,13 @@ A function that tracks an event. The function accepts:
-##### Returns +### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\< \| `undefined` \| [`Response`](https://developer.mozilla.org/docs/Web/API/Response)\> -#### Example +#### Example ```ts import { useTrack } from '@reflag/vue-sdk'; @@ -1701,7 +1595,7 @@ track('button_clicked', { buttonName: 'Start Huddles' }); *** -### useUpdateCompany() +### useUpdateCompany() ```ts function useUpdateCompany(): (opts: {}) => Promise @@ -1713,14 +1607,14 @@ This composable returns a function that can be used to update the company context with the Reflag SDK. You can use this to update the company context at any point in your application. -#### Returns +#### Returns `Function` A function that updates the company context. The function accepts: - `opts`: An object containing the company context to update. -##### Parameters +### Parameters @@ -1745,11 +1639,11 @@ A function that updates the company context. The function accepts:
-##### Returns +### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> -#### Example +#### Example ```ts import { useUpdateCompany } from '@reflag/vue-sdk'; @@ -1762,7 +1656,7 @@ updateCompany({ id: "123", name: "Acme Inc." }); *** -### useUpdateOtherContext() +### useUpdateOtherContext() ```ts function useUpdateOtherContext(): (opts: {}) => Promise @@ -1774,14 +1668,14 @@ This composable returns a function that can be used to update the other context with the Reflag SDK. You can use this to update the other context at any point in your application. -#### Returns +#### Returns `Function` A function that updates the other context. The function accepts: - `opts`: An object containing the other context to update. -##### Parameters +### Parameters @@ -1806,11 +1700,11 @@ A function that updates the other context. The function accepts:
-##### Returns +### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> -#### Example +#### Example ```ts import { useUpdateOtherContext } from '@reflag/vue-sdk'; @@ -1823,7 +1717,7 @@ updateOtherContext({ id: "123", name: "Acme Inc." }); *** -### useUpdateUser() +### useUpdateUser() ```ts function useUpdateUser(): (opts: {}) => Promise @@ -1835,14 +1729,14 @@ This composable returns a function that can be used to update the user context with the Reflag SDK. You can use this to update the user context at any point in your application. -#### Returns +#### Returns `Function` A function that updates the user context. The function accepts: - `opts`: An object containing the user context to update. -##### Parameters +### Parameters @@ -1867,11 +1761,11 @@ A function that updates the user context. The function accepts:
-##### Returns +### Returns [`Promise`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)\<`void`\> -#### Example +#### Example ```ts import { useUpdateUser } from '@reflag/vue-sdk'; @@ -1882,12 +1776,14 @@ const updateUser = useUpdateUser(); updateUser({ id: "123", name: "John Doe" }); ``` -## References +## References -### ReflagClientProvider +### ReflagClientProvider Renames and re-exports [ReflagBootstrappedProvider](globals.md#reflagbootstrappedprovider) -### ReflagProvider +### ReflagProvider Renames and re-exports [ReflagBootstrappedProvider](globals.md#reflagbootstrappedprovider) + +Using v1? [Legacy docs](../../legacy/v1/vue-sdk/globals.md) · [Upgrade guide](../migrating-from-v1.md).