Create a client that will be responsible to communicate with Liveblocks servers.
When creating a client with a public key, you donโt need to setup an authorization endpoint:
If you are not using a public key, you need to setup your own authEndpoint
.
Please refer to our Authentication guide.
If you need to add additional headers or use your own function to call the
endpoint, authEndpoint
also supports a callback.
If you want to use @liveblocks/client
with
React Native, you need to add an atob
polyfill.
As a polyfill, we recommend installing the package base-64
.
Then you can pass the decode
function to our atob
polyfill option when you
create the client.
If you want to use @liveblocks/client
in a Node.js environment, you need to
provide WebSocket
and fetch
polyfills.
As polyfills, we recommend installing the packages ws
and
node-fetch
.
Then, pass them to the createClient
function as below.
Note that node-fetch
v3+
does not support CommonJS.
If you are using CommonJS, downgrade node-fetch
to v2.
By default, the client throttle the WebSocket messages sent to 100 milliseconds.
It is possible to override that configuration with the throttle
option.
throttle
should be between 80 and 1000 milliseconds.
Client returned by createClient
.
Enters a room and returns it. The authentication endpoint is called as soon as you call this function.
The second argument is a configuration for the presence and storage.
initialPresence
- The initial Presence to use for the User currently
entering the Room. Presence data belongs to the current User and is readable
to all other Users in the room while the current User is connected to the
Room. Must be serializable to JSON.initialStorage
(optional) - The initial Storage structure to create when a
new Room is entered for the first time. Storage data is shared and belongs to
the Room itself. It persists even after all Users leave the room, and is
mutable by every client. Must either contain Live structures (e.g.
new LiveList()
, new LiveObject({ a: 1 })
, etc.) or be serializable to
JSON.shouldInitiallyConnect
(optional) - Whether or not the room connects to
Liveblocks servers. Default is true
. Usually set to false
when the client
is used from the server to not call the authentication endpoint or connect via
WebSocket.Leaves a room.
Gets a room by id. Returns null
if client.enter
has not been called
previously.
Room returned by client.enter
or client.getRoom
.
Gets the presence of the current user.
Updates the presence of the current user. Only pass the properties you want to update. No need to send the full presence.
updatePresence
accepts an optional argument to add a new item to the undo/redo
stack. See room.history
for more information.
Gets all the other users in the Room.
Broadcast an event to other users in the Room. Event broadcasted to the room can
be listened with Room.subscribe("event")
. Takes a payload as first
argument. Should be serializable to JSON.
By default, broadcasting an event acts as a โfire and forgetโ. If the user is
not currently in the room, the event is simply discarded. With the option
shouldQueueEventIfNotReady
, the event will be queued and sent once the
connection is established.
We are not sure if we want to support this option in the future so it might be deprecated to be replaced by something else.
Gets the current user. Returns null
if it is not yet connected to the room.
Subscribe to updates for a particular storage item.
Takes a callback that is called when the storage item is updated.
Returns an unsubscribe function.
Itโs also possible to subscribe to a storage item and its children by passing an
optional isDeep
parameter. In that case, the callback will get called with a
list of updates instead. Each such update is a { type, node }
object.
Subscribe to events broadcasted by Room.broadcastEvent
.
Takes a callback that is called when a user calls Room.broadcastEvent
.
Returns an unsubscribe function.
Subscribe to the current user presence updates.
Takes a callback that is called every time the current user presence is updated
with Room.updatePresence
.
Returns an unsubscribe function.
Subscribe to the other users updates.
Takes a callback that is called when a user enters or leaves the room or when a user update its presence.
Returns an unsubscribe function.
Subscribe to the WebSocket connection status updates.
Takes a callback that is called when the connection status changes.
The value can be : authenticating
, connecting
, open
, failed
, closed
or
unavailable
.
Returns an unsubscribe function.
Subscribe to potential room connection errors.
Returns an unsubscribe function.
Subscribe to the current userโs history changes.
Returns an unsubscribe function.
Subscribe to storage status changes.
Returns an unsubscribe function.
Batches modifications made during the given function.
All the modifications are sent to other clients in a single message.
All the subscribers are called only after the batch is over.
All the modifications are merged in a single history item (undo/redo).
Roomโs history contains functions that let you undo and redo operation made on by the current client on the presence and storage.
Undoes the last operation executed by the current client. It does not impact operations made by other clients.
Redoes the last operation executed by the current client. It does not impact operations made by other clients.
Returns whether there are any operations to undo.
Returns whether there are any operations to redo.
All future modifications made on the Room will be merged together to create a single history item until resume is called.
Resumes history. Modifications made on the Room are not merged into a single history item anymore.
Get the storage status.
not-loaded
: Initial state when entering the room.loading
: Once the storage has been requested via room.getStorage().synchronizing
: When some local updates have not been acknowledged by
Liveblocks servers.synchronized
: Storage is in sync with Liveblocks servers.Close the room connection and try to reconnect.
The following APIs are subject to change during the beta.
The roomโs storage is a conflicts-free state that multiple users can edit at the same time. It persists even after everyone leaves the room. Liveblocks provides 3 data structures that can be nested to create the state that you want.
LiveObject
- Similar to JavaScript object. Use this for storing records
with fixed key names and where the values donโt necessarily have the same
types. For example, a Person
with a name
(string) and an age
(number)
field.
If multiple clients update the same property simultaneously, the last modification received by the Liveblocks servers is the winner.
LiveList
- An ordered collection of items synchronized across clients.
Even if multiple users add/remove/move elements simultaneously, LiveList will
solve the conflicts to ensure everyone sees the same collection of items.
LiveMap
- Similar to a JavaScript Map. Use this for indexing values that
all have the same structure. For example, to store an index of Person
values
by their name. If multiple users update the same property simultaneously, the
last modification received by the Liveblocks servers is the winner.
Get the roomโs storage asynchronously (returns a Promise). The storageโs root is
a LiveObject
.
The LiveObject
class is similar to a JavaScript object that is synchronized on
all clients. Use this for storing records with fixed key names and where the
values donโt necessarily have the same types. For example, a Person with a
name
(string) and an age
(number) field.
Keys should be strings, and values should be serializable to JSON.
If multiple clients update the same property simultaneously, the last modification received by the Liveblocks servers is the winner.
Create an empty LiveObject
Create a LiveObject
with initial data.
Delete a property from the LiveObject
Get a property from the LiveObject
Adds or updates a property with the specified key and a value.
Adds or updates multiple properties at once.
Starting with 0.18, we recommend toImmutable
instead. Itโs faster, cached,
and leads to fewer surprises.
Transform the LiveObject
into a normal JavaScript object.
Please note that this method wonโt recursively convert Live structures, which may be surprising:
Returns an immutable JavaScript object that is equivalent to the LiveObject
.
Nested values will also be immutable.
The LiveMap
class is similar to a
JavaScript Map
that is synchronized on all clients.
Use this for indexing values that all have the same structure. For example, to
store an index of Person
values by their name. Keys should be strings, and
values should be serializable to JSON. If multiple clients update the same
property simultaneously, the last modification received by the Liveblocks
servers is the winner.
Create an empty LiveMap
.
Create a LiveMap
with initial data.
Removes the specified element by key. Returns true if an element existed and has been removed, or false if the element does not exist.
Returns a new
Iterator
object that contains the [key, value]
pairs for each element.
If your TypeScript project targets es5
or lower, youโll need to
enable the --downlevelIteration
option to use this API.
Executes a provided function once per each key/value pair in the Map object.
Returns a specified element from the LiveMap or undefined if the key canโt be found.
Returns a boolean indicating whether an element with the specified key exists or not.
Returns a new Iterator object that contains the keys for each element.
If your TypeScript project targets es5
or lower, youโll need to
enable the --downlevelIteration
option to use this API.
Adds or updates an element with a specified key and a value.
Returns the number of elements in the LiveMap
.
Returns a new Iterator object that contains the the values for each element.
If your TypeScript project targets es5
or lower, youโll need to
enable the --downlevelIteration
option to use this API.
Returns an immutable ES6 Map that is equivalent to the LiveMap
. Nested values
will also be immutable.
The LiveList
class represents an ordered collection of items that is
synchorinized across clients. Items should be serializable to JSON or another
Live data structure.
Create an empty LiveList
Create a LiveList
with initial data
Removes all the elements.
Deletes an element at the specified index.
Tests whether all elements pass the test implemented by the provided function. Returns true if the predicate function returns a truthy value for every element. Otherwise, false.
Creates an array with all elements that pass the test implemented by the provided function.
Returns the first element that satisfies the provided testing function.
Returns the index of the first element in the LiveList
that satisfies the
provided testing function.
Executes a provided function once for each element.
Get the element at the specified index.
Returns the first index at which a given element can be found in the LiveList
,
or -1 if it is not present.
Inserts one element at a specified index.
Returns the last index at which a given element can be found in the LiveList
,
or -1 if it is not present. The LiveList
is searched backwards, starting at
fromIndex.
Returns the number of elements.
Creates an array populated with the results of calling a provided function on every element.
Moves one element at a specified index.
Adds one element to the end of the LiveList
.
Replace one element at the specified index.
Tests whether at least one element in the LiveList
passes the test implemented
by the provided function.
Starting with 0.18, we recommend toImmutable
instead. Itโs faster, cached,
and leads to fewer surprises.
Transforms the LiveList
into a normal JavaScript array.
Please note that this method wonโt recursively convert Live structures, which may be surprising:
Returns an immutable JavaScript array that is equivalent to the LiveList
.
Nested values will also be immutable.