Skip to contentSkip to navigationSkip to topbar
Page tools
Useful for sharing or LLM
Accelerate development with AI

On this page
Looking for more inspiration?Visit the

Voice JavaScript SDK: Changelog


(warning)

Warning

If you are upgrading to version 2.3.0 or later and have firewall rules or network configuration that blocks any unknown traffic by default, you need to update your configuration to allow connections to the new DNS names and IP addresses. Please refer to this changelog for more details.


2.19.0 (November 12, 2026)

2190-november-12-2026 page anchor

Improvements

improvements page anchor
  • Insights events published by the SDK now include signaling_connection_id when provided by the signaling server in its connected message, improving telemetry and event correlation.
  • Insights events are now buffered in memory when the gateway is unknown or temporarily unreachable, and retried once connectivity is restored. The buffer holds up to 200 events, dropping the oldest events when full, and an event is not sent if it is older than 5 minutes when it would be sent. Events are delivered oldest first. Network errors, HTTP 5xx, and HTTP 429 responses are retried with exponential backoff and full jitter, with the maximum delay between attempts growing from 1 to 30 seconds, and the Retry-After header of an HTTP 429 or 503 response is honored when the gateway exposes it. After the gateway recovers, buffered events are sent at most one every 200 ms. Buffered events are preserved across device.updateOptions() calls but are lost when the page closes. When device.destroy() is called, each buffered event is sent one final time, without retries, and dropped if that send fails or the gateway is still unknown. Delivery is at least once, so duplicate events are possible. Buffered events are sent with the access token current at send time; when device.updateToken() is called with a token for a different account or identity, or with a token that cannot be decoded, buffered events are dropped, while a token refresh for the same identity keeps them. Additionally, Insights gateway HTTP errors are now properly reported, allowing PreflightTest to emit the insights-connection-error warning.
  • Errors that happen outside a call are now sent to Insights. Error-level Insights events were previously dropped when they had no call, so errors raised while no call was active never reached Insights. This covers the errors the Device emits from the signaling connection, such as token errors, connection errors and error messages from the signaling server, and the 31400 error for a malformed incoming call invite. Signaling errors that carry the CallSid of a pending incoming call are sent with that call. Events below error level still require a call. Nothing is sent when publishEvents is false. Transport errors (31000, 31005 and 31009) repeat on every reconnect attempt while the signaling connection is down, so only the first one is sent each time the connection is lost. That event carries the signaling_connection_id of the connection that was lost, including when the error comes from a reconnect attempt after the connection closed. The Device still emits error for every one.

Note: Errors raised before the first signaling connected message are sent only if the Insights gateway host is known. Without the eventgw option, they are buffered and sent only if the Device connects within 5 minutes; otherwise they are dropped. An error caused by an invalid token is sent with that token, so the gateway can reject it.

  • Fixed an issue where an exception thrown by an application's PreflightTest warning listener while handling the insights-connection-error warning caused the warning to be emitted again, twice for one failed Insights request. The warning is now emitted at most once per test. The exception is still raised as an unhandled promise rejection, as before, and is now also written to the SDK log at error level.
  • Fixed an issue where losing the signaling transport before a call received a signaling-reconnect token left its media open and the Device busy with a closed call. The SDK now closes the media and emits disconnect, releasing the active-call slot so a later device.connect() is not rejected with InvalidStateError. Calls with a reconnect token retain their existing recovery behavior. Thanks @ip4422 for your contribution(link takes you to an external page).
  • Fixed an issue where a Device could end up with two open calls. An incoming call only counted as the Device's active call once its media was connected, which can take several seconds while waiting on getUserMedia. Accepting a second incoming call in that window did not disconnect the first, and with allowIncomingWhileBusy: false a new incoming call was still surfaced. An accepted incoming call now becomes the active call as soon as accept() is called, as outgoing calls already did. While it connects, the Device now treats it as active: device.isBusy is true, device.connect() rejects with InvalidStateError, device.audio.unsetInputDevice() rejects with InvalidStateError when an input device is set, an edge-changing device.updateOptions() throws InvalidStateError, device.audio.setInputDevice() switches the connecting call's microphone, another incoming call is surfaced without a ringtone (or ignored when allowIncomingWhileBusy is false), and closeProtection prompts before the page unloads. Accepting an incoming call while device.connect() is still creating its call also no longer leaves both calls open, for example when device.connect() is called from the disconnect handler of the call being replaced; the outgoing call replaces the accepted one. While accept() replaces a call, that call's disconnect handlers still see the Device idle: a call they accept or connect replaces the accepting one, and device.disconnectAll() there ends it.
  • Fixed an issue where a Call emitted disconnect twice when it was disconnected while its microphone was still being acquired, for example by calling call.disconnect() right after call.accept() or device.connect(). The second event fired once getUserMedia resolved. disconnect is now emitted once, and the Call no longer emits an error if getUserMedia then fails.
  • Fixed an issue where an incoming call whose offer the browser rejected never emitted an error and stayed connecting after accept(). It now disconnects and emits error 53402 (ClientRemoteDescFailed). An incoming call also now disconnects when creating its answer fails, where it previously emitted the same error but stayed connecting. An incoming call that is disconnected while its answer is being created no longer emits this error afterwards.
  • Fixed an issue where a Call whose RTCPeerConnection could not be created or set up, for example because rtcConfiguration lists a TURN server without credentials, stayed connecting without emitting anything. It now disconnects and emits error 31000.
  • Fixed issues where the SDK left a microphone track running or stopped the wrong one. A call that ended while its microphone was still being acquired could leave that microphone on, and with a local AudioProcessor a call could leave its raw microphone track running. When the default microphone was lost during a call, the SDK reacquired it and then stopped the new track, leaving the call silent. A call that ended while its microphone was being acquired also no longer destroys the next call's remote processed stream once getUserMedia resolves, and a local AudioProcessor removed while it was creating a call's processed stream no longer keeps processing that call's audio.
  • Fixed an issue where error 31402 (AcquisitionFailedError) did not include the underlying error. It is now set as originalError, for example the error from a local AudioProcessor that failed to create its processed stream.
  • Fixed an issue where device.updateOptions() threw Cannot change Edge while on an active Call but still stored the new options. Retrying the same edge after the call ended found no change and kept the signaling stream on the previous edge, and a signaling connection opened later, for example after the previous one closed, could use the rejected edge. A rejected updateOptions() call now leaves the Device options unchanged. This also applies when updateOptions() throws for an invalid edge, which previously made later updateOptions() calls throw until a valid edge was passed. Thanks @RaphaelFakhri for your contribution(link takes you to an external page).
  • Fixed an issue(link takes you to an external page) where a call that ended while its microphone was being switched, by device.audio.setInputDevice() or by the SDK's own recovery after the active microphone was lost, produced InvalidStateError: Failed to execute 'replaceTrack' on 'RTCRtpSender': The peer connection is closed. The SDK's recovery surfaced it as an unhandled promise rejection. setInputDevice() rejected with it and left the new microphone open without selecting it. On Firefox, setInputDevice() could instead never settle, and every later device.connect() waited on it indefinitely. The switch now completes for future calls instead.
  • Fixed an issue where Voice Insights did not receive the dtls-transport-state closed event when a call ended on Chrome 154 and later or on Firefox. These browsers do not fire the DTLS transport's statechange event when the SDK closes the RTCPeerConnection, so the SDK now reports the closed state itself.

