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
| Parameter | Type | Required | Description |
|---|---|---|---|
apiKey | string | Yes | Environment API Key. Created under Settings → API Keys. |
options | CanaryGateOptions | No | Configuration options. See below. |
CanaryGateOptions
| Option | Type | Default | Description |
|---|---|---|---|
baseUrl | string | http://localhost:3001 | API base URL (useful for self-hosted environments or proxies). |
environment | string | default environment | Environment slug, sent via the X-Environment header. |
stream | boolean | false | Server environments only: opt in to real-time SSE streaming. Ignored in browsers (a warning is logged). |
reconnectDelay | number | 5000 | Initial delay in ms before reconnecting a dropped stream. |
maxReconnectDelay | number | 30000 | Maximum backoff delay in ms for stream reconnection. |
heartbeatTimeoutMs | number | 65000 | Time in ms without a server heartbeat before the stream is considered dead and reconnects. |
init()
await canary.init()Executes two actions in sequence:
- Makes an HTTP fetch to load all flags for the environment (snapshot)
- 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