Skip to main content

BackendWebSocketService Actions

13 actions registered.

NameDeprecated
addChannelCallback
channelHasSubscription
connect
disconnect
findSubscriptionsByChannelPrefix
forceReconnection
getChannelCallbacks
getConnectionInfo
removeChannelCallback
sendMessage
sendRequest
subscribe
unsubscribeChannels

BackendWebSocketService:addChannelCallback​

Package: @metamask/core-backend

Register a callback for specific channels (local callback only, no server subscription)

Key Difference from subscribe():

  • addChannelCallback(): Registers a local callback without creating a server-side subscription. The callback triggers on ANY message matching the channel name, regardless of subscriptionId. Useful for system-wide notifications or when you don't control the subscription lifecycle.

  • subscribe(): Creates a proper server-side subscription with a subscriptionId. The callback only triggers for messages with the matching subscriptionId. Includes proper lifecycle management (unsubscribe, automatic cleanup on disconnect).

When to use addChannelCallback():

  • Listening to system-wide notifications (e.g., 'system-notifications.v1')
  • Monitoring channels where subscriptions are managed elsewhere
  • Debug/logging scenarios where you want to observe all channel messages

When to use subscribe() instead:

  • Creating new subscriptions that need server-side registration
  • When you need proper cleanup via unsubscribe
  • Most application use cases (recommended approach)

Parameters:

NameDescription
optionsChannel callback configuration
options.channelNameChannel name to match exactly
options.callbackFunction to call when channel matches

Handler signature:

(options: {
channelName: string;
callback: (notification: ServerNotificationMessage) => void;
}) => void

BackendWebSocketService:channelHasSubscription​

Package: @metamask/core-backend

Checks if a channel has a subscription

Parameters:

NameDescription
channelThe channel name to check

Returns: True if the channel has a subscription, false otherwise

Handler signature:

(channel: string) => boolean

BackendWebSocketService:connect​

Package: @metamask/core-backend

Establishes WebSocket connection with smart reconnection behavior

Connection Requirements (all must be true):

  1. Feature enabled (isEnabled() = true)
  2. Basic functionality enabled (isBasicFunctionality() = true)
  3. Wallet unlocked (checked by getBearerToken)
  4. User signed in (checked by getBearerToken)

Platform code should call this when app opens/foregrounds. Automatically called on KeyringController:unlock event.

Returns: Promise that resolves when connection is established

Handler signature:

() => Promise<void>

BackendWebSocketService:disconnect​

Package: @metamask/core-backend

Closes the WebSocket and cancels a queued reconnect.

The timer is cleared before the early return. Lock, sign-out, and Basic Functionality off all call this, including when the socket is already gone and onclose will not run. clearTimeout has to run first: assigning #reconnectTimer to null leaves the callback scheduled.

Handler signature:

() => void

BackendWebSocketService:findSubscriptionsByChannelPrefix​

Package: @metamask/core-backend

Finds all subscriptions that have channels starting with the specified prefix

Parameters:

NameDescription
channelPrefixThe channel prefix to search for (e.g., "account-activity.v1")

Returns: Array of subscription info for matching subscriptions

Handler signature:

(channelPrefix: string) => WebSocketSubscription[]

BackendWebSocketService:forceReconnection​

Package: @metamask/core-backend

Forces a WebSocket reconnection to clean up subscription state

This method is useful when subscription state may be out of sync and needs to be reset. It performs a controlled disconnect-then-reconnect sequence:

  • Disconnects cleanly to trigger subscription cleanup
  • Schedules reconnection with exponential backoff to prevent rapid loops
  • All subscriptions will be cleaned up automatically on disconnect

Use cases:

  • Recovering from subscription/unsubscription issues
  • Cleaning up orphaned subscriptions
  • Forcing a fresh subscription state

Returns: Promise that resolves when disconnection is complete (reconnection is scheduled)

Handler signature:

() => Promise<void>

BackendWebSocketService:getChannelCallbacks​

Package: @metamask/core-backend

