Node SDK usage

How to use the Node SDK to call for and retrieve flag details.

Published on: 14 May 2025

RocketFlag Node.js SDK Documentation

Welcome to the official documentation for the RocketFlag Node.js SDK! This guide will help you get started with integrating RocketFlag feature flags into your Node.js applications or JavaScript web apps.

What is RocketFlag?

RocketFlag is a feature flag and A/B testing platform. This SDK allows you to easily integrate RocketFlag into your JavaScript Web Apps or Node.js applications, enabling you to control feature rollouts, perform A/B tests, and manage your features effectively.

Installation

To start using the RocketFlag Node.js SDK, you’ll first need to install it using npm (Node Package Manager). Open your terminal and run the following command:

npm install @rocketflag/node-sdk

This command will download and install the SDK into your project’s node_modules directory and add it to your package.json dependencies.

Getting Started: Basic Usage

Once the SDK is installed, you can start using it in your JavaScript or Node.js application.

1. Setup and Initialisation

First, you need to import and initialise the RocketFlag client.

// ES Module syntax (recommended for modern Node.js and front-end frameworks)
import createRocketflagClient from "@rocketflag/node-sdk";

// Initialise the client with default settings
// This will use the default RocketFlag API URL (https://rocketflag.app or similar) and the latest API version known to the SDK.
const rocketflag = createRocketflagClient();

// --- Optional Configuration ---
// If you need to specify a particular API version or use a custom API domain (e.g., for self-hosted instances):
// const customApiVersion = "v2";
// const customApiUrl = "https://your-api-domain.com";
// const rocketflagWithCustomConfig = createRocketflagClient(customApiVersion, customApiUrl);

// For the rest of the examples, we'll assume you're using the default client:
// const rocketflag = createRocketflagClient();

Explanation:

  • createRocketflagClient(): This function initialises and returns a new RocketFlag client instance.
  • Default Configuration: If you call createRocketflagClient() with no arguments, it will use the default RocketFlag API URL and the latest API version supported by the SDK.
  • Custom Configuration: You can optionally pass two arguments to createRocketflagClient():
    1. apiVersion (string): The specific version of the RocketFlag API you want to use (e.g., "v2").
    2. apiUrl (string): A custom base URL for the RocketFlag API.

2. Getting a Flag

After initialising the client, you can fetch the status of a specific feature flag using its unique ID.

async function checkFeatureFlag() {
  try {
    // Replace "your-flag-id" with the actual ID of the flag you want to retrieve.
    // You can find this ID in your RocketFlag dashboard.
    const flagId = "IFldMsqP5jtv9wAL";
    const flag = await rocketflag.getFlag(flagId);

    // The 'flag' object contains information about the feature flag.
    // A common property to check is 'enabled'.
    console.log(`Flag "${flag.name}" (ID: ${flag.id}) is enabled: ${flag.enabled}`);

    // Example: Conditionally execute code based on the flag's status
    if (flag.enabled) {
      console.log("The new sign-up feature is enabled!");
      // In a React application, you might update state:
      // setSignUpsEnabled(flag.enabled);
    } else {
      console.log("The new sign-up feature is currently disabled.");
      // Execute alternative code or do nothing
    }
  } catch (error) {
    // It's important to handle potential errors, such as network issues or if the flag doesn't exist.
    console.error("Something went wrong fetching the flag:", error.message);
    // You might want to set a default behavior in case of an error
    // setSignUpsEnabled(false); // Default to disabled if fetching fails
  }
}

// Call the function to see it in action
checkFeatureFlag();

Explanation:

  • await rocketflag.getFlag("your-flag-id"): This asynchronous function fetches the flag with the specified ID.
  • flag object: If successful, it returns an object containing the flag’s details, including name, id, and enabled (boolean).
  • Error Handling: The try...catch block is crucial for managing potential issues like network errors or if the flag ID is not found.

Advanced Usage: Working with Cohorts

Cohorts allow you to target feature flags to specific groups of users. To use this, you must first define your cohorts in the RocketFlag dashboard.

When fetching a flag, you can provide a context object that includes a cohort identifier. This tells RocketFlag to evaluate the flag based on the rules you’ve set up for that cohort.

async function checkFlagForCohort() {
  const flagId = "ABC123def456"; // Example flag ID
  const userCohortIdentifier = "beta-testers"; // Replace with your actual cohort identifier

  try {
    const flag = await rocketflag.getFlag(flagId, {
      cohort: userCohortIdentifier,
    });

    console.log(`For cohort "${userCohortIdentifier}", flag "${flag.name}" is enabled: ${flag.enabled}`);

    if (flag.enabled) {
      // Feature is enabled for this cohort
    } else {
      // Feature is disabled for this cohort
    }
  } catch (error) {
    console.error(`Error fetching flag "${flagId}" for cohort "${userCohortIdentifier}":`, error.message);
  }
}

checkFlagForCohort();

In this example, the second argument to getFlag is an object { cohort: "<cohort-identifier>" }. RocketFlag will use this identifier to determine if the user associated with this request (implicitly or explicitly through the cohort identifier) should get the feature enabled based on your cohort rules.

Understanding the API Response

When you call getFlag, the underlying API request can result in a few different outcomes. The SDK will typically handle these and either return the flag data or throw an error. It’s good to understand what these mean:

  1. Successful Response (200 OK with Flag Object)

    If the flag is found and everything is working correctly, the API returns a 200 OK status, and the SDK provides you with the flag object.

    {
      "name": "My Cool Flag",
      "enabled": true,
      "id": "ABC123def456"
    }
    
    • name: The human-readable name you gave the flag in the RocketFlag console.
    • enabled: A boolean indicating whether the flag is active (true) or inactive (false) for the given context.
    • id: The unique identifier of the flag.
  2. Not Found (404 Not Found)

    If the API returns a 404 Not Found status, it means the flagId you provided in your getFlag("your-flag-id") call does not correspond to any existing flag in your RocketFlag environment. The SDK will typically translate this into an error.

    • Action: Double-check the flag ID you are using. Ensure it matches exactly with the ID shown in your RocketFlag console.
  3. Internal Server Error (500 Internal Server Error)

    A 500 Internal Server Error indicates that something unexpected went wrong on the RocketFlag server while trying to retrieve the flag data.

    • Action: These errors should be rare. Trying the request again after a short delay might resolve temporary issues. RocketFlag’s internal alerting system is typically triggered by 500 errors, so the team is likely already aware and investigating. If this persists, you might want to check RocketFlag’s status page (if available) or contact support. The SDK will also translate this server error into a JavaScript error.