2.18.5 (September 10, 2026)

2185-september-10-2026 page anchor
  • Fixed an issue(link takes you to an external page) where losing an audio output device during a call caused an unhandled promise rejection. On browsers without audio output selection, such as Chrome on Android, OutputDeviceCollection.delete() attempted a sink change that can never apply there, raising NotSupportedError without affecting call audio; it no longer attempts one. On browsers that do support selection, a failed switch to the fallback device is now logged as a warning. Thanks @ifabijanovic for reporting this.
  • Fixed an issue where the SDK emitted a false AccessTokenInvalid (20101) error on a still valid access token after the signaling WebSocket dropped. Registration messages that failed to send while the connection was down were queued and replayed immediately after reconnecting, before the server had validated the token, and the server rejected them with error 31204. Registration messages are no longer queued, and a re-registration that fails because the connection dropped again is now logged as a warning instead of surfacing as an unhandled promise rejection. The Device already re-registers once the signaling connection is re-established, so registration recovery is unchanged.
  • Fixed an issue where the periodic registration timer kept running while the signaling connection was down. A registration that fired after the WebSocket reopened but before the server validated the access token was rejected with error 31204 and surfaced as a false AccessTokenInvalid (20101), the same symptom as the issue above. The timer now stops when the signaling stream goes offline, and re-registering on reconnect restarts it, so the registration cadence is unchanged.

Note: On browsers without audio output selection, device.audio.speakerDevices.get() and ringtoneDevices.get() now stay empty after a device is lost instead of reporting default.


2.18.4 (August 31, 2026)

2184-august-31-2026 page anchor
  • Fixed an issue(link takes you to an external page) where a pause character (w) in call.sendDigits() paused the DTMF tones played back to the caller for a different length of time than the tones sent to the recipient, so the two drifted apart, and the gap grew with each w. This is common in PIN and IVR entry such as sendDigits('1w1234'). Local playback now stays in step with the recipient for up to two digits before a w. Longer runs still lag, because those tones take longer to play locally than the 500 ms pause allows. Thanks @a-lindsay for reporting this.
  • Fixed an issue(link takes you to an external page) where the Device was permanently destroyed when Chrome restored a page from the back/forward cache (BFCache) in Chrome 149+. When a page is cached (and no calls are active), the Device now closes its signaling connection instead of destroying itself, and reconnects and re-registers when the page is restored. Normal page unloads still destroy the Device, and a Device you destroy yourself is never revived. Thanks @anene for reporting this.

Note: During a BFCache round-trip, the Device emits unregistered when the page is cached and registered again when it is restored. If your app shows registration status in the UI, expect it to briefly flip to unregistered and back.


2.18.3 (May 11, 2026)

2183-may-11-2026 page anchor
  • Fixed an issue where preflight report samples contained NaN or undefined values for bytesSent, packetsSent, bytesReceived, packetsReceived, packetsLost, and jitter when running on Chrome 141+. Starting in Chrome 141, the outbound-rtp stats entry is omitted from RTCPeerConnection.getStats() while ICE has not yet connected; counter fields are now initialized to 0 so the sample shape matches pre-141 behavior.

