Skip to content

basestack-co/basestack-flags-js

Repository files navigation

Basestack Feature Flags Javascript Integration

Integration with JavaScript Vanilla helps and facilitates the process of testing and developing features in production and other environments. The vanilla version can be integrated into any environment that uses JavaScript, you can use this integration in projects like Vue, Svelte or other JavaScript frameworks.

Why Feature Flags?

Feature flags are an excellent way to test features in production. Take advantage of different environments to hide or show your features. This can be used to facilitate the development process on project features that are not yet ready to be presented in production or even disable in real-time if any of the features in production are malfunctioning

Getting Started

Start by installing the library following the instructions below.

Quick links

Development

This repository uses Bun 1.3.2 as the package manager/runtime. Make sure that version is installed locally (bun --version should print 1.3.2) before running any scripts. The package also targets Node.js >=18.17.0, so ensure your runtime meets that requirement before developing or publishing.

Install dependencies and use the bundled scripts via Bun. Biome is configured for linting/formatting and Vitest powers the unit tests, so you can keep the codebase consistent with the commands below:

bun install
bun run clean # remove the generated dist/ directory
bun run dev   # builds in watch mode
bun run build # produces the package in dist/
bun run update:deps # interactively choose dependency upgrades
bun run lint  # run Biome lint checks
bun run check # run Biome's check task with auto-fixes
bun run format # format files via Biome
bun run test   # run the Vitest suite once
bun run test:watch # watch and re-run impacted tests
bun run publish # wraps npm publish; lint/test/build run via the prepublishOnly hook

Running npm publish directly will also trigger the lint/test pipeline because of the prepublishOnly hook.

Examples

Minimal example apps live under examples/ to manually verify the SDK in different environments:

  • examples/client: Vite + TypeScript client rendered with Bun (bun run dev)
  • examples/vue: Vue + Vite app using the same SDK credentials (bun run dev)
  • examples/server: Hono server running on Bun (bun run dev)

All examples depend on the local package via link:../.., so run bun run build at the repo root first to ensure dist/ is up-to-date.

Installation

First, let's install some packages!

npm install --save @basestack/flags-js

or with yarn

yarn add @basestack/flags-js

or with Script Tag

<script type="module" src="https://unpkg.com/@basestack/flags-js"></script>

Create a new instance

This params values can be found on the on your project's settings

import { FlagsSDK } from "@basestack/flags-js";

// Basic Initialization
const client = new FlagsSDK({
  projectKey: "your-project-key",
  environmentKey: "your-environment-key",
});

// Advanced Configuration Example
const advancedClient = new FlagsSDK({
  baseURL: "https://your-basestack-hosted-app-domain.com/api/v1",
  projectKey: "your-project-key",
  environmentKey: "your-environment-key",
  apiKey: "your-project-api-token", // only required for authenticated write endpoints
  preloadFlags: ["header", "footer"],
  cache: {
    enabled: true,
    ttl: 10 * 60 * 1000, // 10-minute cache
    maxSize: 50, // Limit cache to 50 entries
  },
});

That's it! Now your app is ready to start using feature flags and other features. Follow the instructions of the supported methods to make the most of the Basestack Feature Flags functionalities.

SDK Config

FlagsSDK accepts the following configuration:

  • baseURL?: string - API base URL. Defaults to https://flags-api.basestack.co/v1.
  • projectKey: string - required project identifier.
  • environmentKey: string - required environment identifier.
  • apiKey?: string - project API token used by authenticated write endpoints such as submitCodeReferences(). Prefer server-side usage for this token.
  • cache?: CacheConfig - optional cache settings.
  • fetchImpl?: typeof fetch - optional custom fetch implementation.
  • preloadFlags?: string[] - optional list of flags to preload during init(). If omitted, init() preloads all flags.

Exported Types

The SDK exports these public types:

  • CacheConfig
  • SDKConfig
  • Flag
  • PreviewFlag
  • PreviewFlagsResponse
  • PreviewFeedbackMood
  • SubmitPreviewFeedbackPayload
  • SubmitPreviewFeedbackResponse
  • CodeReferenceRow
  • SubmitCodeReferencesPayload
  • SubmitCodeReferencesResponse

Usage

import { FlagsSDK } from "@basestack/flags-js";

const client = new FlagsSDK({
  baseURL: "https://flags-api.basestack.co/v1",
  projectKey: "your-project-key",
  environmentKey: "your-environment-key",
});

// Preload flags on initialization (optional)
// This will fetch the flags and cache them for future use
// But you can still fetch flags on-demand using getFlag()
await client.init();

