Node.js

Installation and Setup

  1. Install the TypeScript library using your package manager of choice:
$npm install @schematichq/schematic-typescript-node
$# or
$yarn add @schematichq/schematic-typescript-node
$# or
$pnpm add @schematichq/schematic-typescript-node
  1. Issue an API key for the appropriate environment using the Schematic app. Be sure to capture the secret key when you issue the API key; you’ll only see this key once, and this is what you’ll use with schematic-typescript-node.

  2. Using this secret key, initialize a client in your application:

1import { SchematicClient } from "@schematichq/schematic-typescript-node";
2
3const apiKey = process.env.SCHEMATIC_API_KEY;
4const client = new SchematicClient({ apiKey });
5
6// interactions with the client
7
8client.close();

By default, the client will do some local caching for flag checks. If you would like to change this behavior, you can do so using an initialization option to specify the max size of the cache (in terms of number of records) and the max age of the cache (in milliseconds):

1import { LocalCache, SchematicClient, type CheckFlagWithEntitlementResponse } from "@schematichq/schematic-typescript-node";
2
3const apiKey = process.env.SCHEMATIC_API_KEY;
4const cacheSize = 100;
5const cacheTTL = 1000; // in milliseconds
6const client = new SchematicClient({
7 apiKey,
8 cacheProviders: {
9 flagChecks: [new LocalCache<CheckFlagWithEntitlementResponse>({ maxItems: cacheSize, ttl: cacheTTL })],
10 },
11});
12
13// interactions with the client
14
15client.close();

You can also disable local caching entirely with an initialization option; bear in mind that, in this case, every flag check will result in a network request:

1import { SchematicClient } from "@schematichq/schematic-typescript-node";
2
3const apiKey = process.env.SCHEMATIC_API_KEY;
4const client = new SchematicClient({
5 apiKey,
6 cacheProviders: {
7 flagChecks: [],
8 },
9});
10
11// interactions with the client
12
13client.close();

You may want to specify default flag values for your application, which will be used if there is a service interruption or if the client is running in offline mode (see below). You can do this using an initialization option:

1import { SchematicClient } from "@schematichq/schematic-typescript-node";
2
3const apiKey = process.env.SCHEMATIC_API_KEY;
4const client = new SchematicClient({
5 apiKey,
6 flagDefaults: {
7 "some-flag-key": true,
8 },
9});
10
11// interactions with the client
12
13client.close();

Custom Logging

You can provide your own logger implementation to control how the Schematic client logs messages. The logger must implement the Logger interface with error, warn, info, and debug methods:

1import { SchematicClient, Logger } from "@schematichq/schematic-typescript-node";
2
3// Example using a custom logger (could be Winston, Pino, etc.)
4class CustomLogger implements Logger {
5 error(message: string, ...args: any[]): void {
6 // Your custom error logging logic
7 console.error(`[ERROR] ${message}`, ...args);
8 }
9
10 warn(message: string, ...args: any[]): void {
11 // Your custom warning logging logic
12 console.warn(`[WARN] ${message}`, ...args);
13 }
14
15 info(message: string, ...args: any[]): void {
16 // Your custom info logging logic
17 console.info(`[INFO] ${message}`, ...args);
18 }
19
20 debug(message: string, ...args: any[]): void {
21 // Your custom debug logging logic
22 console.debug(`[DEBUG] ${message}`, ...args);
23 }
24}
25
26const apiKey = process.env.SCHEMATIC_API_KEY;
27const client = new SchematicClient({
28 apiKey,
29 logger: new CustomLogger(),
30});
31
32// interactions with the client
33
34client.close();

Example using a popular logging library like Winston:

1import winston from 'winston';
2import { SchematicClient } from "@schematichq/schematic-typescript-node";
3
4// Create a Winston logger instance
5const winstonLogger = winston.createLogger({
6 level: 'debug',
7 format: winston.format.combine(
8 winston.format.timestamp(),
9 winston.format.json()
10 ),
11 transports: [
12 new winston.transports.Console(),
13 ]
14});
15
16const apiKey = process.env.SCHEMATIC_API_KEY;
17const client = new SchematicClient({
18 apiKey,
19 logger: winstonLogger, // Winston logger directly implements the Logger interface
20});
21
22// interactions with the client
23
24client.close();