2.18.2 (April 21, 2026)

2182-april-21-2026 page anchor
  • Fixed an issue where multiple PeerConnections are created when device.connect() is called multiple times.
  • Fixed an issue where the docs:ts build fails when the repository is inside a monorepo or workspace due to TypeDoc picking up conflicting @types from parent node_modules. Thanks @taf2 for your contribution(link takes you to an external page).

2.18.1 (March 17, 2026)

2181-march-17-2026 page anchor

2.18.0 (January 5, 2026)

2180-january-5-2026 page anchor

Previously, the SDK relied solely on a backoff mechanism when reconnecting the signaling connection. With this update, the SDK will use a server-provided Retry-After value, if available, when a connection attempt is rejected.


2.17.0 (December 1, 2025)

2170-december-1-2025 page anchor

Remote audio processor APIs

remote-audio-processor-apis page anchor

In version 2.9.0, the SDK introduced the Audio Processor API, which allows you to access the raw audio input and modify audio data before the SDK sends it to Twilio. This release also extends these capabilities to remote audio streams, enabling developers the ability to modify audio before it is played through the speaker.

With these enhancements, you can implement the following client-side audio use cases:

  • Background noise removal using any noise cancellation library of your choice
  • Custom audio filters
  • AI-powered audio classification
  • Additional audio processing capabilities

For more information, see Twilio Audio Processor.

Example

1
import { AudioProcessor, Device } from '@twilio/voice-sdk';
2
3
class OutputAudioProcessor implements AudioProcessor {
4
async createProcessedStream(stream: MediaStream): Promise<MediaStream> {
5
// Implementation
6
}
7
8
async destroyProcessedStream(stream: MediaStream): Promise<void> {
9
// Cleanup
10
}
11
}
12
13
const processor = new OutputAudioProcessor();
14
const device = new Device(token, options);
15
16
// Pass “true” as second argument to apply processor to remote output audio stream
17
await device.audio.addProcessor(processor, true);
18
// To remove it later:
19
// device.audio.removeProcessor(processor, true);

2.16.0 (September 25, 2025)

2160-september-25-2025 page anchor

ECMAScript Module Support GA

ecmascript-module-support-ga page anchor

The SDK includes ESM support by default and considered Generally Available (GA). It should work with the standard import:

import { Device } from '@twilio/voice-sdk';
  • Removed support for the deprecated Plan-B SDP semantics.
  • Removed outdated tests.

2.15.0 (July 14, 2025)

2150-july-14-2025 page anchor

2.14.0 (June 25, 2025)

2140-june-25-2025 page anchor
  • Upgraded Typescript dependency to 5.x.
  • Replaced Karma test runner with Cypress.
  • Added @types/events as a dependency. This resolves issues regarding missing Intellisense hinting for SDK objects that extend EventEmitters.

2.13.0 (May 6, 2025)

2130-may-6-2025 page anchor

In version 2.5.0, the SDK introduced a mechanism to override WebRTC APIs, enabling support for redirection technologies like Citrix HDX(link takes you to an external page). In this release, the SDK extends this capability by allowing the override of the native MediaStream(link takes you to an external page) API, making it possible to create custom media streams tailored for such environments. See WebRTC API Overrides for an example.


2.12.4 (March 12, 2025)

2124-march-12-2025 page anchor
  • Fixed an issue(link takes you to an external page) where device.destroy() did not work for Chrome Extension Manifest V3.
  • Addressed an issue where the publisher was null upon destruction of an AudioProcessorObserver.
  • Added an API for testing PreflightTest in realms other than production. You can now pass chunderw and eventgw values within the options object when constructing a PreflightTest. Note: These new options are intended for internal testing by Twilio employees only, and should not be used otherwise.

2.12.3 (December 3, 2024)

2123-december-3-2024 page anchor
  • Fixed an issue where the originalError property is not populated when a general ConnectionError (31005) happens.

2.12.2 (November 12, 2024)

2122-november-12-2024 page anchor
  • Fixed an issue where the chunderw parameter is not being used during signaling reconnection. Note that this parameter is intended solely for testing purposes.

2.12.1 (August 30, 2024)

2121-august-30-2024 page anchor
  • Fixed an issue where calling device.connect() without waiting for the promise to get resolved, then calling device.audio.setInputDevice() right away results in an AcquisitionFailedError.

2.12.0 (August 26, 2024)

2120-august-26-2024 page anchor

The Call Message Events, originally released in 2.2.0, has been promoted to GA. This release includes the following breaking changes.


2.11.3 (August 21, 2024)

2113-august-21-2024 page anchor
  • The SDK now updates its internal device list when microphone permissions change.

2.11.2 (June 26, 2024)

2112-june-26-2024 page anchor
  • Fixed an issue where an AcquisitionFailedError is raised when making a call while a setInputDevice invocation is still in progress. The following snippet will reproduce the issue in versions <2.11.2:
1
// Call setInputDevice without waiting for it to resolve e.g. using 'await'
2
device.audio.setInputDevice(id);
3
4
// Calling device.connect immediately raises an AcquisitionFailedError error
5
device.connect(...);

