Skip to main content

Services

Basis Theory Elements offers several methods and to interact with the underlying data and services to collect or share data safely.

Methods

Once you have created and mounted an element instance, you can invoke the methods below:

<div id="my-card"></div>

<script>
var cardElement = BasisTheory.createElement("card");
await cardElement.mount("#my-card");

cardElement.focus();
</script>
NameResulting TypeEligible ElementsDescription
clearvoidAllClears the element input(s) value.
focusvoidAllFocuses on the element input.
blurvoidAllBlurs the element input.
monthnumbercardExpirationDateData-parsing method that resolves to the month value of the input date, where "January" = 1.
yearnumbercardExpirationDateData-parsing method that resolves to the four-digit year value of the input date.
format*stringcardExpirationDateData-parsing method that takes a date format as an argument and returns the expiration date in the given format.
setValuevoidAllAccepts a synthetic reference from a retrieved token and safely sets it as the input value.
setValueRef*voidtext
cardNumber
cardExpirationDate
cardElement
cardVerificationCode
Sets the element's value to the value of the provided element.

Format*

Our card expiration date format implements Luxon's toFormat, so all of Luxon's date formatting tokens are available.

Card Expiration Date format example
const cardExpirationDateElement = BasisTheory.createElement("cardExpirationDate", {
targetId: "expirationDate",
value: "04/25",
});

...

const requestBody = {
...
expiration_date1: cardExpirationDateElement.format("yyyy-MM"), // 2025-04
expiration_date2: cardExpirationDateElement.format("MM"), // 04
expiration_date3: cardExpirationDateElement.format("M"), // 4
expiration_date4: cardExpirationDateElement.format("MM/yyyy"), // 04/2025
expiration_date5: cardExpirationDateElement.format("yy"), // 25
...
}

setValueRef*

Sets the element's value to the value of the provided element.

Card Expiration Date setValueRef example
const cardExpirationDateElement = BasisTheory.createElement("cardExpirationDate", {
targetId: "expirationDate",
value: "04/25",
});

const cardExpirationDateElementReadOnly = BasisTheory.createElement("cardExpirationDate", {
targetId: "expirationDateReadOnly",
readOnly: true
});

cardExpirationDateElementReadOnly.setValueRef(cardExpirationDateElement)

cardExpirationDateElementReadOnly will be updated every time the value of cardExpirationDateElement changes.

When using setValueRef to keep an element in sync with another element, or to set the text of an element, it is strongly recommended that you make the element that is being acted upon readonly. This is possible by setting readOnly to true.

Tokenization Services

Elements' values can be securely tokenized by simply passing the Element instance (or one of its data parsing methods) in the tokenization payload.

The actual input data never leaves the element (iframe) other than to hit our secure API endpoints.
When submitting plainText values, data will be HTML encoded before storage for security reasons.

Create Token

The examples below show how to use Elements' instances in the payload of the tokens.create service.

Create generic token
BasisTheory.tokens
.create({
type: "token",
data: {
sensitiveData: sensitiveDataElement,
nonSensitiveData: "plainText", // see warning on plain text data
otherData: {
someInteger: 20,
someBoolean: false,
},
someOtherData: ["plainText1", "plainText2"],
},
metadata: {
nonSensitiveField: "nonSensitiveValue",
},
})
.then((token) => {
console.log(token.id); // token to store
console.log(JSON.stringify(token)); // full response
});
Create card token
BasisTheory.tokens
.create({
type: "card",
data: cardElement,
})
.then((token) => {
console.log(token.id); // token to store
console.log(JSON.stringify(token.data)); // redacted card data
});
Create bank token
BasisTheory.tokens
.create({
type: "bank",
data: {
routingNumber: routingNumberElement,
accountNumber: accountNumberElement,
},
})
.then((token) => {
console.log(token.id); // token to store
console.log(JSON.stringify(token.data)); // redacted bank data
});

Tokenize

The example below shows how to use Elements' instances in the payload of the tokenize service.

