How to create a collaborative text editor with Lexical, Yjs, Next.js, and Liveblocks
In this tutorial, we’ll be building a collaborative text editor using Lexical, Yjs, Next.js, and Liveblocks.
This guide assumes that you’re already familiar with React, Next.js, TypeScript, and Lexical.
Install Lexical, Yjs, and Liveblocks into your React application
Run the following command to install the Lexical, Yjs, and Liveblocks packages:
Set up access token authentication
The first step in connecting to Liveblocks is to set up an authentication
endpoint in /app/api/liveblocks-auth/route.ts
.
Here’s an example using the older API routes format in /pages
.
Initialize your Liveblocks config file
Let’s initialize the liveblocks.config.ts
file in which you’ll set up the
Liveblocks client.
Set up the client
Next, we can create the front end client which will be responsible for
communicating with the back end. You can do this by modifying createClient
in
your config file, and passing the location of your endpoint.
Join a Liveblocks room
Liveblocks uses the concept of rooms, separate virtual spaces where people
collaborate. To create a realtime experience, multiple users must be connected
to the same room. Create a file in the current directory within /app
, and name
it Room.tsx
.
Set up the Lexical editor
Now that we set up Liveblocks, we can start integrating Lexical and Yjs in the
Editor.tsx
file.
And here is the Editor.module.css
file to make sure your multiplayer text
editor looks nice and tidy.
Add live cursors
To add live cursors to the text editor, we can pass the current user’s
information from our authentication endpoint into CollaborationPlugin
.
Add a toolbar
From this point onwards, you can build your Lexical app as normal! For example, should you wish to add a basic text-style toolbar to your app:
Add some matching styles:
You can then import this into your editor to enable basic rich-text:
Theme your text styles
You can go a step further and theme your basic custom text styles by using the
theme
property, and adding corresponding styles:
And then in your CSS module, you can style your rich-text:
Create live avatars with Liveblocks hooks
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.
Try it out
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.