Author avatar

Shannon Duncan

Building a Realtime Collaborative Editor with RethinkDB

Shannon Duncan

  • Jan 10, 2019
  • 22 Min read
  • Jan 10, 2019
  • 22 Min read

What is ReThinkDB?

RethinkDB is a new take on the typical database. It pushes changed data to your app in realtime, which makes building realtime applications less stressful. Instead of polling for data, you can wait for the data to change. Once the data changes, RethinkDB notifies you, allowing you to make changes as needed. It is open source, it scales very well, and it is just plain cool.


Ok, So how do we build this?

We are going to use a handful of technologies to help us build this app. I want to keep it small to demonstrate what it is doing well. You will need the following:

  • Node.js
    • This allows us to run JavaScript on the back-end and much, much more.
  • Express Framework
    • This framework allows us to serve the static files and assets, as well as build a small API to retrieve data.
  • Socket.IO
    • With Socket.IO, we can send realtime data to all connected clients.
  • RethinkDB
    • The core of our document storage and retrieval.
  • CodeMirror
    • This JavaScript library builds a fully-featured code editor with little work.
  • jQuery
    • The ever-popular JavaScript library that makes things "easier." We are going to be using jQuery's AJAX (Asynchronous JavaScript and XML).
  • Bower
    • An awesome package manager for front-end development.

Installing RethinkDB

To install RethinkDB just visit their site, find the package matching your operating system, and follow the instructions. I am using Ubuntu on my dev server, so here is the script I'll run in bash to install RethinkDB

1source /etc/lsb-release && echo "deb $DISTRIB_CODENAME main" | sudo tee /etc/apt/sources.list.d/rethinkdb.list
2wget -qO- | sudo apt-key add -
3sudo apt-get update
4sudo apt-get install rethinkdb

After it is installed, you can run RethinkDB with a simple command rethinkdb. However because I want to free up the 8080 port, I am going to run RethinkDB without the admin interface... rethinkdb --no-http-admin.

RethinkDB should be up and running on your system now.

Setting Up Node.js

I already have NodeJS setup on all my dev systems automatically. However, to install it on Ubuntu, just run the following script in the console.

1curl -sL | sudo -E bash -
2sudo apt-get install -y nodejs

Once installed, you can cd to a folder you wish to store your project in.

Setup NodeJS Package

Run the NPM Init command and follow the on-screen prompts. This will set up your Node.js package.

Setup RethinkDB Node Package

Install the RethinkDB adapter with the command npm install --save rethinkdb.

Setup Express Node Package

Install the Express package with the command npm install --save express.

Setup Socket.IO Node Package

Install the Socket.IO package with the command npm install --save

Setting Up Bower

Install Bower using the following command npm install -g bower. This will install Bower globally, so you can use it in future projects as well.

Once Bower is installed, you can initialize it with bower init. Follow the on-screen prompts. If you've already set up your NPM Init, then you should have all your prompts pre-filled from the npm package info.

After you have initialized Bower, it is time to install our front-end dependencies.

Setup jQuery

Install jQuery with the following command: bower install --save jquery

Setup Codemirror

Install Codemirror with the following command: bower install --save codemirror

Setting up your HTML page

By now, you're ready to use the technologies that we have installed. First, we need to create the two files that we will need. In the folder of your project, run the console commands touch index.html and touch index.js to create two blank files.

In the HTML, you want to put the following Code:

1<!doctype html>
3  <head>
4    <title>Collaborative Editor</title>
5  </head>
6  <body>
7    <textarea id="editor"></textarea>
9    <script src="/bower_components/codemirror/lib/codemirror.js"></script>
10    <link rel="stylesheet" href="/bower_components/codemirror/lib/codemirror.css">
11    <script src="/bower_components/codemirror/mode/javascript/javascript.js"></script>
12    <script src="/"></script>
13    <script src="/bower_components/jquery/dist/jquery.min.js"></script>
15    <script>
16        var myCodeMirror = CodeMirror.fromTextArea(document.getElementById("editor"), {
17            lineNumbers: true,
18            mode: "javascript"
19        });
20    </script>
21  </body>

The code block above is going to be the basis for the editor's HTML page. In the block, we create a text area with an ID of the editor that we can refer to later. Below this, we include all of the javascript files that we want to use. These include files for CodeMirror, Socket.IO (which will be served by Socket.IO itself), and jQuery. We then initialize the CodeMirror editor, with which the user will interact.

Next, open up index.js, and input the following code:

