Initialization
This document covers setting up Elements in your project, from installation to initialization, with examples for common scenarios.
Installation Options
- Web Elements
- React Elements
- npm
- yarn
- CDN
npm install --save @basis-theory/web-elements
yarn add @basis-theory/web-elements
1 <!-- Including this tag will export a global/window "basistheory" variable -->2 <!--3 You can either pin the version to a specific release for stability4 or use the latest tag to always pull the most recent version.5 However, relying on latest can be risky, as it may introduce unexpected changes or breaking updates.6 For detailed information about each version, refer to our changelog.7 -->89 <script src="https://js.basistheory.com/web-elements/latest/index.js"></script>10 <!-- or -->11 undefined
https://js.basistheory.com/sri/?version=<YOUR VERSION>
. For a complete list of published hashes, please refer to our Github repository. - npm
- yarn
npm install --save @basis-theory/react-elements
yarn add @basis-theory/react-elements
@basis-theory/web-elements
separately as it's included as a dependency.>1.12.1
is not compatible with Create React App v5.0.0
or above due to a known issue.Initialization
- Web Elements
- React Elements
- ES Module
- CDN
import { basistheory } from "@basis-theory/web-elements";
// Async initialization
const bt = await basistheory("<PUBLIC_API_KEY>");
// Now bt is ready to use
const cardElement = bt.createElement('card', {
targetId: 'my-card'
});
<script src="https://js.basistheory.com/web-elements/latest/index.js"></script>
<script>
// Initialize after the window loads
document.addEventListener("DOMContentLoaded", async () => {
try {
// Global basistheory function from the CDN
const bt = await basistheory("<PUBLIC_API_KEY>");
// Create elements after initialization
const cardElement = bt.createElement('card', {
targetId: 'my-card'
});
cardElement.mount('#card-container');
} catch (error) {
console.error("Failed to initialize Elements:", error);
}
});
</script>
import { useBasisTheory, BasisTheoryProvider } from "@basis-theory/react-elements";
function App() {
// The useBasisTheory hook handles initialization asynchronously
const { bt, error } = useBasisTheory("<PUBLIC_API_KEY>");
// Handle loading state
if (!bt) {
return <div>Loading Elements...</div>;
}
// Handle initialization errors
if (error) {
return <div>Error initializing Elements: {error.message}</div>;
}
return (
// Provide the instance to your component tree
<BasisTheoryProvider bt={bt}>
<YourApp />
</BasisTheoryProvider>
);
}
Initialization Options
Property | Default Value | Description |
---|---|---|
debug | false | When enabled, the library will append a debug object to every response payload to help you trace and diagnose rendering or integration issues step by step. |
disableTelemetry | false | Opts out of sending anonymous usage metrics, error reports, and performance data back to Basis Theory. |
useSameOriginApi | true | Routes all API calls through the same origin (https://js.basistheory.com/api ), leveraging HTTP/2 connection reuse and eliminating CORS preflight overhead—resulting in lower latency and fewer round-trips. |
Best Practices
- Single Instance: Create one Elements instance and share it throughout your application
- Loading States: Show appropriate loading indicators while Elements initialize
- Error Handling: Always wrap initialization in try/catch blocks
- Lazy Loading: For applications where Elements are only needed in specific sections, consider lazy-loading the Elements library
- API Key Security: Only use Public API keys in frontend code
*.basistheory.com
domains for both script sources and frame-src directives.Framework-Specific Setup
Next.js
When using Basis Theory Elements with Next.js, you need to ensure the Elements are only initialized on the client side. This is because Elements require browser-specific APIs and DOM access.
Here's how to properly set up Elements in a Next.js application:
// components/CreditCardForm.tsx
"use client";
import { useRef } from "react";
import { CardElement, useBasisTheory } from "@basis-theory/react-elements";
const CreditCardForm = () => {
const cardRef = useRef<ICardElement | null>(null);
const { bt } = useBasisTheory(process.env.NEXT_PUBLIC_BASIS_THEORY_KEY);
const handleSubmit = async (event: React.FormEvent) => {
event.preventDefault();
try {
const token = await bt.tokens.create({
type: "card",
data: cardRef.current,
});
// Handle the token
} catch (err) {
console.error("Tokenization error", err);
}
};
return (
<form onSubmit={handleSubmit}>
<CardElement id="card" bt={bt} ref={cardRef} />
<button type="submit">Submit</button>
</form>
);
};
export default CreditCardForm;
For a complete Next.js implementation example, check out our Next.js Example Repository.
Nuxt.js
For Nuxt.js applications, you'll need to set up Elements as a client-side plugin. Here's how to configure it:
// plugins/basistheory.js
import Vue from "vue";
import { basistheory } from "@basis-theory/web-elements";
export default async ({ $config }, inject) => {
try {
const bt = await basistheory(process.env.BASIS_PUBLIC_API_KEY);
inject("bt", bt);
} catch (e) {
console.error("Basis Theory init error", e);
}
};
// nuxt.config.js
export default {
plugins: [{ src: "~/plugins/basistheory.js", mode: "client" }],
build: {
transpile: ["@basis-theory/web-elements"],
},
publicRuntimeConfig: {
basisPublicApiKey: process.env.BASIS_PUBLIC_API_KEY,
},
};
For a complete Nuxt.js implementation example, check out our Nuxt.js Example Repository.
Don't see your framework here? We're happy to help you integrate Basis Theory Elements with your specific tech stack. Reach out to us support@basistheory.com
Troubleshooting Initialization
If you encounter any issues during initialization, such as Elements not loading or displaying correctly, please refer to our troubleshooting guide.
For specific environment configurations like Content Security Policy settings, see the CSP documentation.
For framework specific considerations visit this section.