Utilities
The @arcblock/did-connect-react library exports a collection of utility functions designed to simplify common tasks related to authentication flows, data handling, and API communication. While the core components and hooks handle most use cases, these utilities offer granular control for advanced integrations or custom implementations.
API Client#
createAxios#
This function is a factory for creating a pre-configured axios instance. It automatically includes essential headers like x-did-connect-version and x-blocklet-visitor-id, ensuring proper communication with Blocklet-based services. It's the recommended way to create API clients in your application.
Parameters
Returns
Example
apiClient.js
import { createAxios } from '@arcblock/did-connect-react/lib/utils';
const apiClient = createAxios({
baseURL: '/api',
});
export default apiClient;URL and Popup Handling#
These functions help manage the URLs and popup windows used during the DID Connect authentication process.
Function | Description |
|---|---|
| Encodes a URL to be safely passed as a |
| Decodes a URL that was encoded with |
| Extracts the session token ( |
| Opens a new, centered popup window. It's used internally by the |
| A promise-based wrapper that manages the lifecycle of a popup created with |
| Parses custom |
Example: Custom Popup Flow
customAuthButton.js
import { openPopup, runPopup } from '@arcblock/did-connect-react/lib/utils';
const handleCustomLogin = async () => {
const authUrl = 'https://your-auth-service.com/connect';
try {
const popup = openPopup(authUrl);
const result = await runPopup({ popup, timeoutInSeconds: 600 });
console.log('Authentication successful:', result);
// Handle successful login
} catch (error) {
console.error('Authentication failed:', error.message);
// Handle popup closed or timeout
}
};Session and Cookie Management#
These helpers are used to read and write user connection information to cookies, enabling session persistence across page loads.
Function | Description |
|---|---|
| Formats the raw response data from a connection request into a standardized object suitable for cookie storage. |
| Sets the necessary cookies ( |
| Retrieves the unique visitor ID from cookies. |
| Sets the unique visitor ID in cookies. |
Example
sessionManager.js
import { getConnectedInfo, updateConnectedInfo } from '@arcblock/did-connect-react/lib/utils';
// Assuming 'authResponse' is the object returned from your login API
function persistSession(authResponse) {
const connectedInfo = getConnectedInfo(authResponse);
updateConnectedInfo(connectedInfo, true);
console.log('Session info saved to cookies.');
}Encryption Utilities#
For advanced scenarios requiring client-side encryption or decryption, the library exposes helpers that wrap the tweetnacl-sealedbox-js library.
Function | Description |
|---|---|
| Base64URL encodes a key for transmission. |
| Decodes a Base64URL string into a |
| Encrypts a string value using a public key. |
| Decrypts a base64 string using the corresponding public and private keys. |
Error Handling#
To provide better feedback to users, you can use these functions to parse technical error objects into human-readable messages.
Function | Description |
|---|---|
| Extracts a user-friendly error message from an |
| Handles WebAuthn/Passkey specific errors (e.g., user cancellation, browser not supported) and returns localized, user-friendly messages. |
Example
errorHandling.js
import { getApiErrorMessage } from '@arcblock/did-connect-react/lib/utils';
import apiClient from './apiClient';
async function fetchData() {
try {
const response = await apiClient.get('/data');
return response.data;
} catch (error) {
const message = getApiErrorMessage(error, 'Failed to fetch data.');
alert(message);
}
}By leveraging these utilities, you can build more complex and customized authentication experiences. For a complete list of all exported members and their types, please refer to the API Reference.