Get all registered channel callbacks (for debugging)

Returns: Array of all registered channel callbacks

Handler signature:

() => ChannelCallback[]

BackendWebSocketService:getConnectionInfo​

Package: @metamask/core-backend

Gets current connection information

Returns: Current connection status and details

Handler signature:

() => WebSocketConnectionInfo

BackendWebSocketService:removeChannelCallback​

Package: @metamask/core-backend

Remove a channel callback

Parameters:

NameDescription
channelNameThe channel name returned from addChannelCallback

Returns: True if callback was found and removed, false otherwise

Handler signature:

(channelName: string) => boolean

BackendWebSocketService:sendMessage​

Package: @metamask/core-backend

Sends a message through the WebSocket (fire-and-forget, no response expected)

This is a low-level method for sending messages without waiting for a response. Most consumers should use sendRequest() instead, which handles request-response correlation and provides proper error handling with timeouts.

Use this method only when:

  • You don't need a response from the server
  • You're implementing custom message protocols
  • You need fine-grained control over message timing

Parameters:

NameDescription
messageThe message to send

Handler signature:

(message: ClientRequestMessage) => void

BackendWebSocketService:sendRequest​

Package: @metamask/core-backend

Sends a request and waits for a correlated response (recommended for most use cases)

This is the recommended high-level method for request-response communication. It automatically handles:

  • Request ID generation and correlation
  • Response matching with timeout protection
  • Automatic reconnection on timeout
  • Proper cleanup of pending requests

Parameters:

NameDescription
messageThe request message (can include optional requestId for testing)

Returns: Promise that resolves with the response data

Handler signature:

(message: Omit<ClientRequestMessage, 'data'> & {
data?: Omit<ClientRequestMessage['data'], 'requestId'> & {
requestId?: string;
};
}) => Promise<Type>

BackendWebSocketService:subscribe​

Package: @metamask/core-backend

Create and manage a subscription with server-side registration (recommended for most use cases)

This is the recommended subscription API for high-level services. It creates a proper server-side subscription and routes notifications based on subscriptionId.

Key Features:

  • Creates server-side subscription with unique subscriptionId
  • Callback triggered only for messages with matching subscriptionId
  • Automatic lifecycle management (cleanup on disconnect)
  • Includes unsubscribe method for proper cleanup
  • Request-response pattern with error handling

When to use subscribe():

  • Creating new subscriptions (account activity, price updates, etc.)
  • When you need proper cleanup/unsubscribe functionality
  • Most application use cases

When to use addChannelCallback() instead:

  • System-wide notifications without server-side subscription
  • Observing channels managed elsewhere
  • Debug/logging scenarios

Parameters:

NameDescription
optionsSubscription configuration
options.channelsArray of channel names to subscribe to
options.callbackCallback function for handling notifications
options.requestIdOptional request ID for testing (will generate UUID if not provided)
options.channelTypeChannel type identifier

Returns: Subscription for the channels the gateway accepted. failed lists the channels it refused. A response that accepts nothing rejects.

Handler signature:

(options: {
/** Channel names to subscribe to */
channels: string[];
/** Channel type with version (e.g., 'account-activity.v1') for tracing and monitoring */
channelType: string;
/** Handler for incoming notifications */
callback: (notification: ServerNotificationMessage) => void;
/** Optional request ID for testing (will generate UUID if not provided) */
requestId?: string;
}) => Promise<WebSocketSubscription>

BackendWebSocketService:unsubscribeChannels​

Package: @metamask/core-backend

Remove these channels from the server.

Channels stored on the same subscription go out in one unsubscribe frame. A channel the server does not have is skipped. A refusal on one subscription does not skip the others.

Channels the gateway refuses are returned in failed and stay stored. The caller decides whether to retry or give up. A request that fails outright, or a reply that does not acknowledge the removal, rejects instead.

Parameters:

NameDescription
channelsFully-qualified channel names to close.

Returns: The channels the gateway refused to close.

Handler signature:

(channels: readonly string[]) => Promise<UnsubscribeResult>