How to create a collaborative code editor with CodeMirror, Yjs, Next.js, and Liveblocks

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

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

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

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

$npm install @liveblocks/client @liveblocks/react @liveblocks/node @liveblocks/yjs yjs codemirror @codemirror/lang-javascript y-codemirror.next

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

We’ll also need another type for this tutorial. After creating the config file, open it up and insert the following:

liveblocks.config.ts
import LiveblocksProvider from "@liveblocks/yjs";
// ...
export type TypedLiveblocksProvider = LiveblocksProvider< Presence, Storage, UserMeta, RoomEvent>;

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 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.

/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 CodeMirror editor

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

Editor.tsx
"use client";
import * as Y from "yjs";import { yCollab } from "y-codemirror.next";import { EditorView, basicSetup } from "codemirror";import { EditorState } from "@codemirror/state";import { javascript } from "@codemirror/lang-javascript";import { useCallback, useEffect, useState } from "react";import LiveblocksProvider from "@liveblocks/yjs";import { TypedLiveblocksProvider, useRoom } from "@/liveblocks.config";import styles from "./CollaborativeEditor.module.css";
// Collaborative code editor with undo/redo, live cursors, and live avatarsexport function CollaborativeEditor() { const room = useRoom(); const [element, setElement] = useState<HTMLElement>(); const [yUndoManager, setYUndoManager] = useState<Y.UndoManager>();
const ref = useCallback((node: HTMLElement | null) => { if (!node) return; setElement(node); }, []);
// Set up Liveblocks Yjs provider and attach CodeMirror editor useEffect(() => { let provider: TypedLiveblocksProvider; let ydoc: Y.Doc; let view: EditorView;
if (!element || !room || !userInfo) { return; }
// Create Yjs provider and document ydoc = new Y.Doc(); provider = new LiveblocksProvider(room as any, ydoc); const ytext = ydoc.getText("codemirror"); const undoManager = new Y.UndoManager(ytext); setYUndoManager(undoManager);
// Set up CodeMirror and extensions const state = EditorState.create({ doc: ytext.toString(), extensions: [ basicSetup, javascript(), yCollab(ytext, provider.awareness, { undoManager }), ], });
// Attach CodeMirror to element view = new EditorView({ state, parent: element, });
return () => { ydoc?.destroy(); provider?.destroy(); view?.destroy(); }; }, [element, room, userInfo]);
return ( <div className={styles.container}> <div className={styles.editorContainer} ref={ref}></div> </div> );}

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

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 code editor, we can get the userInfo for the current user with useSelf, and attach it Yjs awareness. After adding the following, you should see live cursors:

Cursors.tsx
import { useRoom, useSelf } from "@/liveblocks.config";// ...
// Collaborative code editor with undo/redo, live cursors, and live avatarsexport function CollaborativeEditor() { const room = useRoom(); const [element, setElement] = useState<HTMLElement>(); const [yUndoManager, setYUndoManager] = useState<Y.UndoManager>();
// Get user info from Liveblocks authentication endpoint const userInfo = useSelf((me) => me.info);
const ref = useCallback((node: HTMLElement | null) => { if (!node) return; setElement(node); }, []);
// Set up Liveblocks Yjs provider and attach CodeMirror editor useEffect(() => { let provider: TypedLiveblocksProvider; let ydoc: Y.Doc; let view: EditorView;
if (!element || !room || !userInfo) { return; }
// Create Yjs provider and document ydoc = new Y.Doc(); provider = new LiveblocksProvider(room as any, ydoc); const ytext = ydoc.getText("codemirror"); const undoManager = new Y.UndoManager(ytext); setYUndoManager(undoManager);
// Attach user info to Yjs provider.awareness.setLocalStateField("user", { name: userInfo.name, color: userInfo.color, colorLight: userInfo.color + "80", // 6-digit hex code at 50% opacity });
// Set up CodeMirror and extensions const state = EditorState.create({ doc: ytext.toString(), extensions: [ basicSetup, javascript(), yCollab(ytext, provider.awareness, { undoManager }), ], });
// Attach CodeMirror to element view = new EditorView({ state, parent: element, });
return () => { ydoc?.destroy(); provider?.destroy(); view?.destroy(); }; }, [element, room, userInfo]);
return ( <div className={styles.container}> <div className={styles.editorContainer} ref={ref}></div> </div> );}

We can style these cursors by placing CSS in a global CSS file.

Add a toolbar

From this point onwards, you can build your CodeMirror app as normal! For example, should you wish to add a basic undo/redo toolbar to your app:

Toolbar.tsx
import * as Y from "yjs";import styles from "./Toolbar.module.css";
type Props = { yUndoManager: Y.UndoManager;};
export function Toolbar({ yUndoManager }: Props) { return ( <div className={styles.toolbar}> <button className={styles.button} onClick={() => yUndoManager.undo()}> Undo </button> <button className={styles.button} onClick={() => yUndoManager.redo()}> Redo </button> </div> );}

Add some matching styles:

You can then import this into your editor to enable basic CodeMirror features:

Editor.tsx
import { Toolbar } from "@/components/Toolbar";// ...
export function CollaborativeEditor() { // ...
return ( <div className={styles.container}> <div className={styles.editorHeader}> <div> {yUndoManager ? <Toolbar yUndoManager={yUndoManager} /> : null} </div> </div> <div className={styles.editorContainer} ref={ref}></div> </div> );}

Create live avatars with Liveblocks hooks

Along with building out your code 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 to your editor to see it in action:

Editor.tsx
import { Avatars } from "@/components/Avatars";// ...
export function CollaborativeEditor() { // ...
return ( <div className={styles.container}> <div className={styles.editorHeader}> <div> {yUndoManager ? <Toolbar yUndoManager={yUndoManager} /> : null} </div> <Avatars /> </div> <div className={styles.editorContainer} ref={ref}></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 features! On GitHub we have a working example of this multiplayer code editor.