If no logger is provided, the client uses a default console logger. By default it only emits warn and error messages; debug and info are suppressed to keep production output quiet. Use the logLevel option to raise or lower the verbosity of the default logger:

1import { SchematicClient, LogLevel } from "@schematichq/schematic-typescript-node";
2
3const apiKey = process.env.SCHEMATIC_API_KEY;
4const client = new SchematicClient({
5 apiKey,
6 logLevel: "debug", // or LogLevel.Debug — emit all levels (debug, info, warn, error)
7});

The logLevel option only affects the default console logger. When you supply your own logger, its level configuration is respected as-is and logLevel is ignored.

Usage examples

A number of these examples use keys to identify companies and users. Learn more about keys here.

Sending identify events

Create or update users and companies using identify events.

1import { SchematicClient } from "@schematichq/schematic-typescript-node";
2
3const apiKey = process.env.SCHEMATIC_API_KEY;
4const client = new SchematicClient({ apiKey });
5
6client.identify({
7 company: {
8 keys: { id: "your-company-id" },
9 name: "Acme, Inc.",
10 traits: { city: "Atlanta" },
11 },
12 keys: {
13 email: "wcoyote@acme.net",
14 userId: "your-user-id",
15 },
16 name: "Wile E. Coyote",
17 traits: {
18 enemy: "Bugs Bunny",
19 loginCount: 24,
20 isStaff: false,
21 },
22});
23
24client.close();

This call is non-blocking and there is no response to check.

Sending track events

Track activity in your application using track events; these events can later be used to produce metrics for targeting.

1import { SchematicClient } from "@schematichq/schematic-typescript-node";
2
3const apiKey = process.env.SCHEMATIC_API_KEY;
4const client = new SchematicClient({ apiKey });
5
6client.track({
7 event: "some-action",
8 company: {
9 id: "your-company-id",
10 },
11 user: {
12 email: "wcoyote@acme.net",
13 userId: "your-user-id",
14 },
15});
16
17client.close();

This call is non-blocking and there is no response to check.

If you want to record large numbers of the same event at once, or perhaps measure usage in terms of a unit like tokens or memory, you can optionally specify a quantity for your event:

1client.track({
2 event: "some-action",
3 company: {
4 id: "your-company-id",
5 },
6 user: {
7 email: "wcoyote@acme.net",
8 userId: "your-user-id",
9 },
10 quantity: 10,
11});

Both track and identify accept an optional second argument for event metadata. Supply an idempotencyKey to deduplicate events (duplicates with the same key, scoped to the environment, are dropped server-side for 24 hours):

1client.track(
2 {
3 event: "some-action",
4 company: { id: "your-company-id" },
5 },
6 { idempotencyKey: "your-unique-key" },
7);
8
9client.identify(
10 {
11 keys: { userId: "your-user-id" },
12 name: "Wile E. Coyote",
13 },
14 { idempotencyKey: "your-unique-key" },
15);

For track, you can also set a trusted client clock to use your own timestamp as the effective event time, and backfill historical data without affecting billing. Both require a secret API key:

1client.track(
2 {
3 event: "some-action",
4 company: { id: "your-company-id" },
5 },
6 {
7 sentAt: new Date("2026-01-01T00:00:00Z"),
8 trustedClientClock: true,
9 backfill: true,
10 },
11);

Creating and updating companies

Although it is faster to create companies and users via identify events, if you need to handle a response, you can use the companies API to upsert companies. Because you use your own identifiers to identify companies, rather than a Schematic company ID, creating and updating companies are both done via the same upsert operation:

1import { SchematicClient } from "@schematichq/schematic-typescript-node";
2
3const apiKey = process.env.SCHEMATIC_API_KEY;
4const client = new SchematicClient({ apiKey });
5
6const body = {
7 keys: {
8 id: "your-company-id",
9 },
10 name: "Acme Widgets, Inc.",
11 traits: {
12 city: "Atlanta",
13 highScore: 25,
14 isActive: true,
15 },
16};
17
18client.companies
19 .upsertCompany(body)
20 .then((response) => {
21 console.log(response.data);
22 })
23 .catch(console.error);
24
25client.close();

