How to create a collaborative text editor with Slate, Yjs, Next.js, and Liveblocks
In this tutorial, we’ll be building a collaborative text editor using Slate, Yjs, Next.js, and Liveblocks.
Run the following command to install the Slate, Yjs, and Liveblocks packages:
transpilePackages to your
next.config.ts file to allow
@slate-yjs/react to be bundled correctly.
Note that if you’re seeing an error that resembles the following, you’re
probably using an older version of Next.js that doesn’t support
You may need to upgrade to a newer version of Next.js for this to work.
The first step in connecting to Liveblocks is to set up an authentication
Here’s an example using the older API routes format in
Let’s initialize the
liveblocks.config.ts file in which you’ll set up the
Next, we can create the front end client which will be responsible for
communicating with the back end. You can do this by modifying
your config file, and passing the location of your endpoint.
Liveblocks uses the concept of rooms, separate virtual spaces where people
collaborate. To create a real-time experience, multiple users must be connected
to the same room. Create a file in the current directory within
/app, and name
Now that we’ve set up Liveblocks, we can start integrating Slate and Yjs in the
And here is the
Editor.module.css file to make sure your multiplayer text
editor looks nice and tidy.
Next, add the
CollaborativeEditor into the page file, and place it inside the
Room component we created earlier. We should now be seeing a basic
To add live cursors to the text editor, we can rely on hooks from the
And of course we need some corresponding CSS to keep the cursors in the correct positions.
Back in your
Editor component, get the current user’s info with
useSelf, add the
plugin, and pass the user info and awareness. Then wrap your editor in the
Cursors component to see them working.
From this point onwards, you can build your Slate app as normal! For example, should you wish to add a basic text-style toolbar to your app:
Add some matching styles:
These styles are rendered with leaf components, which we’ll add to a new file:
You can then import this into your editor to enable basic rich-text:
Along with building out your text editor, you can now use other Liveblocks
features, such as Presence. The
useOthers hook allows us to
view information about each user currently online, and we can turn this into a
live avatars component.
And here’s the styles:
You can then import this to your editor to see it in action:
Note that the cursors and avatars match in color and name, as the info for both is sourced from the Liveblocks authentication endpoint.
You should now see the complete editor, along with live cursors, live avatars, and some basic rich-text features! On GitHub we have a working example of this multiplayer text editor.