SwarmIdClient API Reference
The SwarmIdClient is the main class for integrating Swarm ID authentication and storage capabilities into web applications. It enables parent windows to interact with a Swarm ID iframe proxy, providing secure authentication, identity management, and data upload/download functionality to the Swarm decentralized storage network.
Installation
pnpm add @swarm-id/libQuick Start
import { SwarmIdClient } from '@swarm-id/lib'
const client = new SwarmIdClient({ iframeOrigin: 'https://swarm-id.example.com', metadata: { name: 'My App', description: 'A decentralized application' }, onAuthChange: (authenticated) => { console.log('Auth status changed:', authenticated) }})
await client.initialize()
// Option 1: Open authentication page manuallyconst authUrl = client.connect()console.log('Authentication opened at:', authUrl)
// Option 2: Check authentication status and upload if authenticatedconst status = await client.checkAuthStatus()if (status.authenticated) { const result = await client.uploadData(new Uint8Array([1, 2, 3])) console.log('Uploaded with reference:', result.reference)}Constructor
new SwarmIdClient(options)
Creates a new SwarmIdClient instance.
Parameters:
| Parameter | Type | Required | Description |
|---|---|---|---|
options.iframeOrigin | string | Yes | The origin URL where the Swarm ID proxy iframe is hosted |
options.iframePath | string | No | The path to the proxy iframe (defaults to "/proxy") |
options.timeout | number | No | Request timeout in milliseconds (defaults to 30000) |
options.onAuthChange | (authenticated: boolean) => void | No | Callback function invoked when authentication status changes |
options.popupMode | "popup" | "window" | No | How to display the authentication popup (defaults to "window") |
options.metadata | AppMetadata | Yes | Application metadata shown to users during authentication |
options.metadata.name | string | Yes | Application name (1-100 characters) |
options.metadata.description | string | No | Application description (max 500 characters) |
options.metadata.icon | string | No | Application icon as a data URL (SVG or PNG, max 4KB) |
options.buttonConfig | ButtonConfig | No | Button configuration for the authentication UI |
options.containerId | string | No | ID of container element to place iframe in (optional) |
Throws: Error if the provided app metadata is invalid
Example:
const client = new SwarmIdClient({ iframeOrigin: 'https://id.swarm.example.com', timeout: 60000, metadata: { name: 'My dApp', description: 'A decentralized application built on Swarm', icon: 'data:image/svg+xml;base64,...' }, onAuthChange: (authenticated) => { updateUI(authenticated) }})Lifecycle Methods
initialize()
Initializes the client by creating and embedding the proxy iframe.
This method must be called before using any other client methods. It creates a hidden iframe, waits for the proxy to initialize, identifies the parent application to the proxy, and waits for the proxy to signal readiness.
Returns: Promise<void> - Resolves when the client is fully initialized
Throws:
Errorif the client is already initializedErrorif the iframe fails to loadErrorif the proxy does not respond within the timeout period (10 seconds)Errorif origin validation fails on the proxy side
Example:
const client = new SwarmIdClient({ ... })try { await client.initialize() console.log('Client ready')} catch (error) { console.error('Failed to initialize:', error)}destroy()
Destroys the client and releases all resources.
This method should be called when the client is no longer needed. It performs the following cleanup:
- Cancels all pending requests with an error
- Removes the message event listener
- Removes the iframe from the DOM
- Resets the client to an uninitialized state
After calling destroy(), the client instance cannot be reused. Create a new instance if you need to reconnect.
Returns: void
Example:
// Clean up when component unmountsuseEffect(() => { const client = new SwarmIdClient({ ... }) client.initialize()
return () => { client.destroy() }}, [])Authentication Methods
getAuthIframe()
Returns the authentication iframe element.
The iframe displays authentication UI based on the current auth status:
- If not authenticated: shows a “Connect” button
- If authenticated: shows identity info and a “Disconnect” button
The iframe is positioned fixed in the bottom-right corner of the viewport.
Returns: HTMLIFrameElement - The iframe element displaying the authentication UI
Throws:
Errorif the client is not initializedErrorif the iframe is not available
Example:
const iframe = client.getAuthIframe()// The iframe is already displayed; this returns a reference to itButton Configuration
The authentication button in the iframe can be customized using the buttonConfig option in the constructor. This configuration allows you to customize the button text, colors, and styling.
ButtonConfig Interface:
interface ButtonConfig { connectText?: string disconnectText?: string loadingText?: string backgroundColor?: string color?: string borderRadius?: string}Example: Customizing Button Configuration
const client = new SwarmIdClient({ iframeOrigin: 'https://swarm-id.example.com', metadata: { name: 'My App', description: 'A decentralized application' }, buttonConfig: { connectText: 'Connect with Swarm', disconnectText: 'Disconnect', loadingText: 'Loading...', backgroundColor: '#4CAF50', color: 'white', borderRadius: '8px' }, onAuthChange: (authenticated) => { console.log('Auth status changed:', authenticated) }})
await client.initialize()ButtonConfig Properties:
| Property | Type | Required | Description | Default Value |
|---|---|---|---|---|
connectText | string | No | Text for the connect button | ”🔐 Login with Swarm ID” |
disconnectText | string | No | Text for the disconnect button | ”🔓 Disconnect from Swarm ID” |
loadingText | string | No | Text shown during loading | ”⏳ Loading…” |
backgroundColor | string | No | Background color for buttons | #dd7200 (connect), #666 (disconnect) |
color | string | No | Text color for buttons | white |
borderRadius | string | No | Border radius for buttons and iframe | 0 |
Notes:
- Button configuration is passed directly to the constructor, not via postMessage
- The
borderRadiusproperty affects both the buttons and the iframe container - Colors should be valid CSS color strings (e.g.,
'#FF0000','rgb(255, 0, 0)','red') - Text properties support plain text or emoji combinations
- The configuration applies to both authentication states (connect/disconnect)
Manual Authentication
In addition to the iframe-based authentication (via getAuthIframe()), you can manually trigger the authentication flow by calling connect(). This opens the same authentication URL in a new window:
// Open authentication manually (opens in new window)const url = client.connect("popup")
// Or open as full windowconst url = client.connect("window")When to use connect():
- When you want to trigger authentication from a custom UI element
- When you prefer the authentication to open in a new window instead of an iframe
- When you need the authentication URL for testing or debugging
Authentication Flow:
- User calls
client.connect()or clicks the iframe button - Authentication page opens with the app metadata
- User authenticates with their Swarm ID
- Authentication state is shared with the iframe proxy
onAuthChangecallback is invoked withtrue
checkAuthStatus()
Checks the current authentication status with the Swarm ID proxy.
Returns: Promise<AuthStatus> - The authentication status object
| Property | Type | Description |
|---|---|---|
authenticated | boolean | Whether the user is currently authenticated |
origin | string | undefined | The origin that authenticated (if authenticated) |
Throws:
Errorif the client is not initializedErrorif the request times out
Example:
const status = await client.checkAuthStatus()if (status.authenticated) { console.log('Authenticated from:', status.origin)}connect(popupMode?)
Opens Swarm ID authentication page in a new window.
This method creates the same authentication URL as used by the iframe proxy and opens it in a new browser window. The user can authenticate with their Swarm ID, and the resulting authentication will be available to the client when they return.
Parameters:
| Parameter | Type | Required | Description |
|---|---|---|---|
popupMode | "window" | "popup" | No | Whether to open as a popup window (“popup”) or full window (“window”, default) |
Returns: string - The URL that was opened (useful for testing or reference)
Throws:
Errorif the client is not initialized
Example:
const client = new SwarmIdClient({ ... })await client.initialize()
// Open authentication pageconst url = client.connect()console.log('Authentication opened at:', url)
// Open as popup windowclient.connect("popup")disconnect()
Disconnects the current session and clears authentication data.
After disconnection, the user will need to re-authenticate to perform uploads or access identity-related features. The onAuthChange callback will be invoked with false.
Returns: Promise<void> - Resolves when disconnection is complete
Throws:
Errorif the client is not initializedErrorif the disconnect operation failsErrorif the request times out
Example:
await client.disconnect()console.log('User logged out')getConnectionInfo()
Retrieves connection information including upload capability and identity details.
Use this method to check if the user can upload data and to get information about the currently connected identity.
Returns: Promise<ConnectionInfo> - The connection info object
| Property | Type | Description |
|---|---|---|
canUpload | boolean | Whether the user can upload data (has valid postage stamp) |
identity | object | undefined | The connected identity details (if authenticated) |
identity.id | string | Unique identifier for the identity |
identity.name | string | Display name of the identity |
identity.address | string | Ethereum address associated with the identity |
Throws:
Errorif the client is not initializedErrorif the request times out
Example:
const info = await client.getConnectionInfo()if (info.canUpload) { console.log('Ready to upload as:', info.identity?.name)} else { console.log('No postage stamp available')}Data Methods
uploadData(data, options?, onProgress?)
Uploads raw binary data to the Swarm network.
The data is uploaded using the authenticated user’s postage stamp. Progress can be tracked via the optional callback.
Parameters:
| Parameter | Type | Required | Description |
|---|---|---|---|
data | Uint8Array | Yes | The binary data to upload |
options | UploadOptions | No | Upload configuration |
options.pin | boolean | No | Whether to pin the data locally (defaults to false) |
options.encrypt | boolean | No | Whether to encrypt the data (defaults to false) |
options.tag | number | No | Tag ID for tracking upload progress |
options.deferred | boolean | No | Whether to use deferred upload (defaults to false) |
options.redundancyLevel | 0-4 | No | Redundancy level for data availability |
onProgress | (progress) => void | No | Callback for tracking upload progress |
Returns: Promise<UploadResult>
| Property | Type | Description |
|---|---|---|
reference | string | The Swarm reference (hash) of the uploaded data |
tagUid | number | undefined | The tag UID if a tag was created |
Throws:
Errorif the client is not initializedErrorif the user is not authenticated or cannot uploadErrorif the request times out
Example:
const data = new TextEncoder().encode('Hello, Swarm!')const result = await client.uploadData(data, { encrypt: true }, (progress) => { console.log(`Progress: ${progress.processed}/${progress.total}`)})console.log('Reference:', result.reference)downloadData(reference, options?)
Downloads raw binary data from the Swarm network.
Parameters:
| Parameter | Type | Required | Description |
|---|---|---|---|
reference | string | Yes | The Swarm reference (64 or 128 hex chars) |
options | DownloadOptions | No | Download configuration |
options.redundancyStrategy | 0-3 | No | Strategy for handling redundancy |
options.fallback | boolean | No | Whether to use fallback retrieval |
options.timeoutMs | number | No | Download timeout in milliseconds |
options.actPublisher | Uint8Array | string | No | ACT publisher for encrypted content |
options.actHistoryAddress | Uint8Array | string | No | ACT history address for encrypted content |
options.actTimestamp | number | string | No | ACT timestamp for encrypted content |
Returns: Promise<Uint8Array> - The downloaded data
Throws:
Errorif the client is not initializedErrorif the reference is not foundErrorif the request times out
Example:
const data = await client.downloadData('a1b2c3...') // 64 char hex referenceconst text = new TextDecoder().decode(data)console.log('Downloaded:', text)File Methods
uploadFile(file, name?, options?)
Uploads a file to the Swarm network.
Accepts either a File object (from file input) or raw Uint8Array data. When using a File object, the filename is automatically extracted unless explicitly overridden.
Parameters:
| Parameter | Type | Required | Description |
|---|---|---|---|
file | File | Uint8Array | Yes | The file to upload |
name | string | No | Filename (extracted from File object if not provided) |
options | UploadOptions | No | Upload configuration (see uploadData) |
Returns: Promise<UploadResult> - Contains reference and optional tagUid
Throws:
Errorif the client is not initializedErrorif the user is not authenticated or cannot uploadErrorif the request times out
Example:
// From file inputconst fileInput = document.querySelector('input[type="file"]')const file = fileInput.files[0]const result = await client.uploadFile(file)
// From Uint8Array with custom nameconst data = new Uint8Array([...])const result = await client.uploadFile(data, 'document.pdf')downloadFile(reference, path?, options?)
Downloads a file from the Swarm network.
Returns both the file data and its original filename (if available). For manifest references, an optional path can be specified to retrieve a specific file from the manifest.
Parameters:
| Parameter | Type | Required | Description |
|---|---|---|---|
reference | string | Yes | The Swarm reference of the file |
path | string | No | Path within a manifest to retrieve a specific file |
options | DownloadOptions | No | Download configuration (see downloadData) |
Returns: Promise<FileData>
| Property | Type | Description |
|---|---|---|
name | string | The filename |
data | Uint8Array | The file contents |
Throws:
Errorif the client is not initializedErrorif the reference is not foundErrorif the request times out
Example:
const file = await client.downloadFile('a1b2c3...')console.log('Filename:', file.name)
// Create download linkconst blob = new Blob([file.data])const url = URL.createObjectURL(blob)Chunk Methods
uploadChunk(data, options?)
Uploads a single chunk to the Swarm network.
Chunks are the fundamental unit of storage in Swarm (4KB each). This method is useful for low-level operations or when implementing custom chunking strategies.
Parameters:
| Parameter | Type | Required | Description |
|---|---|---|---|
data | Uint8Array | Yes | The chunk data (should be exactly 4KB for optimal storage) |
options | UploadOptions | No | Upload configuration (see uploadData) |
Returns: Promise<UploadResult> - Contains the reference of the uploaded chunk
Throws:
Errorif the client is not initializedErrorif the user is not authenticated or cannot uploadErrorif the request times out
Example:
const chunk = new Uint8Array(4096) // 4KB chunkchunk.fill(0x42) // Fill with dataconst result = await client.uploadChunk(chunk)console.log('Chunk reference:', result.reference)downloadChunk(reference, options?)
Downloads a single chunk from the Swarm network.
Retrieves a chunk by its reference hash. This method is useful for low-level operations or when implementing custom retrieval strategies.
Parameters:
| Parameter | Type | Required | Description |
|---|---|---|---|
reference | string | Yes | The Swarm reference of the chunk |
options | DownloadOptions | No | Download configuration (see downloadData) |
Returns: Promise<Uint8Array> - The chunk data
Throws:
Errorif the client is not initializedErrorif the reference is not foundErrorif the request times out
Example:
const chunk = await client.downloadChunk('a1b2c3...')console.log('Chunk size:', chunk.length)Types
import type { ClientOptions, AuthStatus, ConnectionInfo, UploadOptions, DownloadOptions, UploadResult, FileData, Reference, AppMetadata,} from '@swarm-id/lib'