2.11.1 (May 30, 2024)

2111-may-30-2024 page anchor

2.11.0 (May 2, 2024)

2110-may-2-2024 page anchor

Chrome Extensions Manifest V3 Support

chrome-extensions-manifest-v3-support page anchor

In Manifest V2, Chrome Extensions(link takes you to an external page) had the capability to run the Voice JS SDK in the background for making calls. However, with the introduction of Manifest V3(link takes you to an external page), running the Voice JS SDK in the background is now possible only through service workers. Service workers lack access to certain features, such as DOM, getUserMedia, and audio playback, making it impossible to make calls with previous versions of the SDK.

This new release enables the SDK to run in a service worker context, allowing it to listen for incoming calls or initiate outgoing calls. Once a call object is created, it can be forwarded to an offscreen document(link takes you to an external page), where the SDK gains access to all necessary APIs to fully establish and interact with the call. For implementation details, refer to our example(link takes you to an external page).

Client side incoming call forwarding and better support for simultaneous calls

client-side-incoming-call-forwarding-and-better-support-for-simultaneous-calls page anchor

Previous versions of the SDK supported simultaneous outgoing and incoming calls using different identities. If an incoming call was received while the Device with the same identity was busy, the active call had to be disconnected before accepting the incoming call. With this SDK release, multiple incoming calls for the same identity can be accepted, muted, or put on hold, without disconnecting any existing active calls. This is achieved by forwarding the incoming call to a different Device instance. Below are the new APIs and an example for more details.

1
// Create a Device instance that handles receiving all incoming calls for the same identity.
2
const receiverDevice = new Device(token, options);
3
await receiverDevice.register();
4
5
receiverDevice.on('incoming', (call) => {
6
// Forward this call to a new Device instance using the call.connectToken string.
7
forwardCall(call.connectToken);
8
});
9
10
// The forwardCall function may look something like the following.
11
async function forwardCall(connectToken) {
12
// For each incoming call, create a new Device instance for interaction
13
// without affecting other calls.
14
// IMPORTANT: The token for this new Device needs to have the same identity
15
// as the token used in the receiverDevice.
16
const device = new Device(token, options);
17
const call = await device.connect({ connectToken });
18
19
// Destroy the Device after the call is completed
20
call.on('disconnect', () => device.destroy());
21
}

2.10.2 (February 14, 2024)

2102-february-14-2024 page anchor

2.10.1 (January 12, 2024)

2101-january-12-2024 page anchor

2.10.0 (January 5, 2024)

2100-january-5-2024 page anchor
  • Added tags to client logs for easier filtering
  • Added log statements to API calls and events for debugging purposes

2.9.0 (November 28, 2023)

290-november-28-2023 page anchor

The SDK now includes Audio Processor APIs, enabling access to raw audio input and the ability to modify audio data before sending it to Twilio. With this new feature, the following use cases can now be achieved on the client side:

  • Background noise removal using a noise cancellation library of your choice
  • Music playback when putting the call on hold
  • Audio filters
  • AI audio classification
  • ... and more!

Please visit this page for more details about the Audio Processor APIs.


2.8.0 (October 16, 2023)

280-october-16-2023 page anchor

Added a new feature flag enableImprovedSignalingErrorPrecision to enhance the precision of errors emitted by Device and Call objects.

1
const token = ...;
2
const device = new Device(token, {
3
enableImprovedSignalingErrorPrecision: true,
4
});

The default value of this option is false.

When this flag is enabled, some errors that would have been described with a generic error code are now described with a more precise error code. With this feature, the following errors now have their own error codes. Please see this page for more details about each error.

Device Error Changes

1
const device = new Device(token, {
2
enableImprovedSignalingErrorPrecision: true,
3
});
4
device.on('error', (deviceError) => {
5
// the following table describes how deviceError will change with this feature flag
6
});
Device Error NameDevice Error Code with Feature Flag EnabledDevice Error Code with Feature Flag Disabled
GeneralErrors.ApplicationNotFoundError3100153000
GeneralErrors.ConnectionDeclinedError3100253000
GeneralErrors.ConnectionTimeoutError3100353000
MalformedRequestErrors.MissingParameterArrayError3110153000
MalformedRequestErrors.AuthorizationTokenMissingError3110253000
MalformedRequestErrors.MaxParameterLengthExceededError3110353000
MalformedRequestErrors.InvalidBridgeTokenError3110453000
MalformedRequestErrors.InvalidClientNameError3110553000
MalformedRequestErrors.ReconnectParameterInvalidError3110753000
SignatureValidationErrors.AccessTokenSignatureValidationFailed3120253000
AuthorizationErrors.NoValidAccountError3120353000
AuthorizationErrors.JWTTokenExpirationTooLongError3120753000
ClientErrors.NotFound3140453000
ClientErrors.TemporarilyUnavilable3148053000
ClientErrors.BusyHere3148653000
SIPServerErrors.Decline3160353000

Call Error Changes

