Proxy Transforms
Pre-configured proxies support two families of transforms:
- Request transforms run on the inbound request before it is forwarded to the destination. Use them to mutate the request body or headers, tokenize incoming data, or short-circuit the request and return a response without contacting the destination.
- Response transforms run on the response from the destination before it is returned to the caller. Use them to mutate the response body or headers, mask sensitive values, tokenize sensitive data, or append additional content.
Transforms are executed in the order specified in the request_transforms and response_transforms arrays on the proxy.
Request Transforms
require_auth setting and must run before any privileged operation. See Using Sessions with Proxies.| Type | Purpose |
|---|---|
code | Run custom Node.js to mutate the request body or headers, inject configuration secrets, or short-circuit and return a response without forwarding to the destination |
tokenize | Create tokens from request data using plaintext, encrypted JWE, or Liquid expressions |
Code Request Transform
Code request transforms run in Basis Theory's serverless runtime environment. New examples use a Node.js runtime image. Existing node-bt transforms use the legacy contract.
To update an existing legacy code transform, follow Migrate from node-bt.
node-bt runtime is deprecated. Use a Node.js runtime image for new Reactors and Proxy code transforms. Migrate away from the node-bt runtime as soon as possible to avoid disruption.- node-bt (Deprecated)
- node22 / node24
module.exports = async function (req) {
const { bt, args, configuration } = req;
const { body, headers, method, path, query } = args; // access properties of the http request
const { MY_CONFIG } = configuration; // access any static config defined on the Proxy
// do anything here!
const processedBody = ...; // do something with body
const processedHeaders = ...; // do something with headers
return {
body: processedBody, // transformed request body
headers: processedHeaders // transformed request headers
};
};
module.exports = async function (event) {
const { req, configuration, logger, applicationOptions } = event;
const { body, headers, method, path, query } = req; // access properties of the http request
const { MY_CONFIG } = configuration; // access any static config defined on the Proxy
logger.info("Processing request");
// do anything here!
const processedBody = ...; // do something with body
const processedHeaders = ...; // do something with headers
return {
req: {
body: processedBody, // transformed request body
headers: processedHeaders // transformed request headers
}
};
};
What a Code Request Transform Can and Cannot Change
A code request transform can:
- Mutate the request body.
- Mutate the request headers.
- Short-circuit the request and return a response directly without forwarding to the destination — see Skip Proxy Request.
A code request transform cannot:
- Change the destination URL, hostname, path, or query string. These are read-only — the outbound URL is always
destination_urlwith the inbound path suffix appended. - Change the HTTP method.
- Invoke a Reactor with
POST /reactors/{id}/reactor/react-async. The request is blocked with a403. See Invoke Reactors limitations.
node-bt Code Contract
Input
The transform function receives a request object containing the HTTP request properties and configuration:
| Attribute | Type | Description |
|---|---|---|
args | object | HTTP request properties (see below) |
configuration | map<string, string> | Configuration values defined on the proxy |
bt | object | Pre-configured Basis Theory SDK instance for token operations (if application.id is set) |
applicationOptions | object | Configuration information about the associated application (if application.id is set) |
applicationOptions.apiKey | string | The API key of the associated application |
applicationOptions.baseUrl | string | The Basis Theory API base URL (e.g., https://api.basistheory.com) |
headers | object | Allowlisted Basis Theory headers from the proxy request: bt-merchant-id and bt-trace-id, each present only when received. See Forwarding BT-MERCHANT-ID in Transforms |
The args object contains the HTTP request properties:
| Attribute | Type | Description |
|---|---|---|
body | object or string | The request body parsed as a JavaScript object when Content-Type is application/json, or string for other content types. |
headers | object | A JavaScript object containing the headers received on the proxy request |
method | string | The HTTP method of the proxy request (e.g., "GET", "POST", "PUT", "PATCH", "DELETE") |
path | string | The path suffix received on the proxy request after /proxy (e.g., a request to /proxy/sub/path?param=value would result in a path of /sub/path) |
query | string | The unparsed query string that was received on the proxy request (e.g., a request to /proxy/sub/path?param=value would result in a query of ?param=value) |
Output
An object of the following type must be returned by the transform function:
| Attribute | Type | Description |
|---|---|---|
body | object | The transformed request body to forward to the destination |
headers | object | The transformed request headers to forward to the destination |
Node.js Runtime Contract
Input
The transform function receives an event object containing the HTTP request properties and configuration:
| Attribute | Type | Description |
|---|---|---|
req | object | HTTP request properties (see below) |
configuration | map<string, string> | Configuration values defined on the proxy |
logger | object | Logger instance with info(), warn(), error() methods |
applicationOptions | object | Options available for calling the Basis Theory API from this runtime |
applicationOptions.apiKey | string | Scoped API key generated from runtime.permissions. This value is only available when runtime permissions are configured. |
applicationOptions.baseUrl | string | The Basis Theory API base URL (e.g., https://api.basistheory.com) |
headers | object | Allowlisted Basis Theory headers from the proxy request: bt-merchant-id and bt-trace-id, each present only when received. See Forwarding BT-MERCHANT-ID in Transforms |
The req object contains the HTTP request properties:
| Attribute | Type | Description |
|---|---|---|
body | object or string | The request body parsed as a JavaScript object when Content-Type is application/json, or string for other content types. |
headers | object | A JavaScript object containing the headers received on the proxy request |
method | string | The HTTP method of the proxy request (e.g., "GET", "POST", "PUT", "PATCH", "DELETE") |
path | string | The path suffix received on the proxy request after /proxy (e.g., a request to /proxy/sub/path?param=value would result in a path of /sub/path) |
query | string | The unparsed query string that was received on the proxy request (e.g., a request to /proxy/sub/path?param=value would result in a query of ?param=value) |
Output
To proceed with forwarding the request to the destination, return a req object containing the transformed body and headers. To short-circuit and respond directly without contacting the destination, return a res object instead — see Skip Proxy Request.
| Attribute | Type | Description |
|---|---|---|
req.body | object | The transformed request body to forward to the destination |
req.headers | object | The transformed request headers to forward to the destination |
Skip Proxy Request
A code request transform can skip forwarding to the destination and return a response directly. This is useful for caching, rate limiting, early validation, or authentication checks.
The examples below demonstrate success responses (such as returning cached data). You can also use this approach to return error responses — see Proxy Transform Error Handling.
- node-bt (Deprecated)
- node22 / node24
Throw CustomHttpResponseError to skip proxying and return a custom response:
const { CustomHttpResponseError } = require('@basis-theory/basis-theory-reactor-formulas-sdk-js');
module.exports = async function (req) {
const { args, configuration } = req;
const cacheKey = args.path;
// Check cache (pseudo-code)
const cachedData = getFromCache(cacheKey);
if (cachedData) {
throw new CustomHttpResponseError({
status: 200,
headers: {
'X-Cache': 'HIT',
'Content-Type': 'application/json'
},
body: cachedData
});
}
// Continue with normal proxy flow
return {
body: args.body,
headers: args.headers
};
};
Return a res object to skip proxying and return a custom response:
module.exports = async function (event) {
const { req, configuration, logger } = event;
const cacheKey = req.path;
// Check cache (pseudo-code)
const cachedData = getFromCache(cacheKey);
if (cachedData) {
logger.info('Cache hit', { key: cacheKey });
return {
res: {
statusCode: 200,
headers: {
'X-Cache': 'HIT',
'Content-Type': 'application/json'
},
body: cachedData
}
};
}
// Continue with normal proxy flow
return {
req: {
body: req.body,
headers: req.headers
}
};
};
Tokenize Request Transform
Creates tokens from request data and makes them available for subsequent transforms via identifiers.
Basic Configuration:
{
"type": "tokenize",
"options": {
"token": {
"type": "token",
"data": "sensitive_value"
},
"identifier": "my_token"
}
}
Data Sources for token.data:
- Plaintext: Static string values
- Encrypted expression:
"{{ encrypted | json: '$.data' }}"- Extract data from the headerBT-ENCRYPTED - Request expressions:
"{{ req.card_number }}"- Extract data from request properties
The fingerprint_expression, search_indexes, and mask properties of the token are passed to the token service verbatim and cannot contain req, res, or encrypted expressions.
Token References in the Request Body:
Use tokenize_transform to reference a token created by a request transform:
"{{ tokenize_transform: 'my_token' }}"- The token object"{{ tokenize_transform: 'my_token' | json: '$.id' }}"- The token ID"{{ tokenize_transform: 'my_token' | json: '$.data' }}"- The data supplied to the transform in this request"{{ tokenize_transform: 'my_token' | json: '$.metadata' }}"- The metadata supplied to the transform in this request
When tokenization deduplicates against an existing token, the ID can refer to that existing token. The data and metadata properties contain only values supplied to the transform in this request; stored values omitted from the request are not added. For example, if the transform supplies only metadata.customer_id, other metadata fields from the existing token are not included. Other token properties follow the redaction applied to the tokenization result.
If the transform supplies token.encrypted, data comes from that decrypted payload. A transform that supplies only token_intent_id does not expose data through these references.
In append response transforms, use transform_identifier instead. Those references do not expose the token's data property.
Response Transforms
2xx status code, except code response transforms on a Node.js runtime image. Other response transforms, including node-bt code transforms, are skipped on responses with a status code of 300 or higher (including 3xx redirects, 4xx client errors, and 5xx server errors). If no Node.js runtime code transform changes such a response, it is returned to the caller as-is.| Type | Purpose |
|---|---|
code | Run custom Node.js to mutate the response body or headers, tokenize sensitive values returned by the destination, or detokenize values for inbound flows |
mask | Pattern-based masking using regex or predefined matchers |
tokenize | Create tokens from response data using Liquid expressions or plaintext |
append_json | Add JSON properties to the response payload at a JSONPath location |
append_text | Append plain text to the response body |
append_header | Add HTTP headers to the response |
Code Response Transform
Code Response Transform can be used to:
- Transform the body or headers on the HTTP response received from the destination before returning a response from the proxy
- Tokenize sensitive values returned by a third party destination API
- For inbound HTTP requests, tokens returned in responses from your system can be detokenized before sending the response to the third party caller
Code response transforms run in Basis Theory's serverless runtime environment:
- node-bt (Deprecated)
- node22 / node24
module.exports = async function (req) {
const { bt, args, configuration } = req;
const { body, headers } = args; // access properties of the http response
const { MY_CONFIG } = configuration; // access any static config defined on the Proxy
// do anything here!
const processedBody = ...; // do something to build a transformed body
const processedHeaders = ...; // do something to build transformed headers
return {
body: processedBody, // transformed response body
headers: processedHeaders // transformed request headers
};
};
module.exports = async function (event) {
const { res, configuration, logger, applicationOptions } = event;
const { body, headers } = res; // access properties of the http response
const { MY_CONFIG } = configuration; // access any static config defined on the Proxy
logger.info("Processing response");
// do anything here!
const processedBody = ...; // do something to build a transformed body
const processedHeaders = ...; // do something to build transformed headers
return {
res: {
body: processedBody, // transformed response body
headers: processedHeaders // transformed response headers
}
};
};
What a Code Response Transform Can and Cannot Change
A code response transform can:
- Mutate the response body.
- Mutate the response headers.
- Change the response status code when using a Node.js runtime image. On
node-bt, the status code is read-only. To return a non-2xxstatus from anode-bttransform, throw an error. See Error Handling. - Handle destination errors (
3xx,4xx, and5xxresponses) when using a Node.js runtime image. See Handling Destination Errors.
Like a code request transform, a code response transform can't invoke a Reactor. See Invoke Reactors limitations.
node-bt Code Contract
Input
The transform function receives a request object containing the HTTP response properties and configuration:
| Attribute | Type | Description |
|---|---|---|
args | object | HTTP response properties (see below) |
configuration | map<string, string> | Configuration values defined on the proxy |
bt | object | Pre-configured Basis Theory SDK instance for token operations (if application.id is set) |
applicationOptions | object | Configuration information about the associated application (if application.id is set) |
applicationOptions.apiKey | string | The API key of the associated application |
applicationOptions.baseUrl | string | The Basis Theory API base URL (e.g., https://api.basistheory.com) |
headers | object | Allowlisted Basis Theory headers from the proxy request: bt-merchant-id and bt-trace-id, each present only when received. See Forwarding BT-MERCHANT-ID in Transforms |
The args object contains the HTTP response properties:
| Attribute | Type | Description |
|---|---|---|
body | object or string | The response body returned from the destination endpoint, parsed as a JavaScript object when Content-Type is application/json, or string for other content types. |
headers | object | A JavaScript object containing the response headers returned from the destination endpoint, plus BT-PROXY-DESTINATION-STATUS with the destination's HTTP status code. See Destination Status in Response Transforms |
Output
An object of the following type must be returned by the transform function:
| Attribute | Type | Description |
|---|---|---|
body | object | The transformed response body to return from the proxy |
headers | object | The transformed response headers to return from the proxy |
Node.js Runtime Contract
Input
The transform function receives an event object containing the HTTP response properties and configuration:
| Attribute | Type | Description |
|---|---|---|
res | object | HTTP response properties (see below) |
configuration | map<string, string> | Configuration values defined on the proxy |
logger | object | Logger instance with info(), warn(), error() methods |
applicationOptions | object | Options available for calling the Basis Theory API from this runtime |
applicationOptions.apiKey | string | Scoped API key generated from runtime.permissions. This value is only available when runtime permissions are configured. |
applicationOptions.baseUrl | string | The Basis Theory API base URL (e.g., https://api.basistheory.com) |
headers | object | Allowlisted Basis Theory headers from the proxy request: bt-merchant-id and bt-trace-id, each present only when received. See Forwarding BT-MERCHANT-ID in Transforms |
The res object contains the HTTP response properties:
| Attribute | Type | Description |
|---|---|---|
body | object or string | The response body returned from the destination endpoint, parsed as a JavaScript object when Content-Type is application/json, or string for other content types. |
headers | object | A JavaScript object containing the response headers returned from the destination endpoint, plus BT-PROXY-DESTINATION-STATUS with the destination's HTTP status code. See Destination Status in Response Transforms |
Output
An object of the following type must be returned by the transform function:
| Attribute | Type | Description |
|---|---|---|
res.body | object | The transformed response body to return from the proxy |
res.headers | object | The transformed response headers to return from the proxy |
res.statusCode | number | Optional. Override the HTTP status code returned to the caller. Omit it to keep the destination's status code, including on destination errors. |
Destination Status in Response Transforms
Response transforms receive the destination's HTTP status code in the BT-PROXY-DESTINATION-STATUS header, the same custom header Basis Theory adds to the response returned to the caller. On a Node.js runtime image, the header carries any status the destination returned, so a transform can tell a 200 from a 202, or a successful response from a 400 decline. On node-bt, transforms receive 2xx responses, so the value is always a 2xx code.
Header name casing follows the proxy's header normalization, so look the header up case-insensitively. On a 2xx response, the header is passed to your transforms instead of the response returned to the caller. On a destination error, the caller's response also includes it, with the destination's status code.
On a 2xx response, a transform must return a non-empty body. On the Node.js runtime, an empty string is rejected with a 400 error (Transform response must return a 'body' response property), so when the destination returns no content, as it can with 202 or 204, the transform has to supply one. Keep any body the destination sent, and build a body from the status only when the received one is empty. On a destination error, a Node.js runtime transform that received no body may return none, and the destination's status code and headers are returned.
module.exports = async function (event) {
const { res } = event;
const status = Object.entries(res.headers).find(
([name]) => name.toLowerCase() === "bt-proxy-destination-status"
)?.[1];
if (res.body === "" || res.body == null) {
// the destination returned no content to transform, but a body is still required
return { res: { body: { status }, headers: res.headers } };
}
return { res: { body: res.body, headers: res.headers } };
};
On node-bt, read the same header from args.headers.
Handling Destination Errors
With a Node.js runtime image, your code response transform also receives the destination's 3xx, 4xx, and 5xx responses. Use it to remove card data a destination echoes back in an error, such as a card number in a validation message, or to map each destination's errors to one format, before the response reaches your systems. Errors returned by Basis Theory itself, such as a destination timeout, don't reach the transform.
Error responses often use a different format than successful ones: a different JSON shape, plain text, HTML, or no body at all. When writing a transform that handles errors:
- Check
BT-PROXY-DESTINATION-STATUSbefore reshaping the body, and return anything you don't recognize unchanged. - Omit
res.statusCodeto keep the destination's status code. Set it only to replace that status on purpose: returningstatusCode: 200turns a destination decline into a success for your client. - Don't assume the body is JSON or present. An uncaught error from your code returns a
422instead of the destination's error. See Error Handling.
For example, this transform masks card numbers in text error bodies and in JSON values, and keeps the destination's status. It doesn't change JSON property names, so adapt it if your destination uses card numbers as keys:
// Matches 13 to 19 digits, optionally separated by spaces or dashes, and keeps only the last 4
const maskCardNumbers = (text) =>
text.replace(/\d(?:[ -]?\d){12,18}/g, (match) => {
const digits = match.replace(/\D/g, "");
return "*".repeat(digits.length - 4) + digits.slice(-4);
});
// Masks card numbers in every string and long number value, whatever the body's shape
const mask = (value) => {
if (typeof value === "string") return maskCardNumbers(value);
if (Number.isInteger(value) && value >= 1e12) return maskCardNumbers(String(value));
if (Array.isArray(value)) return value.map(mask);
if (value !== null && typeof value === "object") {
return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, mask(item)]));
}
return value;
};
module.exports = async function (event) {
const { res } = event;
const status = Number(
Object.entries(res.headers).find(
([name]) => name.toLowerCase() === "bt-proxy-destination-status"
)?.[1]
);
if (status >= 300) {
// destination error: mask card numbers and keep the destination's status
return { res: { body: mask(res.body), headers: res.headers } };
}
// successful responses still need a body when the destination sent none, as with 202 or 204
if (res.body === "" || res.body == null) {
return { res: { body: { status }, headers: res.headers } };
}
// transform successful responses as usual
return { res: { body: res.body, headers: res.headers } };
};
Mask Response Transform
Mask response transform can be used to transform the body of the response received from the destination before returning a response from the proxy.
The mask transform has two available matcher types, regex and chase_stratus_pan.
Regex Matcher
Mask response transform using the regex matcher is defined using regular expressions and a replacement character.
{
"name": "My masked proxy",
"destination_url": "https://echo.basistheory.com/anything",
"require_auth": false,
"response_transforms": [
{
"type": "mask",
"matcher": "regex",
"replacement": "*",
"expression": "\"accountNumber\":\\s*\"(.*?)\""
}
]
}
The regular expression must contain at least one capture group.
In the example above, the expression will capture the value of an accountNumber attribute of a JSON payload.
Given the proxied service responds with a JSON similar to the following:
Original Response
{
"username": "bsmith1486",
"accountNumber": "56834512"
}
Then the sample proxy will mask the response as:
Transformed Response
{
"username": "bsmith1486",
"accountNumber": "********"
}
When a response body matches the given expression, the matched part of the body will be processed.
During processing, any portion of the matched body section that is equivalent to any value of a capture group defined in the regex will be replaced.
In this case, the matched body section is "accountNumber": "56834512".
The best practice is to limit the match scope to be as narrow as possible. There could be unintended or unexpected side effects if the match string is larger than necessary.
For example, given a regex defined as ^(aa).*?$, a match will occur when the line starts with "aa".
However, since the regular expression uses the beginning, ^, and end $ syntax, the whole string will be matched and eligible for replacements.
Given a response body of aabbccaabbccaa, the entire body will processed during masking.
ALL values that match the capture group value, in this case aa, will be replaced.
The response body will then be masked as **bbcc**bbcc**.
Chase Stratus PAN Matcher
If your proxy is interfacing with the Chase Stratus service, you may be able to take advantage of a default mask.
The chase_stratus_pan matcher will automatically mask PANs from the Chase Stratus Account Verification and Tokenize responses.
{
"name": "My Chase Stratus proxy",
"destination_url": "<REPLACE WITH CHASE STATUS URL>",
"require_auth": false,
"response_transforms": [
{
"type": "mask",
"matcher": "chase_stratus_pan",
"replacement": "*"
}
]
}
This mask will return responses as follows:
Account Verification
T74VKiwuJZ7TYGXD4navTHDLZG104240726tst844 *******************0929VI 000000000000CT01USANNXNNNXY\r
Tokenize
T74VEqMOciR1n8le3BhTVvl3zJ104240726 *******************0329DI 000000000000TI6559909009126557 \r
Tokenize Response Transform
Creates tokens from response data and makes them available for subsequent transforms via identifiers.
Basic Configuration:
{
"type": "tokenize",
"options": {
"token": {
"type": "token",
"data": "{{ res.card_number }}"
},
"identifier": "response_token"
}
}
Data Sources for token.data:
- Plaintext: Static string values
- Encrypted expression:
"{{ encrypted | json: '$.data' }}"- Extract data from the headerBT-ENCRYPTED - Response expressions:
"{{ res.card_number }}"- Extract data from response properties
Removing Tokenized Fields from the Response:
By default, tokenizing response data does not modify the response body, so the plaintext values you tokenized are still returned to the caller.
Use the optional remove option, an array of JSONPath expressions, to remove fields from the response body after the token is created successfully.
Removal happens before any subsequent transforms run, so an append_json transform later in the chain operates on the already-stripped body.
{
"response_transforms": [
{
"type": "tokenize",
"options": {
"token": {
"type": "card",
"data": {
"number": "{{ res.pan }}",
"cvc": "{{ res.cvv }}"
}
},
"identifier": "cardToken",
"remove": ["$.pan", "$.cvv"]
}
},
{
"type": "append_json",
"options": {
"value": "{{ transform_identifier: 'cardToken' | json: '$.id' }}",
"location": "$.card_token_id"
}
}
]
}
With this configuration, the response returned to the caller contains card_token_id while pan and cvv are absent.
Paths that match nothing are ignored. remove is only supported on tokenize response transforms.
Each remove entry must be a JSONPath made of property or array-index segments starting at the root, for example $.card.number or $.cards[0].cvv. Wildcards, recursive descent, and filter expressions are not supported. A transform can have at most 10 paths, each up to 256 characters, with no duplicates. Configurations that violate these rules are rejected when the proxy is created or updated.
Expression Fields Are Passed Through Verbatim:
The fingerprint_expression, search_indexes, and mask properties of the token in a tokenize transform (request or response) are expressions the token service evaluates against the token's data.
The proxy passes them through verbatim; they cannot contain req, res, or encrypted expressions, and configurations embedding those expressions in these fields are rejected when the proxy is created or updated.
Append JSON Response Transform
Add JSON properties to response payload at specified locations using JSONPath expressions.
Basic Configuration:
{
"type": "append_json",
"options": {
"value": "{{ transform_identifier: 'response_token' | json: '$.id' }}",
"location": "$.created_token_id"
}
}
Append Text Response Transform
Appends plain text content to the end of response body.
Basic Configuration:
{
"type": "append_text",
"options": {
"value": "Token ID: {{ transform_identifier: 'response_token' | json: '$.id' }}"
}
}
Append Header Response Transform
Add HTTP headers to response with values that can reference tokens from previous transforms.
Basic Configuration:
{
"type": "append_header",
"options": {
"value": "{{ transform_identifier: 'response_token' | json: '$.id' }}",
"location": "X-Token-ID"
}
}
Token References in Response Transforms: All append transforms support referencing tokens created by previous transforms using:
"{{ transform_identifier: 'identifier' }}"- The token object withdataredacted"{{ transform_identifier: 'identifier' | json: '$.path' }}"- Extract specific data with JSONPath
The token's data property is unavailable through transform_identifier.
Tokenizing or Detokenizing
In some situations, you may want to tokenize or detokenize data with Code Request Transform or Code Response Transform. In order to do this,
set the application.id property when creating your Proxy with the id of an
Application that has been granted the desired permissions.
This will inject a Basis Theory JS instance into the transform request
that is pre-configured for this application. For example:
- node-bt (Deprecated)
- node22 / node24
module.exports = async function (req) {
const token = await req.bt.tokenize({
type: "token",
data: req.args.body.sensitive_value,
});
req.args.body.sensitive_value = token.id;
return {
body: req.args.body,
headers: req.args.headers,
};
};
In the above example, we utilized the injected Basis Theory JS instance to tokenize a property called sensitive_value on our request body
and passed the token back as the updated sensitive_value to be forwarded to the configured destination_url on our Proxy.
const { BasisTheoryClient } = require("@basis-theory/node-sdk");
module.exports = async function (event) {
const { req, applicationOptions, logger } = event;
const client = new BasisTheoryClient({
apiKey: applicationOptions.apiKey,
baseUrl: applicationOptions.baseUrl,
});
const token = await client.tokens.create({
type: "token",
data: req.body.sensitive_value
});
logger.info("Token created", { tokenId: token.id });
return {
req: {
headers: req.headers,
body: { ...req.body, sensitive_value: token.id }
}
};
};
For Node.js runtime images, add @basis-theory/node-sdk to your runtime.dependencies and include the token permissions your transform needs in runtime.permissions. For example, include token:create when creating tokens.
Forwarding BT-MERCHANT-ID in Transforms
When a proxy request includes a BT-MERCHANT-ID header, the request acts as that tenant merchant. Basis Theory API calls made inside a code transform are separate requests: BT-MERCHANT-ID and BT-TRACE-ID are never auto-forwarded onto them, consistent with BT-API-KEY, which is never forwarded. An internal call without the header runs at the tenant level, counting against the tenant's rate limits rather than the merchant's.
Code transforms receive the allowlisted Basis Theory headers on the top-level headers property of the transform input, keyed in lowercase: bt-merchant-id and bt-trace-id, each present only when received. This is a different object from the HTTP request headers your transform forwards to the destination (args.headers on node-bt, req.headers on Node.js runtime images); those exclude BT-MERCHANT-ID.
To keep internal calls attributed to the merchant, forward the header explicitly on each call:
const { BasisTheoryClient } = require("@basis-theory/node-sdk");
module.exports = async function (event) {
const { req, headers, applicationOptions, logger } = event;
const client = new BasisTheoryClient({
apiKey: applicationOptions.apiKey,
baseUrl: applicationOptions.baseUrl,
});
const token = await client.tokens.create(
{ type: "token", data: req.body.sensitive_value },
{ headers: { "BT-MERCHANT-ID": headers["bt-merchant-id"] } }
);
logger.info("Token created as the acting merchant", { tokenId: token.id });
return {
req: {
headers: req.headers,
body: { ...req.body, sensitive_value: token.id }
}
};
};
A header entry with an undefined value is not sent, so this pattern is safe when the proxy is also called without a BT-MERCHANT-ID header: the internal call simply runs at the tenant level.
For the same pattern in Reactors, including a node-bt example, see Forwarding BT-MERCHANT-ID in Reactors and Proxy Transforms.
Testing and Dependencies
Testing transforms works the same as testing Reactors.
npm modules
node-bt only supports a curated set of npm modules — see the list of available modules.
Node.js runtime images have no dependency whitelist. You can install any npm package by specifying it in runtime.dependencies.
For deployment-time and continuous dependency scanning details, see Runtime Vulnerability Scanning.
Plaintext Secrets in Transform Code
Transform source is scanned for plaintext secrets on proxy create, update, and patch, and writes that contain one are rejected. Supply credentials through the Proxy's encrypted configuration object instead. See Plaintext Secret Scanning for what is detected, what the scan deliberately allows, and how to check your source before you deploy it.
Error Handling
For information on handling errors in proxy transforms, including error types, response formats, and best practices, see Error Handling.
API Reference
For complete API documentation including all parameters and SDK examples: