# SDK Integration

Use the AccessIQ SDK to evaluate feature flags in your application. The SDK connects to AccessIQ, fetches flag values, and caches them locally for fast evaluation.

## Available SDKs

| Platform             | Package                      |
| -------------------- | ---------------------------- |
| JavaScript / Node.js | `@accessiq/sdk-js`           |
| React                | `@accessiq/sdk-react`        |
| Python               | `accessiq-sdk`               |
| Java                 | `com.accessiq:sdk-java`      |
| Go                   | `github.com/accessiq/sdk-go` |

## Quick Start (JavaScript)

### 1. Install the SDK

```
npm install @accessiq/sdk-js
```

### 2. Initialize the Client

```javascript
import { AccessIQClient } from '@accessiq/sdk-js';

const client = AccessIQClient.init({
  sdkKey: 'YOUR_ENVIRONMENT_SDK_KEY',
  user: {
    id: 'user-123',
    email: 'jane@acme.com',
    attributes: {
      plan: 'enterprise',
      org: 'engineering'
    }
  }
});
```

### 3. Evaluate a Flag

```javascript
const showNewDashboard = client.booleanValue('new-dashboard', false);

if (showNewDashboard) {
  // render new dashboard
} else {
  // render existing dashboard
}
```

The second argument is the default value returned if the flag is not found or the SDK cannot connect.

## Quick Start (React)

### 1. Install

```
npm install @accessiq/sdk-react
```

### 2. Wrap Your App

```jsx
import { AccessIQProvider } from '@accessiq/sdk-react';

function App() {
  return (
    <AccessIQProvider
      sdkKey="YOUR_ENVIRONMENT_SDK_KEY"
      user={{ id: 'user-123', email: 'jane@acme.com' }}
    >
      <YourApp />
    </AccessIQProvider>
  );
}
```

### 3. Use the Hook

```jsx
import { useFlag } from '@accessiq/sdk-react';

function Dashboard() {
  const showNewDashboard = useFlag('new-dashboard', false);

  return showNewDashboard ? <NewDashboard /> : <OldDashboard />;
}
```

## Using JWT Entitlements

If a flag has **Include in JWT** enabled, the flag value is embedded in the user's access token. You can read it directly without the SDK:

1. Decode the JWT access token.
2. Look for the `entitlements` claim.
3. Check the flag value.

```javascript
const token = decodeJwt(accessToken);
const canAccessReports = token.entitlements?.['advanced-reports'] === true;
```

This approach is useful for backend services that already validate the JWT.

## Evaluating Flags in PunchOut Sessions

Supplier catalogs that receive buyers via PunchOut can evaluate feature flags using the SDK REST endpoint. This is useful when the catalog needs to check flags based on the buyer's organization without a logged-in user session.

### 1. Retrieve the Session Context

First, fetch the PunchOut session context to get the buyer's organization:

```javascript
const sessionContext = await fetch(
  `${GATEWAY_URL}/api/v1/sdk/punchout/session/${sessionId}/context`,
  { headers: { 'X-SDK-Key': SDK_KEY } }
).then(r => r.json());

const orgId = sessionContext.data.organizationScope.organizations[0]?.organizationId;
```

### 2. Evaluate Flags with Org Context

Pass the organization ID to the feature flag evaluation endpoint:

```javascript
const flags = await fetch(
  `${GATEWAY_URL}/api/v1/sdk/feature-flags/evaluate?environment=production`,
  {
    method: 'POST',
    headers: {
      'X-SDK-Key': SDK_KEY,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      organizationId: orgId,
      anonymous: true
    })
  }
).then(r => r.json());

if (flags.data.flags['premium-catalog']) {
  // show premium product selection
}
```

The `anonymous: true` flag indicates that this is an unauthenticated evaluation (typical for PunchOut flows where the buyer may not have a direct login session). The same SDK key is used for both session context retrieval and flag evaluation.

## SDK Configuration Options

| Option            | Description                                      | Default |
| ----------------- | ------------------------------------------------ | ------- |
| `sdkKey`          | Environment-specific SDK key (required)          | --      |
| `user`            | User context for flag evaluation                 | --      |
| `refreshInterval` | How often to fetch updated flag values (seconds) | 60      |
| `offline`         | If true, only use cached values                  | false   |
| `defaultValues`   | Fallback values when the SDK cannot connect      | `{}`    |

## Best Practices

* Use the correct SDK key for each environment (development, staging, production).
* Always provide a sensible default value when evaluating flags so your app works even if the SDK cannot connect.
* Include relevant user attributes in the user context to enable targeting rules.
* In server-side applications, initialize the SDK once at startup and reuse the client instance.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://accessiq.gitbook.io/accessiq-docs/feature-entitlements/sdk-integration.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
