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 } 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<boolean>({ 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();

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});

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();

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}

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();