How to create a collaborative text editor with Quill, Yjs, Next.js, and Liveblocks

In this tutorial, we’ll be building a collaborative text editor using Quill, Yjs, Next.js, and Liveblocks.

This guide assumes that you’re already familiar with React, Next.js, TypeScript, and Quill.

Install Quill, Yjs, and Liveblocks into your Next.js application

Run the following command to install the Quill, Yjs, and Liveblocks packages:

$npm install @liveblocks/client @liveblocks/react @liveblocks/yjs yjs quill quill-cursors react-quill y-quill

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.

import { Liveblocks } from "@liveblocks/node";import { NextRequest } from "next/server";
const API_KEY = "";
const liveblocks = new Liveblocks({ secret: API_KEY!,});
export async function POST(request: NextRequest) { // Get the current user's info from your database const user = { id: "charlielayne@example.com", info: { name: "Charlie Layne", color: "#D583F0", picture: "https://liveblocks.io/avatars/avatar-1.png", }, };
// Create a session for the current user // userInfo is made available in Liveblocks presence hooks, e.g. useOthers const session = liveblocks.prepareSession(user.id, { userInfo: user.info, });
// Give the user access to the room const { room } = await request.json(); session.allow(room, session.FULL_ACCESS);
// Authorize the user and return the result const { body, status } = await session.authorize(); return new Response(body, { status });}

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.

$npx create-liveblocks-app@latest --init --framework react

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.

const client = createClient({  authEndpoint: "/api/liveblocks-auth",});

Join a Liveblocks room

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 it Room.tsx.

/app/Room.tsx
"use client";
import { ReactNode } from "react";import { RoomProvider } from "../liveblocks.config";import { ClientSideSuspense } from "@liveblocks/react";
export function Room({ children }: { children: ReactNode }) { return ( <RoomProvider id={roomId} initialPresence={{ cursor: null, }} > <ClientSideSuspense fallback={<div>Loading…</div>}> {() => children} </ClientSideSuspense> </RoomProvider> );}

Set up the Quill editor

Now that we’ve set up Liveblocks, we can start integrating Tiptap and Yjs in the Editor.tsx file.

Editor.tsx
"use client";
import Quill from "quill";import ReactQuill from "react-quill";import { QuillBinding } from "y-quill";import * as Y from "yjs";import LiveblocksProvider from "@liveblocks/yjs";import { useRoom } from "@/liveblocks.config";import { useEffect, useRef, useState } from "react";import styles from "./Editor.module.css";
// Collaborative text editor with simple rich text, live cursors, and live avatarsexport function CollaborativeEditor() { const room = useRoom(); const [text, setText] = useState<Y.Text>(); const [provider, setProvider] = useState<any>();
// Set up Liveblocks Yjs provider useEffect(() => { const yDoc = new Y.Doc(); const yText = yDoc.getText("quill"); const yProvider = new LiveblocksProvider(room, yDoc); setText(yText); setProvider(yProvider);
return () => { yDoc?.destroy(); yProvider?.destroy(); }; }, [room]);
if (!text || !provider) { return null; }
return <QuillEditor yText={text} provider={provider} />;}
type EditorProps = { yText: Y.Text; provider: any;};
function QuillEditor({ yText, provider }: EditorProps) { const reactQuillRef = useRef<ReactQuill>(null);
// Set up Yjs and Quill useEffect(() => { let quill: ReturnType<ReactQuill["getEditor"]>; let binding: QuillBinding;
if (!reactQuillRef.current) { return; }
quill = reactQuillRef.current.getEditor(); binding = new QuillBinding(yText, quill, provider.awareness); return () => { binding?.destroy?.(); }; }, [yText, provider]);
return ( <div className={styles.container}> <div className={styles.editorContainer}> <ReactQuill className={styles.editor} placeholder="Start typing here…" ref={reactQuillRef} theme="snow" modules={{ toolbar: false, history: { // Local undo shouldn't undo changes from remote users userOnly: true, }, }} /> </div> </div> );}

And here is the Editor.module.css file to make sure your multiplayer text editor looks nice and tidy.

We recommend importing some global styles into your layout.tsx or page.tsx file too. We’ll be creating a custom UI, but some classes are still necessary for Quill:

Add your editor to the current page

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 collaborative editor!

/app/page.tsx
import { Room } from "./Room";import CollaborativeEditor from "@/components/Editor";
export default function Page() { return ( <Room> <CollaborativeEditor /> </Room> );}

Add live cursors

To add live cursors to the text editor, we can get the userInfo for the current user with useSelf, and feed it into editor. We should now see some cursors with names.

CollaborativeEditor.tsx
import { useSelf } from "../liveblocks.config.ts";// ...
Quill.register("modules/cursors", QuillCursors);
// ...
function QuillEditor({ yText, provider }: EditorProps) { // Add user info to cursors from Liveblocks authentication endpoint const userInfo = useSelf((me) => me.info); useEffect(() => { const { name, color } = userInfo; provider.awareness.setLocalStateField("user", { name, color, }); }, [userInfo]);
// ...
return ( <div className={styles.container}> <div className={styles.editorContainer}> <ReactQuill className={styles.editor} placeholder="Start typing here…" ref={reactQuillRef} theme="snow" modules={{ cursors: true, toolbar: false, history: { // Local undo shouldn't undo changes from remote users userOnly: true, }, }} /> </div> </div> );}

Add a toolbar

From this point onwards, you can build your Quill app as normal! For example, should you wish to add a basic text-style toolbar to your app:

Toolbar.tsx
import styles from "./Toolbar.module.css";import { QuillEditorType } from "@/components/CollaborativeEditor";import { useCallback } from "react";
type Props = { getQuill: () => QuillEditorType | null;};
type Formats = "bold" | "italic" | "underline";
export function Toolbar({ getQuill }: Props) { const formatSelection = useCallback( (format: Formats) => { const quill = getQuill(); if (!quill) { return; }
const selection = quill.getSelection(); if (!selection) { return; }
const { index, length } = selection; const hasFormat = quill.getFormat(index, length)[format];
quill.formatText( index, length, { [format]: !hasFormat, }, "user" ); }, [getQuill] );
return ( <div className={styles.toolbar}> <button className={styles.button} onClick={() => formatSelection("bold")} aria-label="bold" > B </button> <button onClick={() => formatSelection("italic")} className={styles.button} aria-label="italic" > I </button> <button onClick={() => formatSelection("underline")} className={styles.button} aria-label="underline" > U </button> </div> );}

Add some matching styles:

You can then import this into your editor, and create the getQuill function to enable basic rich-text:

Editor.tsx
import { Toolbar } from "./Toolbar";// ...
function QuillEditor({ yText, provider }: EditorProps) { // ...
// Function to get the current Quill editor const getQuill = useCallback(() => { if (!reactQuillRef.current) { return null; }
return reactQuillRef.current.getEditor(); }, []);
return ( <div className={styles.container}> <div className={styles.editorHeader}> <Toolbar getQuill={getQuill} /> </div> <div className={styles.editorContainer}>{/* ... */}</div> </div> );}

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.

Avatars.tsx
import { useOthers, useSelf } from "@/liveblocks.config";import styles from "./Avatars.module.css";
export function Avatars() { const users = useOthers(); const currentUser = useSelf();
return ( <div className={styles.avatars}> {users.map(({ connectionId, info }) => { return ( <Avatar key={connectionId} picture={info.picture} name={info.name} /> ); })}
{currentUser && ( <div className="relative ml-8 first:ml-0"> <Avatar picture={currentUser.info.picture} name={currentUser.info.name} /> </div> )} </div> );}
export function Avatar({ picture, name }: { picture: string; name: string }) { return ( <div className={styles.avatar} data-tooltip={name}> <img src={picture} className={styles.avatar_picture} data-tooltip={name} /> </div> );}

And here’s the styles:

You can then import this into your editor to see it in action:

Editor.tsx
import { Avatars } from "./Avatars";// ...
function QuillEditor({ yText, provider }: EditorProps) { // ...
return ( <div className={styles.container}> <div className={styles.editorHeader}> <Toolbar getQuill={getQuill} /> <Avatars /> </div> <div className={styles.editorContainer}>{/* ... */}</div> </div> );}

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.