ข้ามไปยังเนื้อหา

JavaScript SDK

@growthbook/growthbook คือ foundation package หรือ core SDK ที่ทำงานได้ในทุก JavaScript environment — browser, Node.js, Deno และ edge workers (Cloudflare Workers, Vercel Edge และอื่น ๆ) React SDK และ framework wrappers อื่น ๆ ถูกสร้างขึ้นบน package นี้

npm install @growthbook/growthbook

สร้าง instance ด้วย new GrowthBook({ apiHost, clientKey }) จากนั้นเรียก await gb.init({ timeout: 2000 }) เพื่อดึง feature definitions จาก GrowthBook CDN และ cache ไว้ภายใน instance ค่า timeout (หน่วยเป็น millisecond) ที่เป็น optional จะป้องกันแอปค้างหาก network ช้า — SDK จะ fallback ไปใช้ค่า default หากการดึงข้อมูลไม่เสร็จทันเวลา

import { GrowthBook } from '@growthbook/growthbook';
const gb = new GrowthBook({
apiHost: 'https://cdn.growthbook.io',
clientKey: 'sdk-abc123',
});
await gb.init({ timeout: 2000 });

เรียก gb.setAttributes({ ... }) พร้อม context ของผู้ใช้ เช่น id, ประเทศ และ tier ข้อมูล attributes เหล่านี้ใช้สำหรับ targeting rules — ตัวอย่างเช่น “แสดง flag นี้เฉพาะผู้ใช้ที่ country เป็น 'US'” หรือ “เฉพาะบัญชี premium เท่านั้น” ส่ง key-value pairs ใด ๆ ที่ rules ของคุณอ้างอิง

gb.setAttributes({
id: 'user-abc',
country: 'US',
premium: true,
});

ควรเรียก setAttributes ก่อนประเมิน flag เสมอ เพื่อให้ targeting rules มี user context ที่ต้องการ

gb.isOn('flag-key') คืนค่า boolean — true หากเปิดใช้ flag สำหรับ attributes ปัจจุบัน, false หากปิด

gb.getFeatureValue('flag-key', fallback) คืนค่าที่มี type argument ที่สองคือ safe fallback ที่จะถูกคืนเมื่อ flag ปิด, key ไม่มีอยู่ หรือ type ไม่ตรง

import { GrowthBook } from '@growthbook/growthbook';

const gb = new GrowthBook({
  apiHost: 'https://cdn.growthbook.io',
  clientKey: 'sdk-abc123',
});

// Fetch and cache feature definitions
await gb.init({ timeout: 2000 });

// Set user attributes for targeting
gb.setAttributes({
  id: 'user-abc',
  country: 'US',
  premium: true,
});

// Boolean flag
if (gb.isOn('dark-mode')) {
  document.body.classList.add('dark');
}

// Typed value with fallback
const theme = gb.getFeatureValue('ui-theme', 'light');
console.log('Theme:', theme);
ตัวเลือกBenefitCost
Client-side SDKreal-time, personalize ตาม browser ได้ทันทีuser เห็น flag values ผ่าน dev tools ได้ ไม่ควรใช้กับ business-critical secret
Server-side rendering ของ flagซ่อน logic จาก client ได้ต้องเพิ่ม server round-trip ก่อนแสดงผล
  • ไม่ set timeout ให้ init() ทำให้ UI ค้างรอ
  • ไม่ handle กรณี SDK โหลดไม่ทัน (เกิด content flicker)
  • ลืมเรียก cleanup ตอน component/page unmount ทำให้ memory leak

💡 ตัวอย่างจากของจริง

เว็บ e-commerce จำนวนมากใช้ client-side SDK แบบนี้เพื่อทดสอบ UI เช่นปุ่ม checkout แบบ real-time โดยไม่ต้องรอ deploy ใหม่

npm package ใดที่ให้ vanilla GrowthBook JS SDK?
`gb.init()` ทำอะไร?
method ใดคืนค่าที่มี type พร้อม explicit fallback?
ทำไมต้องเรียก setAttributes ก่อนประเมิน flag?