@happycatlabs/superflag-node
v0.5.0
Published
Portable server-side feature flag SDK for Superflag
Maintainers
Readme
@happycatlabs/superflag-node
npm scope migration
This package replaces @superflag-sh/node. Existing installs of the old
package remain available and unchanged. To opt in, replace the dependency and
its imports with @happycatlabs/superflag-node; exported APIs and subpaths
stay the same. Keys, flags, configuration, and stored application data do not change.
Portable server-side feature flags for Node.js, Bun, Deno, Next.js, Vercel,
Cloudflare Workers, and other runtimes with standard fetch and
AbortController APIs.
import { createSuperflag } from "@happycatlabs/superflag-node";
const flags = createSuperflag({
apiKey: process.env.SUPERFLAG_API_KEY!,
});
if (await flags.isEnabled("new-checkout")) {
// New server behavior
}Use an environment-scoped sdk_ server key. Never expose this key through an
EXPO_PUBLIC_*, NEXT_PUBLIC_*, browser bundle, mobile app, or client response.
API
await flags.isEnabled("boolean-flag"); // safe fallback: false
await flags.getString("copy", "Default copy");
await flags.getNumber("limit", 10);
await flags.getJson("policy", { mode: "safe" });
const result = await flags.details("boolean-flag", false, {
targetingKey: user.id,
attributes: { plan: user.plan },
});
await flags.refresh();
await flags.track("new-checkout", "purchase", 42, {
context: { targetingKey: user.id },
});
await flags.flush();
await flags.flush({ timeoutMs: 1_000 }); // { status: "completed" | "timed_out" | "closed", ... }
flags.subscribe((state) => {
observability.emit("superflag-state", state.status);
});
flags.getState();Reads lazily fetch the server configuration, coalesce concurrent first reads,
evaluate locally through @happycatlabs/superflag-core, and return their fallback on
network, authorization, schema, or evaluation failures. Reads do not throw.
Constructor validation does throw for developer mistakes such as a missing
sdk_ key or invalid endpoint.
endpoint and an injected fetch are credential-bearing interfaces: both
receive the complete sdk_ bearer key. They must be fixed trusted
infrastructure, never request- or user-controlled, and must not log, persist,
or forward authorization headers. A custom fetch must pass init.signal to
its underlying request; otherwise requestTimeoutMs cannot abort in-flight
work. Custom endpoints require HTTPS. A loopback HTTP endpoint can be enabled
only for local development:
const localFlags = createSuperflag({
apiKey: process.env.SUPERFLAG_API_KEY!,
endpoint: "http://127.0.0.1:3000/api/v1/advanced-config",
allowInsecureHttpForLocalDevelopment: true,
});The client keeps an in-memory, endpoint/key/source-bound last-known-good config.
It honors the server TTL and ETag, revalidates stale data in the background,
and bounds stale fallback with maxStaleAgeSeconds. A 401 or 403 clears the
cache immediately. A 429 honors a bounded Retry-After or applies a safe
default backoff when the header is absent. Public values, details, diagnostics,
and state are detached from the internal cache. No key, context, or raw
configuration is persisted.
Targeting contexts
Context is optional for a global flag. A missing context uses the stable
{ targetingKey: "server" } subject so the zero-boilerplate example works.
That means a percentage rollout without an explicit context assigns the entire
service instance to one cohort. Pass a request identity when you need per-user,
per-organization, or per-request targeting:
await flags.isEnabled("new-checkout", {
targetingKey: organization.id,
attributes: { plan: organization.plan },
});Superflag's environment privacy allow-list is applied before local evaluation; attributes not explicitly allowed by the server are discarded.
Operational telemetry
Telemetry is opt-in through a canonical event callback or transport. Node emits
schema-v2 decision events with bounded evaluationOrigin (remote,
cache_fresh, or provable cache_stale) and fallbackClass. The origin and
fallback are captured when evaluation completes, before asynchronous identity
work. maxQueueSize also bounds identity work waiting to enter the canonical
queue. Reads never await telemetry. A read without a usable config emits no
event because source and config-version provenance cannot be invented.
const flags = createSuperflag({
apiKey: process.env.SUPERFLAG_API_KEY!,
telemetry: {
pseudonymize: async ({ targetingKey, namespace, state }) =>
identityService.pseudonymize({ targetingKey, namespace, state }),
transport: featureEventTransport,
},
});
await flags.flush();
await flags.shutdown();The required pseudonymizer is the only telemetry hook that receives a raw
targeting key. It must return an application-scoped psn_... subject and must
not log, persist, or emit its input. Events contain no context attributes, SDK
keys, evaluated values, metadata, errors, or stacks. Old schema-v1 producers
remain accepted by ingestion and aggregate into the documented unknown
operational buckets.
Serverless and edge runtimes
Create one client at module scope. The package has no filesystem dependency,
background interval, process hook, or Node built-in import. It uses
request-scoped timers for timeouts and retries, plus one opt-in telemetry queue
timer (flushIntervalMs) while events are queued. That timer is unref'd where
supported and is not a delivery guarantee. An injected fetch supports tests
or custom runtimes.
const flags = createSuperflag({
apiKey: env.SUPERFLAG_API_KEY,
requestTimeoutMs: 1_500,
maxRetries: 1,
onDiagnostic(event) {
observability.emit("superflag", event);
},
});Diagnostics contain bounded operational metadata only. They never contain the API key, evaluation context, flag value, or complete configuration.
To deliver telemetry from a serverless handler, flush with a deadline after the response instead of shutting the client down:
import { waitUntil } from "@vercel/functions";
import { createSuperflag } from "@happycatlabs/superflag-node";
// Module scope: warm invocations reuse the client, cache, and queue.
const flags = createSuperflag({
apiKey: process.env.SUPERFLAG_API_KEY!,
telemetry: { pseudonymize, transport: featureEventTransport },
});
export async function POST(request: Request) {
const session = await authenticate(request);
const enabled = await flags.isEnabled("new-server-path", {
targetingKey: session.organizationId,
});
const response = enabled
? await newPath(request)
: await currentPath(request);
// Wait at most 1 second after the response. Never shut down a shared client here.
waitUntil(flags.flush({ timeoutMs: 1_000 }));
return response;
}flush({ timeoutMs }) bounds the caller's wait, not the work: it never cancels
a send, closes the client, or drops events, and resolves completed,
timed_out, or closed. completed means one flush attempt settled, not that
events were delivered. waitUntil or Next.js after() can still add up to
timeoutMs of billable duration, transports need their own request deadline
(a hung transport stays stuck until shutdown()), and delivery stays best
effort. Call shutdown() only when the process is ending.
OpenFeature
@happycatlabs/superflag-node/openfeature is the networked OpenFeature server provider.
It uses this SDK's authenticated sync, cache, privacy allow-list, fallbacks,
and feature-scoped outcomes, then evaluates through @happycatlabs/superflag-core.
import { OpenFeature } from "@openfeature/server-sdk";
import { createSuperflag } from "@happycatlabs/superflag-node";
import { createOpenFeatureProvider } from "@happycatlabs/superflag-node/openfeature";
const flags = createSuperflag({
apiKey: process.env.SUPERFLAG_API_KEY!,
});
await OpenFeature.setProviderAndWait(createOpenFeatureProvider(flags));
const client = OpenFeature.getClient();
await client.getBooleanValue("new-checkout", false, {
targetingKey: user.id,
plan: user.plan,
});
client.track(
"purchase",
{ targetingKey: user.id },
{
flagKey: "new-checkout",
value: 42,
},
);
await OpenFeature.clearProviders();Install @openfeature/server-sdk next to this package. The adapter never
imports it at runtime.
| Surface | Use it when |
| ------------------------------------------ | -------------------------------------------------------- |
| @happycatlabs/superflag-node | Native Superflag server API, including track |
| @happycatlabs/superflag-node/openfeature | Dynamic OpenFeature provider over that networked SDK |
| @happycatlabs/superflag-core/openfeature | Static OpenFeature adapter for a config you already have |
| /api/ofrep/v1 | Remote evaluation without a local SDK |
OpenFeature track() records a versioned feature metric only. flagKey is
required. It attaches to the latest successful evaluation for that flag and
targeting key, emits at most one exposure for that evaluation, and no-ops with
a track_dropped diagnostic when telemetry is off, the metric is invalid, or
no prior evaluation exists. It never invents an exposure to attach an outcome.
Provider events map READY, STALE, ERROR, and configuration-changed onto this
client's cache lifecycle. Pass evaluation time as superflag.now; a targeting
attribute named now is not reserved. Multi-provider routing stays with the
OpenFeature SDK.
Core package distinction
@happycatlabs/superflag-core/node is a pure helper for callers that already possess a
config. This package, @happycatlabs/superflag-node, is the networked server SDK: it owns
authenticated config sync, TTL/ETag caching, failure policy, and diagnostics,
then delegates all evaluation semantics to core.