1
const device = new Device(token, {
2
enableImprovedSignalingErrorPrecision: true,
3
});
4
const call = device.connect(...);
5
call.on('error', (callError) => {
6
// the following table describes how callError will change with this feature flag
7
});
Call Error NameCall Error Code with Feature Flag EnabledCall Error Code with Feature Flag Disabled
GeneralErrors.ConnectionDeclinedError3100231005
AuthorizationErrors.InvalidJWTTokenError3120431005
AuthorizationErrors.JWTTokenExpiredError3120531005

IMPORTANT: If your application logic currently relies on listening to the generic error code 53000 or 31005, and you opt into enabling the feature flag, then your application logic needs to be updated to anticipate the new error code when any of the above errors happen.


2.7.3 (October 6, 2023)

273-october-6-2023 page anchor
  • Fixed an issue(link takes you to an external page) where, sometimes a TypeError is raised while handling an incoming call under the following circumstances:
    • Network interruptions
    • updating the token before accepting the call

2.7.2 (September 21, 2023)

272-september-21-2023 page anchor

Updated November 1, 2023

We have identified an issue on Chromium-based browsers running on MacOS 14 (Sonoma) where the audio deteriorates during a call. This issue happens due to the excessive calls to MediaDevices: enumerateDevices() API. With this release, the SDK calls this API only when necessary to avoid audio deterioration.

  • Fixed an issue(link takes you to an external page) where audio in the Chrome browser is choppy when another application is also using the audio devices.
  • Added missing documentation for the following events:
    • call.on('ringing', handler)
    • call.on('warning', handler)
    • call.on('warning-cleared', handler)
    • device.on('destroyed', handler)

2.7.1 (August 3, 2023)

271-august-3-2023 page anchor

2.7.0 (August 1, 2023)

270-august-1-2023 page anchor

ECMAScript Module Support

ecmascript-module-support page anchor

Currently, the SDK is imported as a CommonJS Module (CJS)(link takes you to an external page) using the root path @twilio/voice-sdk. With this release, the SDK contains an experimental feature that allows it to be imported as an ECMAScript Module (ESM)(link takes you to an external page) using the @twilio/voice-sdk/esm path. As this is an experimental feature, some frameworks using bundlers like Vite and Rollup may not work. Full support for ESM will be available in a future release and will become the default import behavior of the SDK.

Example:

import { Device } from '@twilio/voice-sdk/esm';

2.6.1 (July 7, 2023)

261-july-7-2023 page anchor
  • Fixed some security vulnerabilities shown by npm audit.
  • Removed unused dependencies.
  • Replaced deprecated dependencies.
  • Fixed an issue(link takes you to an external page) where calling device.updateOptions would reset the device.audio._enabledSounds state.
  • Fixed an issue where custom DTMF sounds would not play. With this release, custom DTMF sounds should now play when configured during device initialization.
1
const device = new Device(token, {
2
sounds: {
3
dtmf8: 'http://example.com/8_button.mp3',
4
// Other custom sounds
5
},
6
// Other options
7
});

2.6.0 (June 20, 2023)

260-june-20-2023 page anchor
  • The SDK now builds on NodeJS versions 16 and above without the --legacy-peer-deps flag.
  • Removed usage of NodeJS modules from the SDK and some dependencies. With this change, the SDK should now work with some of the latest frameworks that use the latest versions of bundlers such as Vite and Webpack.
  • The AudioPlayer dependency has been incorporated into the SDK as part of a migration. This change fixes an issue where source maps are not properly loaded.
  • Removed unnecessary files from the generated npm package.
  • Links to source maps are now included in the generated npm package.
  • The ws package has been moved to devDependencies.
  • The SDK no longer depends on the xmlhttprequest npm package.

2.5.0 (May 9, 2023)

250-may-9-2023 page anchor

WebRTC API Overrides (Beta)

webrtc-api-overrides-beta page anchor

Updated: This is now GA as of December 14, 2023

The SDK now allows you to override WebRTC APIs using the following options and events. If your environment supports WebRTC redirection, such as Citrix HDX(link takes you to an external page)'s WebRTC redirection technologies(link takes you to an external page), your application can use this new beta feature for improved audio quality in those environments.


2.4.0 (April 6, 2023)

240-april-6-2023 page anchor
  • Updated the description of Device.updateToken API. It is recommended to call this API after Device.tokenWillExpireEvent is emitted, and before or after a call to prevent a potential ~1s audio loss during the update process.
  • Updated stats reporting to stop using deprecated RTCIceCandidateStats - ip and deleted.

2.3.2 (February 27, 2023)

232-february-27-2023 page anchor

2.3.1 (February 3, 2023)

231-february-3-2023 page anchor

2.3.0 (January 23, 2023)

230-january-23-2023 page anchor

This release includes updated DNS names for Twilio Edge Locations. The Voice JS SDK uses these Edge Locations to connect to Twilio's infrastructure via the parameter Device.Options.edge. The current usage of this parameter does not change as the SDK automatically maps the edge value to the new DNS names.

Additionally, you need to update your Content Security Policies (CSP)(link takes you to an external page) if you have it enabled for your application. You also need to update your network configuration such as firewalls, if necessary, to allow connections to the new DNS names and IP addresses.


2.2.0 (December 5, 2022)

220-december-5-2022 page anchor

Call Message Events (Beta)