You can define any number of company keys; these are used to address the company in the future, for example by updating the company’s traits or checking a flag for the company.

You can also define any number of company traits; these can then be used as targeting parameters.

Creating and updating users

Similarly, you can upsert users using the Schematic API, as an alternative to using identify events. Because you use your own identifiers to identify users, rather than a Schematic user ID, creating and updating users are both done via the same upsert operation:

1import { SchematicClient } from "@schematichq/schematic-typescript-node";
2
3const apiKey = process.env.SCHEMATIC_API_KEY;
4const client = new SchematicClient({ apiKey });
5
6const body = {
7 keys: {
8 email: "wcoyote@acme.net",
9 userId: "your-user-id",
10 },
11 company: { id: "your-company-id" },
12 name: "Wile E. Coyote",
13 traits: {
14 city: "Atlanta",
15 loginCount: 24,
16 isStaff: false,
17 },
18};
19
20client.companies
21 .upsertUser(body)
22 .then((response) => {
23 console.log(response.data);
24 })
25 .catch(console.error);
26
27client.close();

You can define any number of user keys; these are used to address the user in the future, for example by updating the user’s traits or checking a flag for the user.

You can also define any number of user traits; these can then be used as targeting parameters.

Checking flags

When checking a flag, you’ll provide keys for a company and/or keys for a user. You can also provide no keys at all, in which case you’ll get the default value for the flag.

1import { SchematicClient } from "@schematichq/schematic-typescript-node";
2
3const apiKey = process.env.SCHEMATIC_API_KEY;
4const client = new SchematicClient({ apiKey });
5
6const evaluationCtx = {
7 company: { id: "your-company-id" },
8 user: {
9 email: "wcoyote@acme.net",
10 userId: "your-user-id",
11 },
12};
13
14client
15 .checkFlag(evaluationCtx, "some-flag-key")
16 .then((isFlagOn) => {
17 if (isFlagOn) {
18 // Flag is on
19 } else {
20 // Flag is off
21 }
22 })
23 .catch(console.error);
24
25client.close();

Checking flags with entitlement details

If you need more detail about how a flag check was resolved, including any entitlement associated with the check, use checkFlagWithEntitlement. This returns a response object with the flag value, the reason for the evaluation result, and entitlement details such as usage, allocation, and credit balances when applicable.

1import { SchematicClient } from "@schematichq/schematic-typescript-node";
2
3const apiKey = process.env.SCHEMATIC_API_KEY;
4const client = new SchematicClient({ apiKey });
5
6const evaluationCtx = {
7 company: { id: "your-company-id" },
8 user: {
9 email: "wcoyote@acme.net",
10 userId: "your-user-id",
11 },
12};
13
14client
15 .checkFlagWithEntitlement(evaluationCtx, "some-flag-key")
16 .then((resp) => {
17 console.log(`Flag: ${resp.flagKey}, Value: ${resp.value}, Reason: ${resp.reason}`);
18
19 if (resp.entitlement) {
20 console.log(`Entitlement type: ${resp.entitlement.valueType}`);
21 console.log(`Usage: ${resp.entitlement.usage}, Allocation: ${resp.entitlement.allocation}`);
22 console.log(`Credit remaining: ${resp.entitlement.creditRemaining}`);
23 }
24 })
25 .catch(console.error);
26
27client.close();

Checking multiple flags

The checkFlags method allows you to efficiently check multiple feature flags in a single operation. When you provide specific flag keys, it will only return the flag values for those flags, leveraging intelligent caching to minimize API calls.

1import { SchematicClient } from "@schematichq/schematic-typescript-node";
2
3const apiKey = process.env.SCHEMATIC_API_KEY;
4const client = new SchematicClient({ apiKey });
5
6const evaluationCtx = {
7 company: { id: "your-company-id" },
8};
9
10// Check specific flags by providing an array of flag keys
11client
12 .checkFlags(evaluationCtx, ["feature-flag-1", "feature-flag-2", "feature-flag-3"])
13 .then((flagResults) => {
14 flagResults.forEach((result) => {
15 console.log(`Flag ${result.flag}: ${result.value} (${result.reason})`);
16 if (result.value) {
17 // This flag is enabled
18 } else {
19 // This flag is disabled
20 }
21 });
22 })
23 .catch(console.error);
24
25// Or check all available flags by omitting the keys parameter
26client
27 .checkFlags(evaluationCtx)
28 .then((flagResults) => {
29 flagResults.forEach((result) => {
30 console.log(`Flag ${result.flag}: ${result.value}`);
31 });
32 })
33 .catch(console.error);
34
35client.close();

