How to modify Liveblocks Storage from the server
In realtime applications, Liveblocks Storage is generally modified from the
browser with useMutation
or through
conflict-free data methods.
However, sometimes it can be useful to modify your realtime storage from
server-side Node.js too.
What we’re building
In this guide, we’ll be building a function that allows you to easily modify
storage from the server. We’ll do this by running @liveblocks/client
server-side using Node.js polyfills, and by signing in with a service account
userId
.
Set up Liveblocks server config
The first thing we need to do is to install the required Node.js polyfills.
After this we can create a server config file, which we’ll name
liveblocks.server.config.ts
. In this file we’re implementing the following.
- Creating a node client with
new Liveblocks
. Creating a regular client to be used on the server,
serverClient
.- Authenticating inside the regular client.
Using the same
userId
for server changes, so that MAUs do not increase.- Adding Node.js polyfills to the regular client.
- Creating a typed enter room function.
Here’s the full file:
Create the modify storage function
Using serverClient
and enterRoom
from the previous file, we can create a
typed modifyStorage
function that allows us to join a room, modify storage
(batching all changes into one request), before leaving the room.
Start modifying storage
We can now start modify storage from the server! Import modifyStorage
, pass a
room name, and use the callback to modify as you like.
Account for the service user in your app
Remember to account for the service user appearing in your presence. In our
liveblocks.server.config.ts
we authenticated with "_SERVICE_ACCOUNT"
as the
userId
, so we’ll filter it out when using others in our application.
A shallow
equality check is necessary here, because filter
creates a new
array every time.