Tokenize data
BasisTheory.tokenize({
card1: {
type: "card",
data: cardElement,
},
card2: {
type: "card",
data: {
number: cardNumberElement,
expiration_month: cardExpirationDateElement.month(),
expiration_year: cardExpirationDateElement.year(),
cvc: cardVerificationCodeElement,
},
},
sensitiveData: sensitiveDataElement,
nonSensitiveData: "plainText", // see warning on plain text data
otherData: {
someInteger: 20,
someBoolean: false,
},
someOtherData: ["plainText1", "plainText2"],
}).then((tokens) => {
console.log(tokens.card1.id, tokens.card2.id, tokens.sensitiveData); // token to store
console.log(JSON.stringify(tokens)); // full response
});

Token Update

Aside from creating tokens, an Element value can be used to update a token using tokens.update. To do that, simply pass the Element instance (or one of its data parsing methods) in the payload.

BasisTheory.tokens
.update("ca9f3fd7-3906-4087-83aa-9a6129221297", {
// replace w/ desired token id
data: cardElement,
})
.then((token) => {
console.log(JSON.stringify(token.data)); // redacted updated token data
});

Detokenization Services

Elements' values can be securely detokenized and revealed using these detokenization services and the Elements' setValue method.

Retrieve Token

When retrieve is called from a Basis Theory instance configured with elements: true, the API request is made from inside a Basis Theory hosted iframe and the returned data remains within it. The examples below show how to use retrieve and setValue, but for more information on revealing and session keys, visit the Reveal Tokenized Data guide.

Retrieve 'string' token data and set value into TextElement
const textElement = BasisTheory.createElement("text", {
targetId: "text-element",
});

BasisTheory.tokens
.retrieve("ca9f3fd7-3906-4087-83aa-9a6129221297", {
apiKey: "<SESSION_API_KEY>", // api key is required and should belong to a session
})
.then((token) => {
textElement.setValue(token.data);
});
Retrieve card token and set value into CardElement
const cardElement = BasisTheory.createElement("card");

BasisTheory.tokens
.retrieve("ca9f3fd7-3906-4087-83aa-9a6129221297", {
apiKey: "<SESSION_API_KEY>", // api key is required and should belong to a session
})
.then((token) => {
cardElement.setValue(token.data);
});

// or

BasisTheory.tokens
.retrieve("ca9f3fd7-3906-4087-83aa-9a6129221297", {
apiKey: "<SESSION_API_KEY>", // api key is required and should belong to a session
})
.then((token) => {
cardElement.setValue({
number: token.data.number, // expects string
expiration_month: token.data.expiration_month, // expects number
expiration_year: token.data.expiration_year, // expects number
});
});
Retrieve card token and set value into split card elements
const cardNumberElement = BasisTheory.createElement("cardNumber", {
targetId: "card-number",
});
const cardExpirationDateElement = BasisTheory.createElement("cardExpirationDate", { targetId: "card-expiration-date" });

BasisTheory.tokens
.retrieve("ca9f3fd7-3906-4087-83aa-9a6129221297", {
apiKey: "<SESSION_API_KEY>", // api key is required and should belong to a session
})
.then((token) => {
cardNumberElement.setValue(token.data.number);
cardExpirationDateElement.setValue({
month: token.data.expiration_month,
year: token.data.expiration_year,
});
});
The data attribute in the token returned by the retrieve method is not the actual data, but a a synthetic representation of the sensitive detokenized data.
Token attributes such as metadata are directly accessible from the retrieve response as they are considered non-sensitive.

Proxy Service

This service wraps the proxy API endpoint to proxy a request to a third-party API.

Invoking Proxy

When a proxy is invoked from a Basis Theory instance configured with elements: true, the API request is made from inside a Basis Theory hosted iframe and the returned data remains within it, whether the proxy has Elements instances in its body or not. The examples below show how to invoke the proxy and use setValue, but for more information on revealing and session keys, visit the Reveal Data from 3rd Party guide. Elements can be used to proxy data securely by including them in the proxy body as shown in the example.