1var r = require("rethinkdb");
2var express = require("express");
3var app = require("express")();
4var http = require("http").Server(app);
5var io = require("")(http);
7// Serve HTML
8app.get("/", function(req, res) {
9  res.sendFile(__dirname + "/index.html");
12app.use("/bower_components", express.static("bower_components"));
14// Setup Express Listener
15http.listen(8080, "", function() {
16  console.log("listening on:");

We start off by importing all of the packages that we installed earlier. Then we set up two routes using Express. The first route serves our index.html page, and the second route serves our bower_components folder. As a result, the HTML page can access the bower folder. If you were to run node index.js and navigate to http://localhost:8080, then you should see an HTML page with the CodeMirror editor. If you edit it, then the text on the page changes.


Now let's work with Socket.IO.

Add the following code above the line that starts with // Serve HTML in index.js.

1io.on("connection", function(socket) {
2  console.log("a user connected");
3  socket.on("disconnect", function() {
4    console.log("user disconnected");
5  });

Add the following code above the </script> tag in index.html.

1var socket = io();

The first block tells the server what to do on a Socket connection. In this case, when someone connects, we are going to display to the node console a user connected. The opposite will occur for a disconnect; we will display user disconnected.

Go ahead and run node index.js, and navigate to your url http://localhost:8080. When you do so you should see the messages pop up in your console.


Now I know when I create this app that I want to be able to separate editors into different rooms. Allowing for multiple documents to be edited and shared on a single URL. To do this, I need to add the query parameter to my URL and build a way to get it. Add the following code to your javascript section in index.html

1function getParameterByName(name, url) {
2  if (!url) url = window.location.href;
3  name = name.replace(/[\[\]]/g, "\\$&");
4  var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
5    results = regex.exec(url);
6  if (!results) return null;
7  if (!results[2]) return "";
8  return decodeURIComponent(results[2].replace(/\+/g, " "));
10var room = getParameterByName("room");
11var user = getParameterByName("user");

The first part is a function that parses out query parameters from the URL bar based on the given name. The second part stores a room and a user. Doing this, we need to format the URL like so: http://localhost:8080/?room=1&user=username.

This will pass 1 as the room name and username as the user.

Application-specific RethinkDB setup

Next, we are going to set up the RethinkDB databases. Place the following code above your Socket section.

1r.connect({ host: "localhost", port: 28015 }, function(err, conn) {
2  if (err) throw err;
3  r
4    .db("test")
5    .tableList()
6    .run(conn, function(err, response) {
7      if (response.indexOf("edit") > -1) {
8        // do nothing it is created...
9        console.log("Table exists, skipping create...");
10        console.log("Tables - " + response);
11      } else {
12        // create table...
13        console.log("Table does not exist. Creating");
14        r
15          .db("test")
16          .tableCreate("edit")
17          .run(conn);
18      }
19    });

When you install RethinkDB, it automatically sets up a test database. We are going to use that for our project. (feel free to try and modify your code to add a new database for you to use, if you want).

The first part of this code block connects us to RethinkDB. Then anything we want to do with the database needs to happen within that connection block. Next we call a .tableList() on the database. We want to see if our edit table is already created; if it is, then we are just going to list the current tables in the database. If the table doesn't exist, then we are going to create it. It is a simple way to create the database on the first run, and skip that code every run after that. Otherwise we would get an error that the table already exists every time we tried to created it.

Most of the stuff we are going to be doing with data is going to require RethinkDB, so patch up the RethinkDB and Socket.IO sections to look like this:

1r.connect({ host: "localhost", port: 28015 }, function(err, conn) {
2  if (err) throw err;
3  r
4    .db("test")
5    .tableList()
6    .run(conn, function(err, response) {
7      if (response.indexOf("edit") > -1) {
8        // do nothing it is created...
9        console.log("Table exists, skipping create...");
10        console.log("Tables - " + response);
11      } else {
12        // create table...
13        console.log("Table does not exist. Creating");
14        r
15          .db("test")
16          .tableCreate("edit")
17          .run(conn);
18      }
19    });
21  // Socket Stuff
22  io.on("connection", function(socket) {
23    console.log("a user connected");
24    socket.on("disconnect", function() {
25      console.log("user disconnected");
26    });
27  });

This means that anything we do in the Socket block will have access to the connection of the RethinkDB data.

Moving onto the index.html file, let's add a new section of code:

1myCodeMirror.on("keyup", function() {
2  var msg = {
3    id: room,
4    user: user,
5    value: myCodeMirror.getValue()
6  };
7  socket.emit("document-update", msg);

In the index.js file, add the following code to your socket block.

1socket.on("document-update", function(msg) {
2  console.log(msg);
3  r
4    .table("edit")
5    .insert(
6      { id:, value: msg.value, user: msg.user },
7      { conflict: "update" }
8    )
9    .run(conn, function(err, res) {
10      if (err) throw err;
11      //console.log(JSON.stringify(res, null, 2));
12    });

The first set of code makes it so that every time a keypress goes up on the CodeMirror editor, we will do something. In this case, we are going to send a Socket edit labeled document-update with the value of the editor's contents.

In the second set of code, we are going to receive that socket message and store it into the RethinkDB table. Notice that it is an insertion and that I have a piece of code that looks like {conflict: "update"}. This allows me to insert data when it comes in. If the data is new, then the code will insert a new record into RethinkDB. However, if the incoming data matches a pre-existing room ID in the RethinkDB database, then we will update that record instead of inserting a new one.

But if you were to run this and type in the CodeMirror editor, then you wouldn't see anything happening at all. Let's fix that by adding the following code:

Add the following to index.js below the socket item we just did within the socket block:

2  .table("edit")
3  .changes()
4  .run(conn, function(err, cursor) {
5    if (err) throw err;
6    cursor.each(function(err, row) {
7      if (err) throw err;
8      io.emit("doc", row);
9    });
10  });

Add the following to index.html in your javascript section:

1socket.on("doc", function(msg) {
2  if ( === room && msg.new_val.user != user) {
3    var current_pos = myCodeMirror.getCursor();
4    myCodeMirror.getDoc().setValue(msg.new_val.value);
5    myCodeMirror.setCursor(current_pos);
6  }

The first block of code works the magic that is RethinkDB. We are using their changes function to watch a table of data. Any time a row of data changes, the database will inform us. When it does inform us of the change, we will send that document out through the Socket to all connected clients. This will happen in realtime as new data is pushed to the server.

The second block of code receives the data on the doc socket and checks to make sure it is intended for this client. If the data is for the current room and it wasn't submitted by the current user, then we want it.

The reason we don't want data submitted by the current user is because it can cause a typing glitch. As data is sent to the server, it is sent back to us. And when we retrieve it we are storing it into the codemirror editor. If we were the ones that sent it, we may have already typed a new letter before we recieved the update. This would cause our typed letter to disappear. By checking that the data wasn't sent by the current user, then we can avoid this issue completely.

Next let's add a few more details. Add the following code to index.js It needs to be added within the RethinkDB connection block:

1app.get("/getData/:id", function(req, res, next) {
2  r
3    .table("edit")
4    .get(
5    .run(conn, function(err, result) {
6      if (err) throw err;
7      res.send(result);
8      //return next(result);
9    });

Add the following the the javascript section of your index.html:

2  url: "/getData/" + room,
3  success: function(result, status, xhr) {
4    myCodeMirror.setValue(result.value);
5    console.log(result);
6  }

The first block of code here sets up an API for our client side to load in data for the current room. It passes an ID parameter through the URL and then uses that to query RethinkDB and return the data.

The second block of code sets up the loading call from the client side. It stores the result of the call into the CodeMirror editor. Now when we join a room, if there is already data in the editor, we will retrieve it and show it. Otherwise it will be empty and we can start the new room by typing in the editor.

Now let us spruce the page up a little bit and add some CSS.

Add the following CSS to your index.html page:

2body {
3  height: 100%;
4  width: 100%;
5  background-color: #333;
6  font-family: arial;
8#editor-wrapper {
9  width: 70%;
10  margin-left: auto;
11  margin-right: auto;
12  margin-top: 3em;
14#username {
15  color: #f3f3f3;
17.cuser {
18  color: #999;
20.ouser {
21  color: #fff;

Replace <textarea id="editor"></textarea> in index.html with the following code:

1<div id="editor-wrapper">
2    <span class="cuser">Current User: </span><span id="username"></span><br>
3    <textarea id="editor"></textarea>

Add the following javascript to the script section of index.html:

1document.getElementById("username").innerHTML = user;

This will spruce up the page a bit, and add the username you specified to the page. By now you should have a working application, and it should look something like this.


And here is a recorded demo of using the editor...


If your application is breaking, and you do not know why, then here is exactly what your two files should be looking like by now...

Here is index.js:

1var r = require("rethinkdb");
2var express = require("express");
3var app = require("express")();
4var http = require("http").Server(app);
5var io = require("")(http);
7// Setup Database
8r.connect({ host: "localhost", port: 28015 }, function(err, conn) {
9  if (err) throw err;
10  r
11    .db("test")
12    .tableList()
13    .run(conn, function(err, response) {
14      if (response.indexOf("edit") > -1) {
15        // do nothing it is created...
16        console.log("Table exists, skipping create...");
17        console.log("Tables - " + response);
18      } else {
19        // create table...
20        console.log("Table does not exist. Creating");
21        r
22          .db("test")
23          .tableCreate("edit")
24          .run(conn);
25      }
26    });
28  // Socket Stuff
29  io.on("connection", function(socket) {
30    console.log("a user connected");
31    socket.on("disconnect", function() {
32      console.log("user disconnected");
33    });
34    socket.on("document-update", function(msg) {
35      console.log(msg);
36      r
37        .table("edit")
38        .insert(
39          { id:, value: msg.value, user: msg.user },
40          { conflict: "update" }
41        )
42        .run(conn, function(err, res) {
43          if (err) throw err;
44          //console.log(JSON.stringify(res, null, 2));
45        });
46    });
47    r
48      .table("edit")
49      .changes()
50      .run(conn, function(err, cursor) {
51        if (err) throw err;
52        cursor.each(function(err, row) {
53          if (err) throw err;
54          io.emit("doc", row);
55        });
56      });
57  });
59  app.get("/getData/:id", function(req, res, next) {
60    r
61      .table("edit")
62      .get(
63      .run(conn, function(err, result) {
64        if (err) throw err;
65        res.send(result);
66        //return next(result);
67      });
68  });
71// Serve HTML
72app.get("/", function(req, res) {
73  res.sendFile(__dirname + "/index.html");
76app.use("/bower_components", express.static("bower_components"));
78// Setup Express Listener
79http.listen(process.env.PORT, process.env.IP, function() {
80  console.log("listening on:  " + process.env.IP + ":" + process.env.PORT);

Here is index.html:

1<!doctype html>
3  <head>
4    <title>Collaborative Editor</title>
5    <style>
6      html, body {
7          height: 100%;
8          width: 100%;
9          background-color:#333;
10          font-family: arial;
11      }
12      #editor-wrapper {
13          width: 70%;
14          margin-left:auto;
15          margin-right:auto;
16          margin-top:3em;
17      }
18      #username {
19          color: #f3f3f3;
20      }
21      .cuser {
22          color: #999;
23      }
24      .ouser {
25          color: #fff;
26      }
27    </style>
28  </head>
29  <body>
30      <div id="editor-wrapper">
31        <span class="cuser">Current User: </span><span id="username"></span><br>
32        <textarea id="editor"></textarea>
33      </div>
34    <script src="/bower_components/codemirror/lib/codemirror.js"></script>
35    <link rel="stylesheet" href="/bower_components/codemirror/lib/codemirror.css">
36    <script src="/bower_components/codemirror/mode/javascript/javascript.js"></script>
37    <script src="/"></script>
38    <script src="/bower_components/jquery/dist/jquery.min.js"></script>
39    <script>
41        function getParameterByName(name, url) {
42            if (!url) url = window.location.href;
43            name = name.replace(/[\[\]]/g, "\\$&");
44            var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
45                results = regex.exec(url);
46            if (!results) return null;
47            if (!results[2]) return '';
48            return decodeURIComponent(results[2].replace(/\+/g, " "));
49        }
50        var room = getParameterByName('room');
51        var user = getParameterByName('user');
52        document.getElementById("username").innerHTML = user;
54        var myCodeMirror = CodeMirror.fromTextArea(document.getElementById("editor"), {
55            lineNumbers: true,
56            mode: "javascript"
57        });
59        var socket = io();
61        $.ajax({
62            url: '/getData/' + room,
63            success: function(result, status, xhr) {
64                myCodeMirror.setValue(result.value);
65                console.log(result);
66            }
67        });
69        myCodeMirror.on('keyup', function () {
70            var msg = {
71                id: room,
72                user: user,
73                value: myCodeMirror.getValue()
74            }
75            socket.emit('document-update',msg);
76        });
78        socket.on('doc', function(msg){
79            if( === room && msg.new_val.user != user) {
80                var current_pos = myCodeMirror.getCursor();
81                myCodeMirror.getDoc().setValue(msg.new_val.value);
82                myCodeMirror.setCursor(current_pos);
83            }
84        });
86    </script>
87  </body>


Using this method, you can create a very simple editor with realtime collaboration features. However, this is just the beginning! To make the editor even better, you can implement a login system, chats, data validation, and much, much more.

If you are interested in designing a larger collaborative editor, make sure that you understand Operational Transformation. This is what large-scale collaborative editors use to make sure that every edit you make doesn't overwrite something else that someone is doing. It also handles collision of data, and can help relay information correctly with more than just text data.

Stay tuned, as I plan on writing an article about Operational Transformation. I'll discuss all of the aspects of it, as well as how to add it into your current projects.

I hope this tutorial piques your interest, and you can go off and make amazing apps with RethinkDB.

Shannon Duncan is an Author at Unrestricted Coding. He mentors and teaches people of all ages how to code and enjoy the art of programming. Find him on Twitter, Linkedin, and GitHub.