Other API operations

The Schematic API supports many operations beyond these, accessible via the API modules on the client, Accounts, Billing, Companies, Entitlements, Events, Features, and Plans.

Webhook Verification

Schematic can send webhooks to notify your application of events. To ensure the security of these webhooks, Schematic signs each request using HMAC-SHA256. The SDK provides utility functions to verify these signatures.

Verifying Webhook Signatures

When your application receives a webhook request from Schematic, you should verify its signature to ensure it’s authentic. The SDK provides simple functions to verify webhook signatures. Here’s how to use them in different frameworks:

Express

1import express from "express";
2import {
3 verifyWebhookSignature,
4 WebhookSignatureError,
5 WEBHOOK_SIGNATURE_HEADER,
6 WEBHOOK_TIMESTAMP_HEADER,
7} from "@schematichq/schematic-typescript-node";
8
9// Note: Schematic webhooks use these headers:
10// - X-Schematic-Webhook-Signature: Contains the HMAC-SHA256 signature
11// - X-Schematic-Webhook-Timestamp: Contains the timestamp when the webhook was sent
12
13const app = express();
14
15// Use a middleware that captures raw body for signature verification
16app.use(
17 "/webhooks/schematic",
18 express.json({
19 verify: (req, res, buf) => {
20 if (buf && buf.length) {
21 (req as any).rawBody = buf;
22 }
23 },
24 })
25);
26
27app.post("/webhooks/schematic", (req, res) => {
28 try {
29 const webhookSecret = "your-webhook-secret"; // Get this from the Schematic app
30
31 // Verify the webhook signature using the captured raw body
32 verifyWebhookSignature(req, webhookSecret);
33
34 // Process the webhook payload
35 const data = req.body;
36 console.log("Webhook verified:", data);
37
38 res.status(200).end();
39 } catch (error) {
40 if (error instanceof WebhookSignatureError) {
41 console.error("Webhook verification failed:", error.message);
42 return res.status(400).json({ error: error.message });
43 }
44
45 console.error("Error processing webhook:", error);
46 res.status(500).json({ error: "Internal server error" });
47 }
48});
49
50const PORT = 3000;
51app.listen(PORT, () => {
52 console.log(`Server running on port ${PORT}`);
53});

Node HTTP Server

1import http from "http";
2import {
3 verifySignature,
4 WebhookSignatureError,
5 WEBHOOK_SIGNATURE_HEADER,
6 WEBHOOK_TIMESTAMP_HEADER,
7} from "@schematichq/schematic-typescript-node";
8
9const webhookSecret = "your-webhook-secret"; // Get this from the Schematic app
10
11const server = http.createServer(async (req, res) => {
12 if (req.url === "/webhooks/schematic" && req.method === "POST") {
13 // Collect the request body
14 let body = "";
15 for await (const chunk of req) {
16 body += chunk.toString();
17 }
18
19 try {
20 // Get the headers
21 const signature = req.headers[WEBHOOK_SIGNATURE_HEADER.toLowerCase()] as string;
22 const timestamp = req.headers[WEBHOOK_TIMESTAMP_HEADER.toLowerCase()] as string;
23
24 // Verify the signature
25 verifySignature(body, signature, timestamp, webhookSecret);
26
27 // Process the webhook payload
28 const data = JSON.parse(body);
29 console.log("Webhook verified:", data);
30
31 res.statusCode = 200;
32 res.end();
33 } catch (error) {
34 if (error instanceof WebhookSignatureError) {
35 console.error("Webhook verification failed:", error.message);
36 res.statusCode = 400;
37 res.end(JSON.stringify({ error: error.message }));
38 return;
39 }
40
41 console.error("Error processing webhook:", error);
42 res.statusCode = 500;
43 res.end(JSON.stringify({ error: "Internal server error" }));
44 }
45 } else {
46 res.statusCode = 404;
47 res.end();
48 }
49});
50
51const PORT = 3000;
52server.listen(PORT, () => {
53 console.log(`Server running on port ${PORT}`);
54});

