SDK Usage in Code
Integrate tokenize and detokenize into your application.
What to change in your project
- Add VAULT_URL to your app config or secrets.
- Add an HTTP client with tokenize and detokenize methods.
Integration is HTTP + JSON only. You do not need to add the Securelytix repository as a Go module.
Where to use the Vault API
HTTP / API handlers
- Incoming API calls (create / update / submit): tokenize in the request handler, then store tokens in your database.
- Outgoing API responses: return stored tokens as-is; detokenize only for admin, support, or internal endpoints that need plaintext.
- Downstream HTTP calls: tokenize JSON bodies before POSTing to microservices or webhooks.
Runtime tokenization — when to call
Call tokenize before INSERT/UPDATE, before enqueueing a job, before writing to a cache key that might be dumped, or before emitting to a bus.
Runtime detokenization — when to call
Call detokenize only in narrow flows: reporting export, fulfillment, billing reconciliation, or a screened internal UI. Avoid detokenizing on every read if the consumer only needs the tokenized view.
Storing tokens instead of raw values
After tokenization, the response has the same keys and nesting as your input; only classified PII fields become tokens. Persist that object — never store the pre-tokenize payload.
TypeScript / JavaScript client
javascript · terminal
1export function createVaultClient({ baseUrl, fetchImpl = fetch }) {2const root = baseUrl.replace(/\/$/, "");3return {4async tokenize(data, headers = {}) {5const r = await fetchImpl(`${root}/api/v1/tokenize`, {6method: "POST",7headers: {8"Content-Type": "application/json",9...(headers.customerId ? { "X-Customer-ID": headers.customerId } : {}),10},11body: JSON.stringify({ data }),12});13if (!r.ok) throw new Error(`vault tokenize ${r.status}: ${await r.text()}`);14return r.json();15},16async detokenize(data) {17const r = await fetchImpl(`${root}/api/v1/detokenize`, {18method: "POST",19headers: { "Content-Type": "application/json" },20body: JSON.stringify({ data }),21});22if (!r.ok) throw new Error(`vault detokenize ${r.status}: ${await r.text()}`);23return r.json();24},25};26}2728const vault = createVaultClient({ baseUrl: process.env.VAULT_URL });
Go client
go · terminal
1package vaultclient23import (4"bytes"5"context"6"encoding/json"7"fmt"8"net/http"9"strings"10)1112type Client struct {13BaseURL string14HTTP *http.Client15}1617func New(baseURL string) *Client {18return &Client{BaseURL: strings.TrimRight(baseURL, "/"), HTTP: http.DefaultClient}19}2021func (c *Client) Tokenize(ctx context.Context, data map[string]any, customerID string) (map[string]any, error) {22body, _ := json.Marshal(map[string]any{"data": data})23req, _ := http.NewRequestWithContext(ctx, http.MethodPost, c.BaseURL+"/api/v1/tokenize", bytes.NewReader(body))24req.Header.Set("Content-Type", "application/json")25if customerID != "" {26req.Header.Set("X-Customer-ID", customerID)27}28resp, err := c.HTTP.Do(req)29if err != nil { return nil, err }30defer resp.Body.Close()31if resp.StatusCode < 200 || resp.StatusCode >= 300 {32return nil, fmt.Errorf("tokenize: status %d", resp.StatusCode)33}34var out struct{ Data map[string]any }35json.NewDecoder(resp.Body).Decode(&out)36return out.Data, nil37}
Minimal code patterns
Ingest / create — tokenize, then persist
javascript · terminal
1const { data } = await vault.tokenize(payload, { customerId: tenantId });2await saveToDatabase({ ...record, payload: data });
Privileged read — load, detokenize, return
javascript · terminal
1const row = await loadFromDatabase(id);2const { data, status, failed_fields } = await vault.detokenize(row.payload);3if (status === "partial_success" && failed_fields?.length) {4/* log metrics; some fields may remain token strings */5}6return data;
TypeScript / JavaScript — API route examples
Incoming POST /api/users — tokenize before persisting
javascript · terminal
1app.post("/api/users", async (req, res) => {2const body = req.body;3const { data: safe } = await vault.tokenize(body, {4customerId: req.header("x-tenant-id") ?? undefined,5});6await saveUser(safe);7res.status(201).json({ id: "..." });8});
Outgoing GET /api/admin/users/:id — detokenize before response
javascript · terminal
1app.get("/api/admin/users/:id", requireAdmin, async (req, res) => {2const row = await loadUser(req.params.id);3const { data, status, failed_fields } = await vault.detokenize(row.profile);4if (status === "partial_success" && failed_fields?.length) {5req.log?.warn({ failed_fields }, "partial detokenize");6}7res.json({ ...row, profile: data });8});
Go — API handler examples
go · terminal
1func (s *Server) createUser(w http.ResponseWriter, r *http.Request) {2var body map[string]any3json.NewDecoder(r.Body).Decode(&body)4safe, err := s.vault.Tokenize(r.Context(), body, r.Header.Get("X-Tenant-ID"))5if err != nil { http.Error(w, "tokenize", http.StatusBadGateway); return }6s.store.InsertUser(r.Context(), safe)7w.WriteHeader(http.StatusCreated)8}