call-message-events-beta page anchor

The SDK can now send and receive custom messages to and from Twilio's backend via the following new Call APIs.

Please visit this page for more details about this feature. Additionally, please see the following for more information on how to send and receive messages on the server.

NOTE: This feature should not be used with PII.

Example

1
const device = new Device(token, options);
2
3
const setupCallHandlers = call => {
4
call.on('messageReceived', message => messageReceivedHandler(message));
5
call.on('messageSent', message => messageSentHandler(message));
6
};
7
8
// For outgoing calls
9
const call = await device.connect();
10
setupCallHandlers(call);
11
12
// For incoming calls
13
device.on('incoming', call => setupCallHandlers(call));
14
await device.register();
15
16
// For sending a message
17
const eventSid = call.sendMessage({
18
content: { foo: 'foo' },
19
messageType: Call.MessageType.UserDefinedMessage,
20
});

2.1.2 (October 26, 2022)

212-october-26-2022 page anchor
  • Fixed an issue where insights data stops getting published after calling device.updateOptions.

2.1.1 (February 18, 2022)

211-february-18-2022 page anchor
  • Ignoring a call will now properly stop the ringing sound
  • NPM versioning has been fixed to specify >=12 rather than exactly 12
  • Use DOMException instead of DOMError, which has been deprecated
  • Removed npm util from the package, instead favoring native functions

2.1.0 (January 6, 2022)

210-january-6-2022 page anchor

Signaling reconnection support

signaling-reconnection-support page anchor

The Voice JavaScript SDK now fully supports Call reconnection. If the media connection or signaling websocket is lost, the SDK is able to attempt to reconnect the Call. A Call can now potentially be recovered up to 30 seconds after a media or signaling connection loss.

The Twilio.Device will emit a 'reconnecting' event when a connectivity loss occurs, and a 'reconnected' event upon successful reconnection.

There exists a limitation such that Signaling Reconnection and Edge Fallback are mutually exclusive. To opt-in to the Signaling Reconnection feature, a new option can be passed to the SDK: maxCallSignalingTimeoutMs. If this value is not present in the options object passed to the Device constructor, the default value will be 0. Reconnection can only happen with an up-to-date AccessToken.

(warning)

Warning

Customers relying on edge fallback, along with a small subset of customers using the 'roaming' edge, will not automatically benefit from this feature without additional configuration. Go to the Edge Locations page for more information.

Keep AccessToken up to date with tokenWillExpire event and DeviceOptions.tokenWillExpire

keep-accesstoken-up-to-date-with-tokenwillexpire-event-and-deviceoptionstokenwillexpire page anchor

The Voice JavaScript SDK now provides two additional features to help keep your AccessTokens up to date:

  1. The 'tokenWillExpire' event, which will be emitted by the Twilio.Device before its associated AccessToken is set to expire. By default, it will be emitted 10 seconds before the AccessToken's expiration.
  2. The DeviceOptions.tokenRefreshMs property that can configure the timing of the 'tokenWillExpire' event.

You can use these new features in conjunction with the device.updateToken() method to automatically keep an AccessToken up to date.

In the following example, the 'tokenWillExpire' event will be emitted 30 seconds (3000 milliseconds) before the AccessToken is set to expire, and the event listener for the 'tokenWillExpire' event will retrieve a new AccessToken and update the Device's AccessToken with the device.updateToken() method.

1
const device = new Device(token, {
2
// 'tokenWillExpire' event will be emitted 30 seconds before the AccessToken expires
3
tokenRefreshMs: 30000,
4
});
5
6
device.on('tokenWillExpire', () => {
7
return getTokenViaAjax().then(token => dev.updateToken(token));
8
});

Support for Twilio Regions

support-for-twilio-regions page anchor

The Twilio Voice JavaScript SDK now supports Twilio Regions.

If you are part of the Twilio Regions Pilot and wish to specify a home region when using the Voice JavaScript SDK, you will need to:

  1. Create AccessTokens with API Keys and API Key Secrets that are stored in the specified Twilio Region, and include the Region name when creating the AccessToken. See example below.
  2. Use an edge location that matches your specified Region when instantiating your Twilio.Device.

Below is an example of how you would use the Node.js Helper Library to create AccessTokens for the Voice JavaScript SDK for a Region.

1
const accessToken = const accessToken = new twilio.jwt.AccessToken(
2
credentials.accountSid,
3
credentials.apiKeySid,
4
credentials.apiKeySecret, {
5
identity,
6
ttl,
7
region: 'au1',
8
},
9
);
10
11
const grant = new VoiceGrant({
12
outgoingApplicationSid: credentials.twimlAppSid,
13
incomingAllow: true,
14
});
15
16
accessToken.addGrant(grant);

Note: The API Key and Secret above must be created within the au1 region. It's recommended that the TwiML App used in the Voice Grant is also created in the same Region.

The example below shows how to pass the au1-related edge location to the Twilio.Device constructor.

1
const device = new Device(accessToken, {
2
edge: 'sydney',
3
});

The new Twilio.Device.home accessor will return a string value of the home region of the device instance, given that it successfully connected with Twilio.

(information)

Info