Next.js API Routes

1// pages/api/webhooks/schematic.ts
2import type { NextApiRequest, NextApiResponse } from "next";
3import {
4 verifyWebhookSignature,
5 WebhookSignatureError,
6 WEBHOOK_SIGNATURE_HEADER,
7 WEBHOOK_TIMESTAMP_HEADER,
8} from "@schematichq/schematic-typescript-node";
9import { buffer } from "micro";
10
11// Schematic webhooks use these headers:
12// - X-Schematic-Webhook-Signature: Contains the HMAC-SHA256 signature
13// - X-Schematic-Webhook-Timestamp: Contains the timestamp when the webhook was sent
14
15// Disable body parsing to get the raw body
16export const config = {
17 api: {
18 bodyParser: false,
19 },
20};
21
22export default async function handler(req: NextApiRequest, res: NextApiResponse) {
23 if (req.method !== "POST") {
24 return res.status(405).end("Method not allowed");
25 }
26
27 try {
28 const webhookSecret = process.env.SCHEMATIC_WEBHOOK_SECRET!;
29 const rawBody = await buffer(req);
30
31 // Verify the webhook signature
32 verifyWebhookSignature(req, webhookSecret, rawBody);
33
34 // Parse the webhook payload
35 const payload = JSON.parse(rawBody.toString());
36 console.log("Webhook verified:", payload);
37
38 // Process the webhook event
39 // ...
40
41 res.status(200).end();
42 } catch (error) {
43 if (error instanceof WebhookSignatureError) {
44 console.error("Webhook verification failed:", error.message);
45 return res.status(400).json({ error: error.message });
46 }
47
48 console.error("Error processing webhook:", error);
49 res.status(500).json({ error: "Internal server error" });
50 }
51}

Caching

Local Caching

By default, the client will do some local caching for flag checks. You can customize this behavior by specifying the max size of the cache and the max age of the cache (in milliseconds) as shown in the setup section above.

Cloudflare KV Caching

If you’re using Cloudflare Workers, you can leverage Cloudflare’s KV storage for caching flag check results. This provides a more persistent and distributed cache compared to the local in-memory cache.

To use Cloudflare KV caching, you’ll need to install the Cloudflare adapter package:

$npm install @schematichq/schematic-typescript-cloudflare
$# or
$yarn add @schematichq/schematic-typescript-cloudflare
$# or
$pnpm add @schematichq/schematic-typescript-cloudflare

Then, in your Cloudflare Worker, you can set up the client with KV caching:

1import { SchematicClient } from "@schematichq/schematic-typescript-node";
2import { CloudflareKVCache } from "@schematichq/schematic-typescript-cloudflare";
3
4// Inside a Cloudflare Worker
5export default {
6 async fetch(request, env, ctx) {
7 // Create a CloudflareKVCache instance
8 const cache = new CloudflareKVCache<boolean>(env.MY_KV_NAMESPACE, {
9 ttl: 1000 * 60 * 60, // 1 hour cache TTL
10 keyPrefix: 'schematic:', // Optional prefix for KV keys
11 });
12
13 // Initialize Schematic with the KV cache
14 const schematic = new SchematicClient({
15 apiKey: env.SCHEMATIC_API_KEY,
16 cacheProviders: {
17 flagChecks: [cache],
18 }
19 });
20
21 // Your application logic...
22 // ...
23
24 // Don't forget to close the client when done
25 schematic.close();
26 }
27};

The CloudflareKVCache constructor accepts the following options:

  • ttl: Time-to-live for cache entries in milliseconds (default: 5000ms)
  • keyPrefix: Prefix to add to all KV keys (default: ‘schematic:’)

With this setup, flag check results will be cached in your Cloudflare KV namespace, allowing for persistence across worker invocations and global distribution of your cache.

DataStream

