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

options
object
Standard Axios configuration object.
lazyOptions
object
Configuration for lazy sending.
2 subfields

Returns

axiosInstance
AxiosInstance
A configured instance of Axios.

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

encodeConnectUrl(url)

Encodes a URL to be safely passed as a __connect_url__ query parameter.

decodeConnectUrl(encoded)

Decodes a URL that was encoded with encodeConnectUrl.

parseTokenFromConnectUrl(connectUrl)

Extracts the session token (_t_) from a DID Connect URL.

openPopup(url, options)

Opens a new, centered popup window. It's used internally by the DidConnect component to display the wallet connection interface. Throws a NotOpenError if the popup is blocked.

runPopup(config)

A promise-based wrapper that manages the lifecycle of a popup created with openPopup. It listens for message events from the popup, handles timeouts, and resolves when the authentication flow is complete.

decodeUrlParams()

Parses custom __did-connect__ parameters from the current window's URL.

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
  }
};

These helpers are used to read and write user connection information to cookies, enabling session persistence across page loads.

Function

Description

getConnectedInfo(data)

Formats the raw response data from a connection request into a standardized object suitable for cookie storage.

updateConnectedInfo(info, parsed)

Sets the necessary cookies (connected_did, connected_pk, connected_app) after a successful connection. This allows the library to optimize subsequent authentication checks.

getVisitorId()

Retrieves the unique visitor ID from cookies.

setVisitorId(id)

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

encodeKey(key)

Base64URL encodes a key for transmission.

decodeKey(str)

Decodes a Base64URL string into a Uint8Array key.

encrypt(value, encryptKey)

Encrypts a string value using a public key.

decrypt(value, encryptKey, decryptKey)

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

getApiErrorMessage(err, defaultMessage)

Extracts a user-friendly error message from an axios error object.

getWebAuthnErrorMessage(err, defaultMessage, t)

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.