Invoking Pre-Configured Proxy w/ POST
const submitElement = BasisTheory.createElement("text", {
targetId: "submitElement",
});
const revealElement = BasisTheory.createElement("text", {
targetId: "revealElement",
});

BasisTheory.proxy
.post({
headers: {
"BT-PROXY-KEY": "e29a50980ca5", // replace with your pre-configured proxy key (if pre-configured)
},
body: {
sensitiveValue: submitElement,
nonSensitiveValue: "plainText",
},
apiKey: "<SESSION_API_KEY>",
})
.then((response) => {
revealElement.setValue(response.value);
});
The proxy response object returned after invoking it with elements is not the actual data, but a a synthetic representation of the sensitive data.

Proxy Invocation Methods

The Elements proxy service supports all of the same HTTP methods that the ephemeral or pre-configured proxy APIs support. All proxy calls take the same options object as a parameter.

SignatureDescription
get(proxyRequest: ProxyRequestOptions)Performs a proxy GET request.
post(proxyRequest: ProxyRequestOptions)Performs a proxy POST request.
put(proxyRequest: ProxyRequestOptions)Performs a proxy PUT request.
patch(proxyRequest: ProxyRequestOptions)Performs a proxy PATCH request.
delete(proxyRequest: ProxyRequestOptions)Performs a proxy DELETE request.

ProxyRequestOptions

AttributeTypeRequiredDescription
pathstringfalseString that gets added to the end of the proxied URL path.
queryobjectfalseKey/Value pairs that are added as a query parameter to the proxied URL.
headersobjectfalseKey/Value pairs that are added as headers when invoking the proxied URL.
bodyobjectfalsePayload that gets sent to the proxied URL. Can contain Elements.
apiKeyobjectfalseBasisTheory API Key for authentication
correlationIdobjectfalseID that can be used for request correlation
idempotencyKeyobjectfalseKey used for request idempotency

Access non-sensitive responses from Proxy calls
Beta

Our Elements enable you to convert proxy responses into plain text, which is ideal for non-sensitive data handling. This enhancement streamlines your data processing workflows and facilitates an easier understanding of the returned data, bypassing decryption or tokenization.

This feature is currently invite-only. If you're interested, please get in touch for an invitation.

You can capture values from any of our Elements; hence we strongly recommend only using this feature for non-sensitive data. Converting proxy responses to plain text can expose the underlying data to risks, such as unauthorized access or leakage. Ensure the plain-text proxy responses align with your data security policy, data handling practices, and compliance obligations. If you're unsure, please get in touch for guidance at www.basistheory.com/contact

HTTP Client Service

Element values can be used in a request to a third-party API using our HTTP client service.

Post

The example below shows how to use the HTTP client service to make a POST request to a third-party API with an element in the payload.

Invoking HTTP Client Service w/ POST
const bt = await new BasisTheory().init("<API_KEY>", { elements: true });

bt.client.post(
"https://www.api.thirdpartydomain.com/resources",
{
sensitiveData: sensitiveDataElement,
nonSensitiveData: "plainText", // see warning on plain text data
otherData: {
someInteger: 20,
someBoolean: false,
},
someOtherData: ["plainText1", "plainText2"],
},
{
headers: {
"Content-Type": "application/json",
},
}
).then((response) => {
console.log(JSON.stringify(response)); // full plaintext response
});
The response from this service is the actual plaintext data. It may contain sensitive data depending on the third-party API response.

Put

The example below shows how to use the HTTP client service to make a PUT request to a third-party API with an element in the payload.

Invoking HTTP Client Service w/ PUT
const bt = await new BasisTheory().init("<API_KEY>", { elements: true });

bt.client.put(
"https://www.api.thirdpartydomain.com/resources/id",
{
sensitiveData: sensitiveDataElement,
nonSensitiveData: "plainText", // see warning on plain text data
otherData: {
someInteger: 20,
someBoolean: false,
},
someOtherData: ["plainText1", "plainText2"],
},
{
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
}
).then((response) => {
console.log(JSON.stringify(response)); // full plaintext response
});
The response from this service is the actual plaintext data. It may contain sensitive data depending on the third-party API response.