// Fetching a Single Flag
async function checkFeatureFlag() {
  try {
    const headerFlag = await client.getFlag("header");

    if (headerFlag.enabled) {
      console.log("Header feature is enabled");
      console.log("Payload:", headerFlag.payload);
      // Additional flag properties
    } else {
      console.log("Header feature is disabled");
    }
  } catch (error) {
    console.error("Failed to fetch flag:", error);
  }
}

// Fetching All Flags
async function listAllFlags() {
  try {
    const { flags } = await client.getAllFlags();

    flags.forEach((flag) => {
      console.log(`Flag: ${flag.slug}`);
      console.log(`Enabled: ${flag.enabled}`);
      console.log(`Description: ${flag.description}`);
      // Additional flag properties
    });
  } catch (error) {
    console.error("Failed to fetch flags:", error);
  }
}

// Cache Management
function manageCaching() {
  // Clear entire cache
  client.clearCache();

  // Clear cache for a specific flag
  client.clearFlagCache("header");
}

// Practical Example

async function renderFeature() {
  try {
    const headerFlag = await client.getFlag("new-header-design");

    if (headerFlag.enabled) {
      // Render new header design
      renderNewHeader(headerFlag.payload);
    } else {
      // Render default header
      renderDefaultHeader();
    }
  } catch (error) {
    // Fallback to default implementation
    renderDefaultHeader();
  }
}

// Types
import {
  CacheConfig,
  CodeReferenceRow,
  Flag,
  PreviewFlag,
  PreviewFeedbackMood,
  PreviewFlagsResponse,
  SDKConfig,
  SubmitCodeReferencesResponse,
  SubmitPreviewFeedbackPayload,
  SubmitPreviewFeedbackResponse,
  SubmitCodeReferencesPayload,
} from "@basestack/flags-js";

API

init()

Preloads flags into the internal cache.

  • If preloadFlags is set, it loads those slugs.
  • If preloadFlags is omitted, it loads all flags.
await client.init();

getFlag(slug)

Fetch a single flag by slug.

const flag = await client.getFlag("header");

console.log(flag.slug);
console.log(flag.enabled);
console.log(flag.payload);

getAllFlags()

Fetch all flags for the configured project and environment.

const { flags } = await client.getAllFlags();

flags.forEach((flag) => {
  console.log(flag.slug, flag.enabled);
});

getPreviewFlags()

Fetch preview flags with rendered HTML content.

const previewResponse = await client.getPreviewFlags();

previewResponse.flags.forEach((previewFlag) => {
  console.log(previewFlag.slug);
  console.log(previewFlag.previewName);
  console.log(previewFlag.previewContent);
});

submitPreviewFeedback(payload)

Submit qualitative and quantitative feedback for a preview flag.

const feedback = await client.submitPreviewFeedback({
  flagKey: "landing-preview",
  mood: "HAPPY",
  rating: 4,
  description: "The preview looks good and reads clearly.",
  metadata: {
    page: "landing",
    source: "marketing-site",
  },
});

console.log(feedback.success);
console.log(feedback.feedbackId);

Validation rules:

  • flagKey is required
  • mood is required
  • rating must be an integer from 1 to 5
  • description must be at most 2000 characters
  • metadata, when provided, must be an object

submitCodeReferences(payload)

Upload or replace code references for the provided branch and flag slugs.

  • Requires apiKey in SDK config
  • Best used from CI, static analysis tooling, or server-side code
const authenticatedClient = new FlagsSDK({
  baseURL: "https://flags-api.basestack.co/v1",
  projectKey: "your-project-key",
  environmentKey: "your-environment-key",
  apiKey: "your-project-api-token",
});

const result = await authenticatedClient.submitCodeReferences({
  branch: "main",
  projectName: "acme-web",
  repositoryUrl: "https://github.com/acme/web",
  references: {
    "new-checkout": [
      {
        filePath: "src/features/checkout.tsx",
        lineNumber: 42,
        lineContent: "if (flags.newCheckout) {",
      },
    ],
  },
});

console.log(result.success);
console.log(result.message);

Validation rules:

  • branch is required and must be at most 255 characters
  • projectName is required and must be at most 150 characters
  • repositoryUrl, when provided, must be at most 255 characters
  • references must be an object keyed by flag slug
  • each flag slug must be at most 150 characters
  • each row must include filePath, lineNumber, and lineContent
  • filePath must be at most 2000 characters
  • lineNumber must be a positive integer
  • lineContent must be at most 4000 characters

clearCache()

Clear the entire in-memory cache.

client.clearCache();

clearFlagCache(slug)

Clear cached entries for a specific flag slug.

client.clearFlagCache("header");