티스토리 수익 글 보기
Was this helpful?
<script src="https://cdn.jsdelivr.net/npm/@reflag/browser-sdk@2"></script>
<script>
const reflag = new ReflagBrowserSDK.ReflagClient({
publishableKey: "publishableKey",
user: { id: "42" },
company: { id: "1" },
});
reflag.initialize().then(() => {
console.log("Reflag initialized");
document.getElementById("loading").style.display = "none";
document.getElementById("start-huddle").style.display = "block";
});
</script>
<span id="loading">Loading...</span>
<button
id="start-huddle"
style="display: none"
onClick="reflag.track('Started huddle')"
>
Click me
</button>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<string, { key: string; payload: any } | true>; // 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
};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"
},
});const huddle = reflagClient.getFlag("huddle");
// {
// isEnabled: true,
// config: { key: "zoom", payload: { ... } },
// track: () => Promise<Response>
// requestFeedback: (options: RequestFeedbackData) => void
// }const flags = reflagClient.getFlags();
// {
// huddle: {
// isEnabled: true,
// targetingVersion: 42,
// config: ...
// }
// }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);
}const flags = reflagClient.getFlags();
// {
// huddle: {
// isEnabled: true,
// targetingVersion: 42,
// config: {
// key: "gpt-3.5",
// payload: { maxTokens: 10000, model: "gpt-3.5-beta1" }
// }
// }
// }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
};// 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(
`<script>var bootstrappedState = ${JSON.stringify(bootstrappedState)};</script>
<main id="app"></main>`,
),
);
});
// 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");// 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,
});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",
},
});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" }
// }const client = new ReflagClient({
// show the toolbar even in production if the user is an internal/admin user
toolbar: user?.isInternal,
...
});const client = new ReflagClient({
toolbar: {
show: true;
position: {
placement: "bottom-left",
offset: {x: "1rem", y: "1rem"}
}
}
...
})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)
});reflagClient.track("huddle", { voiceHuddle: true });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();import reflag from "@reflag/browser-sdk";
import { sha256 } from "crypto-hash";
reflag.user(await sha256("john_doe"));