Patch

The example below shows how to use the HTTP client service to make a PATCH request to a third-party API with an element in the payload.

Invoking HTTP Client Service w/ PATCH
const bt = await new BasisTheory().init("<API_KEY>", { elements: true });

bt.client.patch(
"https://www.api.thirdpartydomain.com/resources/id",
{
sensitiveData: sensitiveDataElement,
nonSensitiveData: "plainText", // see warning on plain text data
otherData: {
someInteger: 20,
someBoolean: false,
},
someOtherData: ["plainText1", "plainText2"],
},
{
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
}
).then((response) => {
console.log(JSON.stringify(response)); // full plaintext response
});
The response from this service is the actual plaintext data. It may contain sensitive data depending on the third-party API response.

Get

The example below shows how to use the HTTP client service to make a GET request to a third-party API.

Invoking HTTP Client Service w/ GET
const bt = await new BasisTheory().init("<API_KEY>", { elements: true });

bt.client.get("https://www.api.thirdpartydomain.com/resources/id", {
headers: {
Accept: "application/json",
},
}).then((response) => {
console.log(JSON.stringify(response)); // full plaintext response
});
The response from this service is the actual plaintext data. It may contain sensitive data depending on the third-party API response.

Delete

The example below shows how to use the HTTP client service to make a DELETE request to a third-party API.

Invoking HTTP Client Service w/ DELETE
const bt = await new BasisTheory().init("<API_KEY>", { elements: true });

bt.client.delete("https://www.api.thirdpartydomain.com/resources/id", {
headers: {
Accept: "application/json",
},
}).then((response) => {
console.log(JSON.stringify(response)); // full plaintext response
});
The response from this service is the actual plaintext data. It may contain sensitive data depending on the third-party API response.

Errors

Basis Theory Service Errors

Basis Theory element services could throw an error based on client-side validations or if the server rejects the request.

Handling services errors
import { BasisTheoryApiError, BasisTheoryValidationError } from "@basis-theory/basis-theory-js/common";

BasisTheory.tokenize({
card1: {
type: "card",
data: cardElement1,
},
card2: {
type: "card",
data: cardElement2,
},
ssn: textElement,
}).catch((error) => {
if (error instanceof BasisTheoryValidationError) {
// only applies to tokenization
// check error details
} else if (error instanceof BasisTheoryApiError) {
// check error data or status
}
});

HTTP Client Service Errors

HTTP client services could throw an error based on client-side validations or if the server rejects the request.

Handling services errors
import { HttpClientError, BasisTheoryValidationError } from "@basis-theory/basis-theory-js/common";

const bt = await new BasisTheory().init("<API_KEY>", { elements: true });

bt.client.post({
sensitiveData: textElement,
}).catch((error) => {
if (error instanceof BasisTheoryValidationError) {
// check error details
} else if (error instanceof HttpClientError) {
// check error data, status, or headers
}
});

BasisTheoryValidationError

{
details: {
card1: {
number: {
type: 'invalid'
},
cvc: {
type: 'incomplete'
}
},
card2: {
}
},
validation: [] // deprecated
}
AttributeTypeDescription
namestringError name, always 'BasisTheoryValidationError'.
detailsobjectMaps payload properties to their respective element's validation problems.

BasisTheoryApiError

{
data: {
// API response body
},
status: 400
}
AttributeTypeDescription
namestringError name, always 'BasisTheoryApiError'.
dataobjectResponse body sent from the server.
statusnumberResponse HTTP status.
Error name property may be used instead of checking its instance type.

HttpClientError

{
data: {...},
status: 400,
headers: {...}
}
AttributeTypeDescription
namestringError name, always 'HttpClientError'.
dataobjectResponse body sent from the server.
statusnumberResponse HTTP status.
headersobjectResponse HTTP headers.
The response from this service is the actual plaintext data. It may contain sensitive data depending on the third-party API response.