> For the complete documentation index, see [llms.txt](https://docs.veilio.xyz/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.veilio.xyz/documentation/getting-started/sdk-js.md).

# SDK Javascript Integration

Use an SDK for the fastest production integration.

#### Node.js / TypeScript

Install:

```bash
npm install @veilio/sdk
```

Example:

```ts
import { VeilioClient } from "@veilio/sdk";

const veilio = new VeilioClient({
  apiKey: process.env.VEILIO_API_KEY!,
  baseUrl: process.env.VEILIO_BASE_URL || "https://app.veilio.fr/api",
});

export async function createCustomer(email: string) {
  const { token } = await veilio.tokenize({
    data: email,
    type: "email",
  });

  // Store token in your DB, not the raw email.
  return { emailToken: token };
}

export async function sendWelcomeEmail(emailToken: string) {
  const { data: email } = await veilio.detokenize({
    token: emailToken,
    reason: "Send welcome email",
  });

  return email;
}

// Call when a user requests account deletion (GDPR right to erasure)
export async function deleteUserData(emailToken: string) {
  await veilio.shredToken({
    token: emailToken,
    reason: "GDPR - user deletion request",
  });
}
```

#### Client configuration

```ts
const veilio = new VeilioClient({
  apiKey: string,       // Required — your Veilio API key
  baseUrl?: string,     // Default: https://app.veilio.fr/api
  timeout?: number,     // Request timeout in ms (default: 30000)
  maxRetries?: number,  // Retries on rate limits / network errors (default: 3)
});
```

For **on-premise** deployments, point `baseUrl` to your instance:

```ts
const veilio = new VeilioClient({
  apiKey: process.env.VEILIO_API_KEY!,
  baseUrl: "https://your-domain.com/api",
});
```

Environment variables:

| Variable          | Description                               |
| ----------------- | ----------------------------------------- |
| `VEILIO_API_KEY`  | API key from the Veilio dashboard         |
| `VEILIO_BASE_URL` | API base URL (optional, defaults to SaaS) |

#### API reference

**`tokenize(options)`**

Tokenize a single field.

```ts
const result = await veilio.tokenize({
  data: "john@example.com",
  type: "email",                    // Optional: email, phone, ssn, etc.
  metadata: { source: "signup" },   // Optional
  retention: {                      // Optional — automatic shredding
    ttlDays: 30,                    // Shred after N days
    // or retentionUntil: "2026-12-31T23:59:59.000Z"
  },
});

// Returns: { token, createdAt, retentionUntil? }
```

**`tokenizeBulk(options)`**

Tokenize multiple fields in one request.

```ts
const result = await veilio.tokenizeBulk({
  fields: [
    { data: "john@example.com", type: "email" },
    { data: "+33612345678", type: "phone", retention: { ttlDays: 365 } },
  ],
});

// Returns: { tokens, summary: { total, success, failed }, errors?, createdAt }
```

**`detokenize(options)`**

```ts
const result = await veilio.detokenize({
  token: "tok_abc123...",
  reason: "Send email",  // Optional — logged for audit
});

// Returns: { data, accessedAt }
```

**`detokenizeBulk(options)`**

```ts
const result = await veilio.detokenizeBulk({
  tokens: [
    { token: "tok_abc123...", reason: "Profile view" },
    { token: "tok_def456...", reason: "Profile view" },
  ],
  // Optional: one audit log line for the whole batch
  reason: "Profile view",
});

// Returns: { results, summary, errors?, accessedAt }
```

**`shredToken(options)`**

Immediately and irreversibly destroy a token (cryptographic erasure).

```ts
const result = await veilio.shredToken({
  token: "tok_abc123...",
  reason: "GDPR erase request",  // Optional
});

// Returns: { token, shreddedAt }
```

**`tokenizeFormat(options)`**

Tokenize structured data (JSON, CSV, or SQL).

```ts
const result = await veilio.tokenizeFormat({
  data: JSON.stringify({ email: "john@example.com", phone: "+33612345678" }),
  format: "json",  // Optional — auto-detected if omitted ("json" | "csv" | "sql")
  options: {
    fields: ["email"],              // Optional — tokenize only specific paths
    retention: { ttlDays: 365 },    // Optional
    csv: {                          // CSV-specific options
      delimiter: ",",
      hasHeaders: true,
    },
  },
});

// Returns: { format, tokenizedData, tokens: [{ path, token, type? }], summary, metadata? }
```

**`detokenizeFormat(options)`**

Restore original values in structured data.

```ts
const result = await veilio.detokenizeFormat({
  tokenizedData: tokenizedJson,
  format: "json",
  tokens: [
    { path: "email", token: "tok_abc123..." },
  ],
});

// Returns: { format, detokenizedData, summary: { tokensProcessed } }
```

#### Bulk operations

For imports, migrations, or high-throughput jobs:

* `tokenizeBulk`
* `detokenizeBulk`

Use batching and retry logic for `429` responses. The SDK retries automatically (respecting `Retry-After` headers) up to `maxRetries` times.

```ts
const bulk = await veilio.tokenizeBulk({
  fields: [
    { data: "alice@example.com", type: "email" },
    { data: "+33612345678", type: "phone" },
  ],
});

if (bulk.summary.failed > 0) {
  console.error("Partial failure:", bulk.errors);
}

const values = await veilio.detokenizeBulk({
  tokens: bulk.tokens.map((t) => ({
    token: t.token,
    reason: "Migration verification",
  })),
});
```

#### Retention and shredding

Schedule automatic shredding at tokenization time, or shred immediately:

```ts
// Automatic shredding after 30 days
const tokenized = await veilio.tokenize({
  data: "delete-me@example.com",
  type: "email",
  retention: { ttlDays: 30 },
});

// Immediate shredding (irreversible)
await veilio.shredToken({
  token: tokenized.token,
  reason: "User deletion request",
});
```

#### Error handling

```ts
import {
  VeilioClient,
  VeilioError,
  PlanLimitError,
  TokenShreddedError,
} from "@veilio/sdk";

try {
  const result = await veilio.detokenize({
    token: "tok_abc123...",
    reason: "Support case",
  });
} catch (error) {
  if (error instanceof TokenShreddedError) {
    // HTTP 410 — token was shredded, data is gone
    console.error("Token shredded:", error.message);
  } else if (error instanceof PlanLimitError) {
    // HTTP 403 — plan quota exceeded
    console.error("Plan limit:", error.message, error.details);
  } else if (error instanceof VeilioError) {
    console.error(`API error [${error.code}]:`, error.message);
    console.error("Status:", error.statusCode);
    console.error("Details:", error.details);
  } else {
    console.error("Unexpected error:", error);
  }
}
```

**Error codes**

| Code               | HTTP | Description                               |
| ------------------ | ---- | ----------------------------------------- |
| `AUTH_ERROR`       | 401  | Invalid or missing API key                |
| `VALIDATION_ERROR` | 400  | Invalid request data                      |
| `PLAN_LIMIT`       | 403  | Plan quota exceeded                       |
| `RATE_LIMIT_ERROR` | 429  | Rate limit exceeded                       |
| `TOKEN_SHREDDED`   | 410  | Token has been cryptographically shredded |
| `TIMEOUT_ERROR`    | 408  | Request timed out                         |
| `INTERNAL_ERROR`   | 5xx  | Server error                              |

#### TypeScript

Full type definitions are included:

```ts
import {
  VeilioClient,
  type TokenizeResult,
  type BulkTokenizeResult,
  type FormatTokenizeResult,
} from "@veilio/sdk";

const result: TokenizeResult = await veilio.tokenize({
  data: "test@example.com",
  type: "email",
});
```

#### Requirements

* Node.js 18+ (native `fetch`) or install `node-fetch` for older versions
* A valid Veilio API key

**Links**

* NPM package: <https://www.npmjs.com/package/@veilio/sdk>
* SDK style reference: <https://docs.veilio.xyz/documentation/getting-started/>