DataStream enables local flag evaluation by maintaining a WebSocket connection to Schematic and caching flag rules, company, and user data locally.

Runtime compatibility: DataStream requires Node.js APIs (WebSocket, EventEmitter) and is not supported in edge runtimes such as Cloudflare Workers, Vercel Edge Functions, or Deno Deploy. For these runtimes, use Replicator Mode instead.

Setup

1import { SchematicClient } from "@schematichq/schematic-typescript-node";
2
3const client = new SchematicClient({
4 apiKey: process.env.SCHEMATIC_API_KEY,
5 useDataStream: true,
6});
7
8// Flag checks are now evaluated locally
9const flagValue = await client.checkFlag(
10 { company: { id: "your-company-id" } },
11 "some-flag-key",
12);
13
14client.close();

Configuration options

OptionTypeDefaultDescription
cacheTTLnumber24 hoursCache TTL in milliseconds
redisClientRedisClientRedis client for shared caching (uses in-memory cache if not provided)
redisKeyPrefixstringschematic:Key prefix for Redis cache entries
1import { createClient } from "redis";
2import { SchematicClient } from "@schematichq/schematic-typescript-node";
3
4const redisClient = createClient({ url: "redis://localhost:6379" });
5await redisClient.connect();
6
7const client = new SchematicClient({
8 apiKey: process.env.SCHEMATIC_API_KEY,
9 useDataStream: true,
10 dataStream: {
11 redisClient,
12 redisKeyPrefix: "schematic:",
13 cacheTTL: 60 * 60 * 1000, // 1 hour
14 },
15});

Replicator Mode

Replicator mode is designed for environments where a separate process (the replicator) manages the WebSocket connection and populates a shared cache. The SDK reads from that cache and evaluates flags locally without establishing its own WebSocket connection.

Requirements

Replicator mode requires a shared cache (Redis or custom cache providers) so the SDK can read data written by the external replicator process.

Setup

1import { createClient } from "redis";
2import { SchematicClient } from "@schematichq/schematic-typescript-node";
3
4const redisClient = createClient({ url: "redis://localhost:6379" });
5await redisClient.connect();
6
7const client = new SchematicClient({
8 apiKey: process.env.SCHEMATIC_API_KEY,
9 useDataStream: true,
10 dataStream: {
11 replicatorMode: true,
12 redisClient,
13 replicatorHealthURL: "http://localhost:8080/health",
14 replicatorHealthCheck: 30000, // 30 seconds
15 },
16});

Configuration options

OptionTypeDefaultDescription
replicatorModebooleanfalseEnable replicator mode
redisClientRedisClientRequired. Redis client for reading from the shared cache
redisKeyPrefixstringschematic:Key prefix for Redis cache entries
replicatorHealthURLstringURL to poll for replicator health status
replicatorHealthChecknumber30000Health check polling interval in milliseconds
cacheTTLnumber24 hoursCache TTL in milliseconds

Credit Leases and Reservations

For features metered by credit burndown (e.g. inference tokens), the SDK can enforce credit balances locally — without a Schematic API call on every check — using a lease-and-reservation system:

  • A lease is a tranche of credits acquired transactionally from Schematic’s API. It functions as a hold against the company’s credit balance until it is consumed, released, or expires.
  • A reservation is a client-side hold carved out of the lease at check time, sized to the upper bound of the operation’s usage. This protects against races and over-spend between the check and the eventual usage report.
  • When the work completes, a track call reports actual usage; the difference between reserved and actual usage is refunded to the lease.

Requirements: Credit leases require DataStream (or Replicator Mode) — lease-bearing checks are evaluated locally against cached flag and company state. In a horizontally-scaled deployment, a shared Redis backend is also required so that all SDK instances gate against the same lease balance; without one, lease state is per-process.

Setup

