The user wants a specification for a Feature Flag SDK.
Key requirements:
SSR Defaults: Support Server-Side Rendering (SSR) where flags are evaluated on the server and passed to the client.
Hydration Safety: Ensure consistency between server-rendered content and client-side hydration to prevent layout shifts or "flash of content" (FOUC).
Analytics Beacons: Ability to track when flags are accessed or evaluated for analytics purposes (exposure tracking).
Scope of the Specification:
I need to define the architecture, API surface, initialization flow, data structures, and specific mechanisms to handle the three key requirements.
1. Architecture & Concepts:
Client: The main entry point.
Context: User/Device attributes used for evaluation.
Provider: The backend source of truth (e.g., LaunchDarkly, Unleash, internal).
State: The snapshot of flags.
2. Requirement: SSR Defaults (Server-Side Rendering):
Mechanism: The SDK needs two modes: Server Mode (evaluates) and Client Mode (consumes).
Data Transfer: The server needs to serialize the evaluated state and inject it into the HTML. The client needs to read this "bootstrap" data.
API:createServerClient vs createClientClient (or unified with options).
Spec detail: A bootstrap or initialState configuration option.
3. Requirement: Hydration Safety:
Problem: If the server says true (show feature) and the client defaults to false while waiting for the network, React/Vue hydration fails or flickers.
Solution: The client SDK must use the bootstrapped state immediately. It must not make asynchronous network requests before the initial render if bootstrapped data exists.
Spec detail:useFlag hook (or similar) must return the value synchronously. React integration needs a specific Provider that injects the window-scoped state.
4. Requirement: Analytics Beacons:
Mechanism: Callbacks or Event Emitters.
Trigger: Whenever a flag is evaluated (getFlag, isOn).
Data: Flag key, value, user context, version.
Spec detail:onEvaluation listener, or an ExposureTracker interface.
Drafting the Spec Structure:
Overview: High-level goals.
Core Concepts: Client, Context, Flag Value.
API Reference:
Initialization (Config).
Evaluation Methods (getFlag, isOn).
Context Management (identify).
Event Handling.
SSR & Hydration Strategy:
Server-side evaluation.
State serialization (JSON).
Client-side rehydration.
Analytics & Tracking:
Exposure events.
Beacon format.
Type Definitions (Typescript): To make it concrete.
Refining the Details:
SSR Flow:
Request comes in.
Server SDK initialized with User Context.
Flags evaluated.
State serialized to JSON string.
JSON injected into <script>window.__FLAG_STATE__ = ...</script>.
Client SDK initialized with state: window.__FLAG_STATE__.
Safety check: Client SDK throws warning if server state differs from live stream update immediately (optional, but good for logging).
Hydration Safety:
The client SDK must support a disableNetwork option if bootstrapped, or just prioritize bootstrap.
"Hydration Mismatch" detection: If the client evaluates a flag differently than the server state provided, an error should be logged (dev mode).
Analytics:
Need a standard interface for the beacon sender.
Debouncing might be necessary if flags are checked in a tight loop, though usually, exposure tracking is per unique flag per session or per page load. Let's stick to "per evaluation" for the spec but allow the implementation to handle batching.
Self-Correction/Refinement during thought process:
Initial thought: Should I separate Server SDK and Client SDK completely?
Correction: Usually, SDKs share core logic but have different "sources". However, for a spec, it's cleaner to define a "Provider" interface. But for simplicity in a spec document, I will define a FeatureFlagClient that works on both, but accepts different Source strategies.
Actually: Let's stick to the standard industry pattern (like LaunchDarkly/Unleash): A Server SDK (Node.js) and a Client SDK (Browser). They have different APIs because one is secure/full-evaluation and the other is often insecure/local-evaluation or streaming. The spec should cover how they interact.
Let's define a unified interface IFeatureFlagClient but note implementation differences.
Key Spec Sections:
Configuration: bootstrap, trackingHandler.
The Evaluation Object: Reason (why it returned true), Variant, Value.
The Exposure Event: What gets sent to analytics.
Structuring the Output:
I will present this as a formal Technical Design Specification (TDS).
Title: Feature Flag SDK Specification (SSR-First)
Section 1: Core Interfaces: The Types.
Section 2: Server-Side Logic: Generating state.
Section 3: Client-Side & Hydration: Consuming state safely.
Section 4: Analytics: The Beacon system.
Section 5: Framework Integration (React example): Putting it together.
Let's write the content.
Hydration Safety nuance: The hydrationKey. If the server renders a specific variation, the client needs to know which variation it was to match it. The reason field in evaluation is crucial for debugging hydration issues.
Analytics nuance: "Beacons" usually implies navigator.sendBeacon. The spec should suggest using that for the analytics transport to ensure data isn't lost on page unmount.
Let's go.
This specification outlines a Feature Flag SDK designed for modern web applications, specifically addressing the complexities of Server-Side Rendering (SSR), framework hydration (React/Vue/Angular), and data-driven analytics.
The specification is divided into three core pillars: Architecture, SSR & Hydration Safety, and Analytics.
Feature Flag SDK Specification v1.0
1. Core Concepts & Data Structures
1.1 The Flag Object
The fundamental unit. The SDK must handle primitive types (bool, string, number) and JSON objects.
typescript
type FlagValue = boolean | string | number | object | null;
interface FlagEvaluation {
key: string;
value: FlagValue;
// Determines if the value is "on" or "off" for boolean checks
enabled: boolean;
// CRITICAL for Hydration: The deterministic reason for this result
reason: 'TARGET_MATCH' | 'RULE_MATCH' | 'DEFAULT' | 'ERROR';
// Metadata for analytics
variant?: string;
}
1.2 The Context (User)
The entity used to evaluate flags.
typescript
interface EvaluationContext {
userId?: string;
sessionId?: string;
attributes: Record<string, string | number | boolean>;
// Internal tracking for SSR consistency
_serverRenderedAt?: number;
}
2. SSR Defaults & Hydration Strategy
The core problem in SSR is the "flicker" or Hydration Mismatch: the server renders one state, and the client initializes with a different state before fetching the real flags.
2.1 Server-Side API
The server client performs the actual evaluation logic.
typescript
interface ServerClient {
// Evaluates all flags for a given context
evaluateAll(context: EvaluationContext): Promise<FlagMap>;
// Serializes state to be passed to the client
// Output: JSON string to be injected into HTML <script>
dehydrate(flags: FlagMap): string;
}
2.2 Client-Side API (The "Hydration Safe" Pattern)
The client SDK must be initialized synchronously using data injected by the server. It must not fetch flags from the network before the initial render.
typescript
interface ClientConfig {
// JSON string or Object directly from ServerClient.dehydrate()
// REQUIRED for SSR apps to prevent flicker.
bootstrapData?: string | FlagMap;
}
interface Client {
// Synchronous access. Returns bootstrap value immediately.
getFlag(key: string, defaultValue: FlagValue): FlagEvaluation;
// Asynchronous update. Returns promise that resolves when network flags are fetched.
// UIs should re-render upon resolution, but initial paint uses bootstrap.
flushAndRefresh(): Promise<void>;
}
2.3 Hydration Safety Mechanism
To strictly prevent hydration errors, the SDK exposes a Stable ID generator.
Server: Generates a unique evaluationId based on the hash of the flag state.
Client: Verifies the evaluationId.
Error Handling: If the client detects a mismatch (e.g., bootstrap data missing), it defaults to null or false and logs a severe warning rather than crashing the hydration process.
3. Analytics Beacons
The SDK acts as an emitter for tracking experiments.
3.1 The Exposure Event
When a flag is accessed under specific conditions, an event is fired.
typescript
interface ExposureEvent {
flagKey: string;
value: FlagValue;
variant: string;
context: EvaluationContext;
timestamp: number;
// Used for deduplication
flagInstanceId: string;
}
3.2 Beacon Transport
To ensure analytics do not block the UI thread or the page unload, the SDK must use navigator.sendBeacon (preferred) or a fire-and-forget XMLHttpRequest.
3.3 Configuration
typescript
interface AnalyticsConfig {
// URL to receive beacon payloads
beaconUrl: string;
// Should we track every access, or only the first access per session?
deduplicateStrategy: 'SESSION' | 'PAGE_LOAD' | 'NONE';
// Flushing interval
flushIntervalMs: number;
}
4. Framework Integration (React Example)
This spec defines how the SDK integrates into a UI framework to handle SSR lifecycle.
4.1 The Provider
tsx
interface FlagProviderProps {
// The client instance (initialized with bootstrapData)
client: Client;
children: React.ReactNode;
}
4.2 The Hook API
tsx
function useFlag(key: string, defaultValue: FlagValue): [FlagValue, FlagMeta] {
// 1. Reads from client synchronously.
// 2. Subscribes to updates (if client flushes new data later).
// 3. Triggers "Exposure Event" automatically on mount.
}
Zero Latency Start: The client constructor must not return a Promise. It must be ready to return values instantly using bootstrapData.
Consistency Check: If bootstrapData is provided, the client should treat it as the source of truth until a network request explicitly overwrites it.
Beacon Reliability: Analytics must be sent even if the user closes the tab immediately after the flag renders. (Use visibilitychange or pagehide events to flush buffers).
Tree Shaking: The SDK core must be decoupled from specific analytics providers (Google Analytics, Segment, etc.) to keep bundle size small.