Skip to Content
SDKJavaScript / TypeScriptInitialization

Constructor

import { CanaryGate } from '@canarygate/sdk/js/client' // browser // or import { CanaryGate } from '@canarygate/sdk/js/server' // server runtimes new CanaryGate(apiKey: string, options?: CanaryGateOptions)

Parameters

ParameterTypeRequiredDescription
apiKeystringYesEnvironment API Key. Created under Settings → API Keys.
optionsCanaryGateOptionsNoConfiguration options. See below.

CanaryGateOptions

OptionTypeDefaultDescription
baseUrlstringhttp://localhost:3001API base URL (useful for self-hosted environments or proxies).
environmentstringdefault environmentEnvironment slug, sent via the X-Environment header.
streambooleanfalseServer environments only: opt in to real-time SSE streaming. Ignored in browsers (a warning is logged).
reconnectDelaynumber5000Initial delay in ms before reconnecting a dropped stream.
maxReconnectDelaynumber30000Maximum backoff delay in ms for stream reconnection.
heartbeatTimeoutMsnumber65000Time in ms without a server heartbeat before the stream is considered dead and reconnects.

init()

await canary.init()

Executes two actions in sequence:

  1. Makes an HTTP fetch to load all flags for the environment (snapshot)
  2. Opens the SSE connection — only in server environments when stream: true. In browsers the stream is always disabled; flags come from the snapshot request only.

Always await init() before reading flags — otherwise, getFlag() may return undefined before the initial load completes.

Examples

Browser (React)

In browsers the SDK always uses the snapshot request — stream is ignored and real-time updates are not available.

import { CanaryGate } from '@canarygate/sdk/js/client' import { useEffect, useRef } from 'react' export function useCanaryGate() { const ref = useRef<CanaryGate | null>(null) useEffect(() => { const client = new CanaryGate(process.env.NEXT_PUBLIC_CANARYGATE_KEY!) client.init().then(() => { ref.current = client }) return () => { client.disconnect() } }, []) return ref }

Node.js (singleton)

import { CanaryGate } from '@canarygate/sdk/js/server' let client: CanaryGate | null = null export async function getCanaryGate() { if (!client) { client = new CanaryGate(process.env.CANARYGATE_KEY!) await client.init() } return client }

One-shot script (no SSE)

import { CanaryGate } from '@canarygate/sdk/js/server' const client = new CanaryGate('cg_api_key') await client.init() const flag = client.getFlag('run-migration') if (flag?.enabled) { await runMigration() } // Disconnect (closes any active stream) so the process can exit client.disconnect()
Last updated on