Gathering detailed insights and metrics for @bucketco/node-sdk
Gathering detailed insights and metrics for @bucketco/node-sdk
Gathering detailed insights and metrics for @bucketco/node-sdk
Gathering detailed insights and metrics for @bucketco/node-sdk
npm install @bucketco/node-sdk
Typescript
Module System
Node Version
NPM Version
72.6
Supply Chain
98.6
Quality
91.1
Maintenance
100
Vulnerability
100
License
TypeScript (93.33%)
CSS (3.88%)
JavaScript (2%)
HTML (0.79%)
Total Downloads
12,242
Last Day
21
Last Week
788
Last Month
4,357
Last Year
12,242
7 Stars
298 Commits
2 Forks
1 Watching
28 Branches
8 Contributors
Latest Version
1.4.3
Package Id
@bucketco/node-sdk@1.4.3
Unpacked Size
135.27 kB
Size
31.64 kB
File Count
32
NPM Version
lerna/8.1.3/node@v20.15.1+x64 (linux)
Node Version
20.15.1
Publised On
21 Nov 2024
Cumulative downloads
Total Downloads
Last day
-90.6%
21
Compared to previous day
Last week
-22.8%
788
Compared to previous week
Last month
11.3%
4,357
Compared to previous month
Last year
0%
12,242
Compared to previous year
Node.js, JavaScriptS/Typescript feature flag and tracking client for Bucket.co.
Install using yarn
or npm
with:
yarn add -s @bucketco/node-sdk
ornpm install -s @bucketco/node-sdk
.
Other supported languages/frameworks are in the Supported languages documentation pages.
You can also use the HTTP API directly
To get started you need to obtain your secret key from the environment settings in Bucket.
[!CAUTION] Secret keys are meant for use in server side SDKs only. Secret keys offer the users the ability to obtain information that is often sensitive and thus should not be used in client-side applications.
Bucket will load settings through the various environment variables automatically (see Configuring below).
BUCKET_SECRET_KEY
in your .env
filebucket.ts
file containing the following:1import { BucketClient } from "@bucketco/node-sdk"; 2 3// Create a new instance of the client with the secret key. Additional options 4// are available, such as supplying a logger and other custom properties. 5// 6// We recommend that only one global instance of `client` should be created 7// to avoid multiple round-trips to our servers. 8export const bucketClient = new BucketClient(); 9 10// Initialize the client and begin fetching feature targeting definitions. 11// You must call this method prior to any calls to `getFeatures()`, 12// otherwise an empty object will be returned. 13bucketClient.initialize().then({ 14 console.log("Bucket initialized!") 15})
Once the client is initialized, you can obtain features along with the isEnabled
status to indicate whether the feature is targeted for this user/company:
Note: If user.id
or company.id
is not given, the whole user
or company
object is ignored.
1// configure the client 2const boundClient = bucketClient.bindClient({ 3 user: { 4 id: "john_doe", 5 name: "John Doe", 6 email: "john@acme.com", 7 }, 8 company: { 9 id: "acme_inc", 10 name: "Acme, Inc.", 11 }, 12}); 13 14// get the huddle feature using company, user and custom context to 15// evaluate the targeting. 16const { isEnabled, track } = boundClient.getFeature("huddle"); 17 18if (isEnabled) { 19 // this is your feature gated code ... 20 // send an event when the feature is used: 21 track(); 22 23 // CAUTION: if you plan to use the event for automated feedback surveys 24 // call `flush` immediately after `track`. It can optionally be awaited 25 // to guarantee the sent happened. 26 boundClient.flush(); 27}
You can also use the getFeatures()
method which returns a map of all features:
1// get the current features (uses company, user and custom context to 2// evaluate the features). 3const features = boundClient.getFeatures(); 4const bothEnabled = 5 features.huddle?.isEnabled && features.voiceHuddle?.isEnabled;
The Bucket Node SDK contacts the Bucket servers when you call initialize()
and downloads the features with their targeting rules.
These rules are then matched against the user/company information you provide
to getFeatures()
(or through bindClient(..).getFeatures()
). That means the
getFeatures()
call does not need to contact the Bucket servers once
initialize()
has completed. BucketClient
will continue to periodically
download the targeting rules from the Bucket servers in the background.
The Bucket Node.js
SDK can be configured through environment variables,
a configuration file on disk or by passing options to the BucketClient
constructor. By default, the SDK searches for bucketConfig.json
in the
current working directory.
Option | Type | Description | Env Var |
---|---|---|---|
secretKey | string | The secret key used for authentication with Bucket's servers. | BUCKET_SECRET_KEY |
logLevel | string | The log level for the SDK (e.g., "DEBUG" , "INFO" , "WARN" , "ERROR" ). Default: INFO | BUCKET_LOG_LEVEL |
offline | boolean | Operate in offline mode. Default: false , except in tests it will default to true based off of the TEST env. var. | BUCKET_OFFLINE |
host | string | The host URL for the Bucket servers. | BUCKET_HOST |
featureOverrides | Record<string, boolean> | An object specifying feature overrides for testing or local development. See example/app.test.ts for how to use featureOverrides in tests. | BUCKET_FEATURES_ENABLED, BUCKET_FEATURES_DISABLED |
configFile | string | Load this config file from disk. Default: bucketConfig.json | BUCKET_CONFIG_FILE |
Note: BUCKET_FEATURES_ENABLED, BUCKET_FEATURES_DISABLED are comma separated lists of features which will be enabled or disabled respectively.
bucketConfig.json
example:
1{ 2 secretKey: "...", 3 logLevel: "warn", 4 offline: true, 5 host: "https://proxy.slick-demo.com" 6 featureOverrides: { 7 huddles: true, 8 voiceChat: false 9 }, 10}
When using a bucketConfig.json
for local development, make sure you add it to your
.gitignore
file. You can also set these options directly in the BucketClient
constructor. The precedence for configuration options is as follows, listed in the
order of importance:
To get type checked feature flags, add the list of flags to your bucket.ts
file.
Any feature look ups will now be checked against the list you maintain.
1import { BucketClient } from "@bucketco/node-sdk"; 2 3// Extending the Features interface to define the available features 4declare module "@bucketco/node-sdk" { 5 interface Features { 6 "show-todos": boolean; 7 "create-todos": boolean; 8 "delete-todos": boolean; 9 } 10} 11 12export const bucketClient = new BucketClient(); 13 14bucketClient.initialize().then({ 15 console.log("Bucket initialized!") 16 bucketClient.getFeature("invalid-feature") // feature doesn't exist 17}) 18
A popular way to integrate the Bucket Node.js SDK is through an express middleware.
1import bucket from "./bucket"; 2import express from "express"; 3import { BoundBucketClient } from "@bucketco/node-sdk"; 4 5// Augment the Express types to include a `boundBucketClient` property on the 6// `res.locals` object. 7// This will allow us to access the BucketClient instance in our route handlers 8// without having to pass it around manually 9declare global { 10 namespace Express { 11 interface Locals { 12 boundBucketClient: BoundBucketClient; 13 } 14 } 15} 16 17// Add express middleware 18app.use((req, res, next) => { 19 // Extract the user and company IDs from the request 20 // You'll want to use a proper authentication and identification 21 // mechanism in a real-world application 22 const user = { 23 id: req.user?.id, 24 name: req.user?.name 25 email: req.user?.email 26 } 27 28 const company = { 29 id: req.user?.companyId 30 name: req.user?.companyName 31 } 32 33 // Create a new BoundBucketClient instance by calling the `bindClient` 34 // method on a `BucketClient` instance 35 // This will create a new instance that is bound to the user/company given. 36 const boundBucketClient = bucket.bindClient({ user, company }); 37 38 // Store the BoundBucketClient instance in the `res.locals` object so we 39 // can access it in our route handlers 40 res.locals.boundBucketClient = boundBucketClient; 41 next(); 42}); 43 44// Now use res.locals.boundBucketClient in your handlers 45app.get("/todos", async (_req, res) => { 46 const { track, isEnabled } = res.locals.bucketUser.getFeature("show-todos"); 47 48 if (!isEnabled) { 49 res.status(403).send({"error": "feature inaccessible"}) 50 return 51 } 52 53 ... 54}
See example/app.ts for a full example.
If you don't want to provide context each time when evaluating feature flags but
rather you would like to utilise the attributes you sent to Bucket previously
(by calling updateCompany
and updateUser
) you can do so by calling getFeaturesRemote
(or getFeatureRemote
for a specific feature) with providing just userId
and companyId
.
These methods will call Bucket's servers and feature flags will be evaluated remotely
using the stored attributes.
1// Update user and company attributes 2client.updateUser("john_doe", { 3 attributes: { 4 name: "John O.", 5 role: "admin", 6 }, 7}); 8 9client.updateCompany("acme_inc", { 10 attributes: { 11 name: "Acme, Inc", 12 tier: "premium" 13 }, 14}); 15... 16 17// This will evaluate feature flags with respecting the attributes sent previously 18const features = await client.getFeaturesRemote("acme_inc", "john_doe");
NOTE: User and company attribute updates are processed asynchronously, so there might be a small delay between when attributes are updated and when they are available for evaluation.
There are use cases in which you not want to be sending user
, company
and
track
events to Bucket.co. These are usually cases where you could be impersonating
another user in the system and do not want to interfere with the data being
collected by Bucket.
To disable tracking, bind the client using bindClient()
as follows:
1// binds the client to a given user and company and set `enableTracking` to `false`. 2const boundClient = client.bindClient({ user, company, enableTracking: false }); 3 4boundClient.track("some event"); // this will not actually send the event to Bucket. 5 6// the following code will not update the `user` nor `company` in Bucket and will 7// not send `track` events either. 8const { isEnabled, track } = boundClient.getFeature("user-menu"); 9if (isEnabled) { 10 track(); 11}
Another way way to disable tracking without employing a bound client is to call getFeature()
or getFeatures()
by supplying enableTracking: false
in the arguments passed to
these functions.
[!NOTE] Note, however, that calling
track()
,updateCompany()
orupdateUser()
in theBucketClient
will still send tracking data. As such, it is always recommended to usebindClient()
when using this SDK.
It is highly recommended that users of this SDK manually call flush()
method on process shutdown. The SDK employs a batching technique to minimize
the number of calls that are sent to Bucket's servers. During process shutdown,
some messages could be waiting to be sent, and thus, would be discarded if the
buffer is not flushed.
A naive example:
1process.on("SIGINT", () => { 2 console.log("Flushing batch buffer..."); 3 client.flush().then(() => { 4 process.exit(0); 5 }); 6});
When you bind a client to a user/company, this data is matched against the targeting rules. To get accurate targeting, you must ensure that the user/company information provided is sufficient to match against the targeting rules you've created. The user/company data is automatically transferred to Bucket. This ensures that you'll have up-to-date information about companies and users and accurate targeting information available in Bucket at all time.
Tracking allows events and updating user/company attributes in Bucket. For example, if a customer changes their plan, you'll want Bucket to know about it, in order to continue to provide up-do-date targeting information in the Bucket interface.
The following example shows how to register a new user, associate it with a company and finally update the plan they are on.
1// registers the user with Bucket using the provided unique ID, and 2// providing a set of custom attributes (can be anything) 3client.updateUser("user_id", { 4 attributes: { longTimeUser: true, payingCustomer: false }, 5}); 6client.updateCompany("company_id", { userId: "user_id" }); 7 8// the user started a voice huddle 9client.track("user_id", "huddle", { attributes: { voice: true } });
It's also possible to achieve the same through a bound client in the following manner:
1const boundClient = client.bindClient({ 2 user: { id: "user_id", longTimeUser: true, payingCustomer: false }, 3 company: { id: "company_id" }, 4}); 5 6boundClient.track("huddle", { attributes: { voice: true } });
Some attributes are used by Bucket to improve the UI, and are recommended to provide for easier navigation:
name
-- display name for user
/company
,email
-- the email of the user.Attributes cannot be nested (multiple levels) and must be either strings, integers or booleans.
Last seen
By default updateUser
/updateCompany
calls automatically update the given
user/company Last seen
property on Bucket servers.
You can control if Last seen
should be updated when the events are sent by setting
meta.active = false
. This is often useful if you
have a background job that goes through a set of companies just to update their
attributes but not their activity.
Example:
1client.updateUser("john_doe", { 2 attributes: { name: "John O." }, 3 meta: { active: true }, 4}); 5 6client.updateCompany("acme_inc", { 7 attributes: { name: "Acme, Inc" }, 8 meta: { active: false }, 9});
bindClient()
updates attributes on the Bucket servers but does not automatically
update Last seen
.
The Bucket SDK doesn't collect any metadata and HTTP IP addresses are not being stored. For tracking individual users, we recommend using something like database ID as userId, as it's unique and doesn't include any PII (personal identifiable information). If, however, you're using e.g. email address as userId, but prefer not to send any PII to Bucket, you can hash the sensitive data before sending it to Bucket:
1import { sha256 } from 'crypto-hash'; 2 3client.updateUser({ userId: await sha256("john_doe"), ... });
Types are bundled together with the library and exposed automatically when importing through a package manager.
MIT License Copyright (c) 2024 Bucket ApS
No vulnerabilities found.
No security vulnerabilities found.