Sign in

Get started with a CodeMirror code editor using Liveblocks and Next.js

Liveblocks is a realtime collaboration infrastructure for building performant collaborative experiences. Follow the following steps to start adding collaboration to your Next.js application using the APIs from the @liveblocks/codemirror package.

Quickstart

  1. Install Liveblocks and CodeMirror

    Every Liveblocks package should use the same version.

    Terminal
    npm install @liveblocks/client @liveblocks/react @liveblocks/codemirror codemirror
  2. Initialize the liveblocks.config.ts file

    We can use this file later to define types for our application.

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

    Add types for your CodeMirror document and presence:

    liveblocks.config.ts
    import type { LiveblocksCodemirrorSelection } from "@liveblocks/codemirror";import { LiveText } from "@liveblocks/client";
    declare global { interface Liveblocks { Presence: { selection: LiveblocksCodemirrorSelection | null; }; Storage: { document: LiveText; }; UserMeta: { id?: string; info?: { name?: string; color?: string; }; }; }}
    export {};
  3. Create a Liveblocks room

    Liveblocks uses the concept of rooms, separate virtual spaces where people collaborate, and to create a realtime experience, multiple users must be connected to the same room. When using Next.js’ /app router, we recommend creating your room in a Room.tsx file in the same directory as your current route.

    Store your editor document in Storage as LiveText, and set an initial presence shape for cursors.

    Set up a Liveblocks client with LiveblocksProvider, join a room with RoomProvider, and use ClientSideSuspense to add a loading spinner to your app.

    app/Room.tsx
    "use client";
    import { ReactNode } from "react";import { LiveText } from "@liveblocks/client";import { LiveblocksProvider, RoomProvider, ClientSideSuspense,} from "@liveblocks/react/suspense";
    export function Room({ children }: { children: ReactNode }) { return ( <LiveblocksProvider publicApiKey={""}> <RoomProvider id="my-room" initialPresence={{ selection: null }} initialStorage={{ document: new LiveText("Hello, world") }} > <ClientSideSuspense fallback={<div>Loading…</div>}> {children} </ClientSideSuspense> </RoomProvider> </LiveblocksProvider> );}
  4. Add the Liveblocks room to your page

    After creating your room file, import it into your page.tsx file and place your editor inside it.

    app/page.tsx
    import { Room } from "./Room";import { Editor } from "./Editor";
    export default function Page() { return ( <Room> <Editor /> </Room> );}
  5. Set up the collaborative CodeMirror editor

    Now that Liveblocks is set up, create a CodeMirror editor in Editor.tsx. Use createLiveblocksSyncPlugin to sync the document with Storage, and createLiveblocksPresencePlugin to show remote carets and selections.

    app/Editor.tsx
    "use client";
    import { useCallback, useEffect, useRef, useSyncExternalStore } from "react";import { EditorView } from "@codemirror/view";import { EditorState } from "@codemirror/state";import type { LiveText, Room } from "@liveblocks/client";import { createLiveblocksPresencePlugin, createLiveblocksSyncPlugin,} from "@liveblocks/codemirror";import { useRoom } from "@liveblocks/react/suspense";
    export function Editor() { const room = useRoom(); const root = useRoot(room);
    if (root == null) { return <div>Loading…</div>; }
    return <EditorInner text={root.get("document")} />;}
    function EditorInner({ text }: { text: LiveText }) { const room = useRoom(); const containerRef = useRef<HTMLDivElement>(null);
    useEffect(() => { if (containerRef.current === null) return;
    const view = new EditorView({ parent: containerRef.current, state: EditorState.create({ doc: text.toString(), extensions: [ createLiveblocksSyncPlugin(room, text), createLiveblocksPresencePlugin(room, text), ], }), });
    return () => { view.destroy(); }; }, [room, text]);
    return <div ref={containerRef} className="editor" />;}
    function useRoot(room: Room) { const subscribe = room.events.storageDidLoad.subscribeOnce; const getSnapshot = room.getStorageOrNull; const getServerSnapshot = useCallback(() => null, []); return useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);}
  6. Style remote carets and selections

    The presence plugin renders remote carets and selections using the .lb-remote-caret and .lb-remote-selection class names. Add styles for them in your CSS. This package does not ship a stylesheet.

    app/globals.css
    .editor {  height: 100vh;}
    .lb-remote-selection { position: absolute; background-color: color-mix(in srgb, var(--lb-remote-color) 25%, transparent); border-radius: 1px; pointer-events: none; box-sizing: border-box;}
    .lb-remote-caret { position: absolute; width: 0; border-left: 2px solid var(--lb-remote-color); pointer-events: none; box-sizing: border-box;}
    app/layout.tsx
    import "./globals.css";
  7. Next: authenticate and add your users

    Your editor is set up and working now, but each user is anonymous—the next step is to authenticate each user as they connect, and attach their name and color to remote carets.

    Set up authentication and add user information

What to read next

Congratulations! You now have set up the foundation for your collaborative CodeMirror editor inside your Next.js application.

If you prefer to use Yjs with CodeMirror, see the Yjs CodeMirror React quickstart.