Existing EU customers can now migrate their Voice use-cases to the data center in Ireland to establish data residency within the region. In addition, new customers may now select Ireland as their region of choice for Voice related use cases. There is no additional cost to use the new data center in Ireland. To learn more about Regional Voice in Ireland, check out our blog post(link takes you to an external page) or head over to our Global Infrastructure docs to get started.

The Voice JavaScript SDK now exposes a Twilio.Device.identity accessor.

Given that a Twilio.Device has registered successfully with Twilio, the Twilio.Device.identity accessor will return a read-only string containing the identity that was passed to the AccessToken used to instantiate the Twilio.Device.

  • Updated ws version to fix a potential security vulnerability
  • All event listeners will now be properly cleaned up after calling Twilio.Device.destroy()
  • When Insights fails to post an event, the SDK now logs a warning rather than an Uncaught Promise Rejection

2.0.0 (July 9, 2021)

200-july-9-2021 page anchor

Device singleton behavior removed

device-singleton-behavior-removed page anchor

Device must now be instantiated before it can be used. Calling Device.setup() will no longer work; instead, a new Device must be instantiated via new Device(token, options?).

Connection renamed to Call

connection-renamed-to-call page anchor

As Connection is an overloaded and ambiguous term, the class has been renamed Call to better indicate what the object represents and be more consistent with Mobile SDKs and our REST APIs.

Signaling connection now lazy loaded

signaling-connection-now-lazy-loaded page anchor

Device.setup() has been removed, and new Device(...) will not automatically begin connecting to signaling. There is no need to listen for Device.on('ready'). Instead, the signaling connection will automatically be acquired in one of two scenarios:

  1. The application calls Device.connect(), creating an outbound Call. In this case, the state of the signaling connection will be represented in the Call.
  2. The application calls Device.register(), which will register the client to listen for incoming calls at the identity specified in the AccessToken.
Note on token expiration
note-on-token-expiration page anchor

As long as outgoing calls are expected to be made, or incoming calls are expected to be received, the token supplied to Device should be fresh and not expired. This can be done by setting a timer in the application to call updateToken with the new token shortly before the prior token expires. This is important, because signaling connection is lazy loaded and will fail if the token is not valid at the time of creation.

Example:

1
const TTL = 600000; // Assuming our endpoint issues tokens for 600 seconds (10 minutes)
2
const REFRESH_TIMER = TTL - 30000; // We update our token 30 seconds before expiration;
3
const interval = setInterval(async () => {
4
const newToken = await getNewTokenViaAjax();
5
device.updateToken(newToken);
6
}, REFRESH_TIMER);