1import { createClient } from "redis";
2import { SchematicClient } from "@schematichq/schematic-typescript-node";
3
4const redisClient = createClient({ url: "redis://localhost:6379" });
5await redisClient.connect();
6
7const client = new SchematicClient({
8 apiKey: process.env.SCHEMATIC_API_KEY,
9 useDataStream: true,
10 dataStream: {
11 redisClient, // also backs lease + reservation state automatically
12 },
13 creditLeases: {
14 defaultLeaseDuration: 5 * 60 * 1000, // lease lifetime (ms)
15 defaultReservationTTL: 60 * 1000, // how long a reservation is held if not settled by a track (ms)
16 defaultLeaseSize: 10_000, // credits requested per lease
17 lowWaterMark: 0.25, // extend the lease in the background when its balance dips below this fraction
18 },
19});

When dataStream.redisClient is configured, lease and reservation state automatically lives in the same Redis, with atomic reservations driven by Lua scripts — no additional configuration needed. To point lease state at a different Redis, set creditLeases.redisClient explicitly.

Checking and tracking

check() reserves the operation’s upper-bound usage against the lease and returns a reservation handle; trackWithReservation() settles it with actual usage:

1// Per-request: reserve up to maxTokens against the lease.
2const result = await client.check(
3 { company: { id: "your-company-id" } },
4 "inference",
5 {
6 usage: maxTokens, // upper bound for this operation
7 eventSubtype: "inference_tokens", // the metered event
8 },
9);
10if (!result.allowed) {
11 throw new Error("credit balance exceeded");
12}
13
14const inference = await runInference(/* ... */);
15
16// Report actual usage; the unused slice of the reservation is refunded to the lease.
17await client.trackWithReservation(result.reservation!, inference.tokensUsed);

If the caller never settles a reservation, it expires after defaultReservationTTL and its credits are returned to the lease. If the work outlives the reservation’s TTL, trackWithReservation still bills the usage — the track event carries a deterministic idempotency key, so duplicate or recovery emits never double-bill. However, the local lease balance is not re-debited on that late settle (the expired reservation’s hold was already swept back to the lease), so it reads high until the lease rolls over. Set defaultReservationTTL above the longest expected gap between check() and trackWithReservation() to keep the local balance accurate.

Pre-warming

To avoid paying the lease-acquire round trip on a session’s first check, pre-warm leases when the user is identified:

1await client.identify(
2 {
3 keys: { userId: "your-user-id" },
4 company: { keys: { id: "your-company-id" } },
5 },
6 { prewarm: ["credit-type-id"] }, // credit type IDs to acquire leases for
7);

Or call client.prewarm(evalCtx, creditTypeIds) directly.

Failure behavior

By default, a check that cannot be gated (API unreachable, Redis down, lease exhausted) fails closed (allowed: false). Override per check for callers where letting traffic through is preferable to a denial:

1const result = await client.check(evalCtx, "inference", {
2 usage: maxTokens,
3 eventSubtype: "inference_tokens",
4 onAcquireFailure: "fail-open",
5});

fail-open does not skip evaluation: the flag’s rules still run with the credit balance assumed sufficient, so plan targeting, overrides, and all non-credit conditions still apply — only the credit gate is bypassed.

Configuration options

OptionTypeDefaultDescription
defaultLeaseDurationnumber5 minutesLease lifetime in milliseconds
defaultReservationTTLnumber60 secondsHow long an unsettled reservation is held (ms); set above your longest expected work duration
defaultLeaseSizenumber10000Credits requested per lease acquire/extend
lowWaterMarknumber0.25Extend in the background when the lease balance dips below this fraction
sweepIntervalMsnumber1000Sweep interval for expired reservations (ms)
redisClientRedisClientdataStream.redisClientRedis client for lease + reservation state
redisKeyPrefixstringdataStream.redisKeyPrefixKey prefix for lease + reservation keys
overridesobjectPer-credit-type overrides of the above (keyed by credit type ID)

Testing

Offline mode

In development or testing environments, you may want to avoid making network requests to the Schematic API. You can run Schematic in offline mode by specifying the offline option; in this case, it does not matter what API key you specify:

1import { SchematicClient } from "@schematichq/schematic-typescript-node";
2
3const client = new SchematicClient({ offline: true });
4
5client.close();

Offline mode works well with flag defaults:

1import { SchematicClient } from "@schematichq/schematic-typescript-node";
2
3const client = new SchematicClient({
4 flagDefaults: { "some-flag-key": true },
5 offline: true,
6});
7
8// interactions with the client
9
10client.close();