Skip to content

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

Terminal window
pnpm add @swarm-id/lib

Quick 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 manually
const authUrl = client.connect()
console.log('Authentication opened at:', authUrl)
// Option 2: Check authentication status and upload if authenticated
const 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:

ParameterTypeRequiredDescription
options.iframeOriginstringYesThe origin URL where the Swarm ID proxy iframe is hosted
options.iframePathstringNoThe path to the proxy iframe (defaults to "/proxy")
options.timeoutnumberNoRequest timeout in milliseconds (defaults to 30000)
options.onAuthChange(authenticated: boolean) => voidNoCallback function invoked when authentication status changes
options.popupMode"popup" | "window"NoHow to display the authentication popup (defaults to "window")
options.metadataAppMetadataYesApplication metadata shown to users during authentication
options.metadata.namestringYesApplication name (1-100 characters)
options.metadata.descriptionstringNoApplication description (max 500 characters)
options.metadata.iconstringNoApplication icon as a data URL (SVG or PNG, max 4KB)
options.buttonConfigButtonConfigNoButton configuration for the authentication UI
options.containerIdstringNoID 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:

  • Error if the client is already initialized
  • Error if the iframe fails to load
  • Error if the proxy does not respond within the timeout period (10 seconds)
  • Error if 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 unmounts
useEffect(() => {
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:

  • Error if the client is not initialized
  • Error if the iframe is not available

Example:

const iframe = client.getAuthIframe()
// The iframe is already displayed; this returns a reference to it

Button 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:

PropertyTypeRequiredDescriptionDefault Value
connectTextstringNoText for the connect button”🔐 Login with Swarm ID”
disconnectTextstringNoText for the disconnect button”🔓 Disconnect from Swarm ID”
loadingTextstringNoText shown during loading”⏳ Loading…”
backgroundColorstringNoBackground color for buttons#dd7200 (connect), #666 (disconnect)
colorstringNoText color for buttonswhite
borderRadiusstringNoBorder radius for buttons and iframe0

Notes:

  • Button configuration is passed directly to the constructor, not via postMessage
  • The borderRadius property 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 window
const 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:

  1. User calls client.connect() or clicks the iframe button
  2. Authentication page opens with the app metadata
  3. User authenticates with their Swarm ID
  4. Authentication state is shared with the iframe proxy
  5. onAuthChange callback is invoked with true

checkAuthStatus()

Checks the current authentication status with the Swarm ID proxy.

Returns: Promise<AuthStatus> - The authentication status object

PropertyTypeDescription
authenticatedbooleanWhether the user is currently authenticated
originstring | undefinedThe origin that authenticated (if authenticated)

Throws:

  • Error if the client is not initialized
  • Error if 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:

ParameterTypeRequiredDescription
popupMode"window" | "popup"NoWhether 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:

  • Error if the client is not initialized

Example:

const client = new SwarmIdClient({ ... })
await client.initialize()
// Open authentication page
const url = client.connect()
console.log('Authentication opened at:', url)
// Open as popup window
client.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:

  • Error if the client is not initialized
  • Error if the disconnect operation fails
  • Error if 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

PropertyTypeDescription
canUploadbooleanWhether the user can upload data (has valid postage stamp)
identityobject | undefinedThe connected identity details (if authenticated)
identity.idstringUnique identifier for the identity
identity.namestringDisplay name of the identity
identity.addressstringEthereum address associated with the identity

Throws:

  • Error if the client is not initialized
  • Error if 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:

ParameterTypeRequiredDescription
dataUint8ArrayYesThe binary data to upload
optionsUploadOptionsNoUpload configuration
options.pinbooleanNoWhether to pin the data locally (defaults to false)
options.encryptbooleanNoWhether to encrypt the data (defaults to false)
options.tagnumberNoTag ID for tracking upload progress
options.deferredbooleanNoWhether to use deferred upload (defaults to false)
options.redundancyLevel0-4NoRedundancy level for data availability
onProgress(progress) => voidNoCallback for tracking upload progress

Returns: Promise<UploadResult>

PropertyTypeDescription
referencestringThe Swarm reference (hash) of the uploaded data
tagUidnumber | undefinedThe tag UID if a tag was created

Throws:

  • Error if the client is not initialized
  • Error if the user is not authenticated or cannot upload
  • Error if 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:

ParameterTypeRequiredDescription
referencestringYesThe Swarm reference (64 or 128 hex chars)
optionsDownloadOptionsNoDownload configuration
options.redundancyStrategy0-3NoStrategy for handling redundancy
options.fallbackbooleanNoWhether to use fallback retrieval
options.timeoutMsnumberNoDownload timeout in milliseconds
options.actPublisherUint8Array | stringNoACT publisher for encrypted content
options.actHistoryAddressUint8Array | stringNoACT history address for encrypted content
options.actTimestampnumber | stringNoACT timestamp for encrypted content

Returns: Promise<Uint8Array> - The downloaded data

Throws:

  • Error if the client is not initialized
  • Error if the reference is not found
  • Error if the request times out

Example:

const data = await client.downloadData('a1b2c3...') // 64 char hex reference
const 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:

ParameterTypeRequiredDescription
fileFile | Uint8ArrayYesThe file to upload
namestringNoFilename (extracted from File object if not provided)
optionsUploadOptionsNoUpload configuration (see uploadData)

Returns: Promise<UploadResult> - Contains reference and optional tagUid

Throws:

  • Error if the client is not initialized
  • Error if the user is not authenticated or cannot upload
  • Error if the request times out

Example:

// From file input
const fileInput = document.querySelector('input[type="file"]')
const file = fileInput.files[0]
const result = await client.uploadFile(file)
// From Uint8Array with custom name
const 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:

ParameterTypeRequiredDescription
referencestringYesThe Swarm reference of the file
pathstringNoPath within a manifest to retrieve a specific file
optionsDownloadOptionsNoDownload configuration (see downloadData)

Returns: Promise<FileData>

PropertyTypeDescription
namestringThe filename
dataUint8ArrayThe file contents

Throws:

  • Error if the client is not initialized
  • Error if the reference is not found
  • Error if the request times out

Example:

const file = await client.downloadFile('a1b2c3...')
console.log('Filename:', file.name)
// Create download link
const 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:

ParameterTypeRequiredDescription
dataUint8ArrayYesThe chunk data (should be exactly 4KB for optimal storage)
optionsUploadOptionsNoUpload configuration (see uploadData)

Returns: Promise<UploadResult> - Contains the reference of the uploaded chunk

Throws:

  • Error if the client is not initialized
  • Error if the user is not authenticated or cannot upload
  • Error if the request times out

Example:

const chunk = new Uint8Array(4096) // 4KB chunk
chunk.fill(0x42) // Fill with data
const 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:

ParameterTypeRequiredDescription
referencestringYesThe Swarm reference of the chunk
optionsDownloadOptionsNoDownload configuration (see downloadData)

Returns: Promise<Uint8Array> - The chunk data

Throws:

  • Error if the client is not initialized
  • Error if the reference is not found
  • Error if 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'