@basestack/flags-js
v1.2.3
Published
Feature Flags SDK for JavaScript
Maintainers
Readme
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
Installation
First, let's install some packages!
npm install --save @basestack/flags-jsor with yarn
yarn add @basestack/flags-jsor 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 tohttps://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 assubmitCodeReferences(). 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 duringinit(). If omitted,init()preloads all flags.
Exported Types
The SDK exports these public types:
CacheConfigSDKConfigFlagPreviewFlagPreviewFlagsResponsePreviewFeedbackMoodSubmitPreviewFeedbackPayloadSubmitPreviewFeedbackResponseCodeReferenceRowSubmitCodeReferencesPayloadSubmitCodeReferencesResponse
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
preloadFlagsis set, it loads those slugs. - If
preloadFlagsis 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:
flagKeyis requiredmoodis requiredratingmust be an integer from1to5descriptionmust be at most2000charactersmetadata, when provided, must be an object
submitCodeReferences(payload)
Upload or replace code references for the provided branch and flag slugs.
- Requires
apiKeyin 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:
branchis required and must be at most255charactersprojectNameis required and must be at most150charactersrepositoryUrl, when provided, must be at most255charactersreferencesmust be an object keyed by flag slug- each flag slug must be at most
150characters - each row must include
filePath,lineNumber, andlineContent filePathmust be at most2000characterslineNumbermust be a positive integerlineContentmust be at most4000characters
clearCache()
Clear the entire in-memory cache.
client.clearCache();clearFlagCache(slug)
Clear cached entries for a specific flag slug.
client.clearFlagCache("header");This SDK is distributed under the MIT License. Development is maintained in a private monorepo, and releases are published to npm as the official distribution.
For bug reports, support requests, or security concerns, please contact [email protected].