The Device states have changed. The states were: [Ready, Busy, Offline]. These have been changed to more accurately and clearly represent the states of the Device. There are two changes to Device state:

  1. The states themselves have changed to [Registered, Registering, Unregistered, Destroyed]. This removes the idea of "Busy" from the state, as technically the Device can have an active Call whether it is registered or not, depending on the use case. The Device will always start as Unregistered. In this state, it can still make outbound Calls. Once Device.register() has been called, this state will change to Registering and finally Registered. If Device.unregister() is called the state will revert to Unregistered. If the signaling connection is lost, the state will transition to Registering or `Unregistered' depending on whether or not the connection can be re-established.

The destroyed state represents a Device that has been "destroyed" by calling Device.destroy. The device should be considered unusable at this point and a new one should be constructed for further use.

  1. The busy state has been moved to a Boolean, Device.isBusy. This is a very basic shortcut for the logic return !!device.activeConnection.

The events emitted by the Device are represented by the Device.EventName enum and represent the new Device states:

1
export enum EventName {
2
Destroyed = 'destroyed',
3
Error = 'error',
4
Incoming = 'incoming',
5
Unregistered = 'unregistered',
6
Registering = 'registering',
7
Registered = 'registered',
8
}

Note that unregistered, registering, and registered have replaced offline and ready. Although frequently used to represent connected or disconnected, ready and offline actually were meant to represent registered and unregistered, which was quite ambiguous and a primary reason for the change.

When the device is destroyed using Device.destroy, a "destroyed" event will be emitted.

The construction signature and usage of Device has changed. These are the new API signatures:

1
/**
2
* Create a new Device. This is synchronous and will not open a signaling socket immediately.
3
*/
4
new Device(token: string, options?: Device.Options): Device;
5
6
/**
7
* Promise resolves when the Device has successfully registered.
8
* Replaces Device.registerPresence()
9
* Can reject if the Device is unusable, i.e. "destroyed".
10
*/
11
async Device.register(): Promise<void>;
12
/**
13
* Promise resolves when the Device has successfully unregistered.
14
* Replaces Device.unregisterPresence()
15
* Can reject if the Device is unusable, i.e. "destroyed".
16
*/
17
async Device.unregister(): Promise<void>;
18
/**
19
* Promise resolves when signaling is established and a Call has been created.
20
* Can reject if the Device is unusable, i.e. "destroyed".
21
*/
22
async Device.connect(options?: Device.ConnectOptions): Promise<Call>;
Listening for incoming calls
listening-for-incoming-calls page anchor
1
const device = new Device(token, { edge: 'ashburn' });
2
3
device.on(Device.EventName.Incoming, call => { /* use `call` here */ });
4
await device.register();
1
const device = new Device(token, { edge: 'ashburn' });
2
const call = await device.connect({ To: 'alice' });

Device CallOptions and Call AcceptOptions standardized

device-calloptions-and-call-acceptoptions-standardized page anchor

The arguments for Device.connect() and Call.accept() have been standardized to the following options objects:

1
interface Call.AcceptOptions {
2
/**
3
* An RTCConfiguration to pass to the RTCPeerConnection constructor.
4
*/
5
rtcConfiguration?: RTCConfiguration;
6
7
/**
8
* MediaStreamConstraints to pass to getUserMedia when making or accepting a Call.
9
*/
10
rtcConstraints?: MediaStreamConstraints;
11
}
1
interface Device.ConnectOptions extends Call.AcceptOptions {
2
/**
3
* A flat object containing key\:value pairs to be sent to the TwiML app.
4
*/
5
params?: Record<string, string>;
6
}

Note that these now take a MediaStreamConstraints(link takes you to an external page) rather than just the audio constraints. For example:

device.connect({ To: 'client:alice' }, { deviceId: 'default' });

might be re-written as:

1
device.connect({
2
params: { To: 'client:alice' },
3
rtcConstraints: { audio: { deviceId: 'default' } },
4
});

Moved to new Error format

moved-to-new-error-format page anchor

For backward compatibility, the new error format was attached to the old format under error.twilioError:

1
class oldError extends Error {
2
//...
3
code: number;
4
message: string;
5
twilioError: TwilioError;
6
}

The new Error format is:

1
class TwilioError extends Error {
2
/**
3
* A list of possible causes for the Error.
4
*/
5
causes: string[];
6
7
/**
8
* The numerical code associated with this Error.
9
*/
10
code: number;
11
12
/**
13
* A description of what the Error means.
14
*/
15
description: string;
16
17
/**
18
* An explanation of when the Error may be observed.
19
*/
20
explanation: string;
21
22
/**
23
* Any further information discovered and passed along at run-time.
24
*/
25
message: string;
26
27
/**
28
* The name of this Error.
29
*/
30
name: string;
31
32
/**
33
* The original Error received from the external system, if any.
34
*/
35
originalError?: Error;
36
37
/**
38
* A list of potential solutions for the Error.
39
*/
40
solutions: string[];
41
}

With the transition, the following error codes have changed:

  • 31003 -> 53405 | When ICE connection fails
  • 31201 -> 31402 | When getting user media fails
  • 31208 -> 31401 | When user denies access to user media
  • 31901 -> 53000 | When websocket times out in preflight

Previously, Device.setup() could only be used the set options once. Now, we've added Device.updateOptions(options: Device.Options) which will allow changing the Device options without instantiating a new Device. Note that the edge cannot be changed during an active Call.

Example usage:

1
const options = { edge: 'ashburn' };
2
const device = new Device(token, options);
3
4
// Later...
5
6
device.updateOptions({ allowIncomingWhileBusy: true });

The resulting (non-default) options would now be:

1
{
2
allowIncomingWhileBusy: true,
3
edge: 'ashburn',
4
}

This function will throw with an InvalidStateError if the Device has been destroyed beforehand.

The SDK now uses the loglevel(link takes you to an external page) module. This exposes several new features for the SDK, including the ability to intercept log messages with custom handlers and the ability to set logging levels after instantiating a Device. To get an instance of the loglevel Logger class used internally by the SDK:

1
import { Logger as TwilioClientLogger } from '@twilio/voice-client-sdk';
2
...
3
TwilioClientLogger.setLogLevel('DEBUG');

Please see the original loglevel(link takes you to an external page) project for more documentation on usage.

  • Removed Connection.mediaStream. To access the MediaStreams, use Connection.getRemoteStream() and Connection.getLocalStream()
  • Removed Connection.message in favor of the newer Connection.customParameters. Where .message was an Object, .customParameters is a Map.
  • Removed the following private members from the public interface:
    • Connection.options
    • Connection.pstream
    • Connection.sendHangup
  • Fixed Connection.on('cancel') logic so that we no longer emit cancel in response to Connection.ignore().

Device Option Deprecations

device-option-deprecations page anchor

Some deprecated Device options have been removed. This includes:

  • enableIceRestart
  • enableRingingState
  • fakeLocalDtmf

The above three removed options are now assumed true. The new Device.Options interface is now:

1
export interface Options {
2
allowIncomingWhileBusy?: boolean;
3
appName?: string;
4
appVersion?: string;
5
audioConstraints?: MediaTrackConstraints | boolean;
6
closeProtection?: boolean | string;
7
codecPreferences?: Connection.Codec[];
8
disableAudioContextSounds?: boolean;
9
dscp?: boolean;
10
edge?: string[] | string;
11
forceAggressiveIceNomination?: boolean;
12
maxAverageBitrate?: number;
13
rtcConfiguration?: RTCConfiguration;
14
sounds?: Partial<Record<Device.SoundName, string>>;
15
}

The formula used to calculate the mean-opinion score (MOS) has been fixed for extreme network conditions. These fixes will not affect scores for nominal network conditions.


For the version 1.x changelog, see Voice JavaScript SDK v1 changelog.