Real-Time Code Collaboration Platform (Node.
js
& MySQL)
A real-time code collaboration platform is a web-based tool where multiple developers can edit the
same code together simultaneously, with everyone seeing updates live. This is analogous to Google
Docs but for programming code. Tools like Replit already offer “real-time coding with teammates” by
streaming code edits instantly between browsers 1 . Our goal is to build a similar system from scratch
using Node.js (server) and MySQL (database), supporting features for programmers to collaborate on
code in real time.
Real-time collaboration relies on low-latency, bidirectional communication between clients and server.
In practice, we’ll use Socket.IO, a library that “enables real-time, bidirectional and event-based
communication between the browser and the server” 2 . Socket.IO will let our Node.js backend
broadcast code changes and chat messages to all connected clients immediately. For example, when
one user types, the new code can be emitted via WebSockets and applied in everyone’s browser. (Under
the hood, Socket.IO uses the WebSocket protocol, providing a full-duplex low-latency channel between
client and server 3 .)
Core Features and Functionality
At minimum, our platform will include:
• Collaborative Code Editor. A web-based code editor (using a library like Ace or CodeMirror) that
multiple users can edit together. All participants’ cursors and keystrokes are synchronized in real
time, so everyone sees the same content. Real-time editing “propagates changes to other
participants … as soon as they arrive” 4 . We’ll use code editor libraries (e.g. Ace or CodeMirror)
embedded in the HTML, and hook them to Socket.IO events. For example, Ace is “an embeddable
code editor” with syntax highlighting and many language modes 5 , ideal for rich coding
experience.
• User Sessions / Rooms. Programmers can create or join a “session” or “room” for a joint coding
session. Each session has a unique ID (often via a shareable URL) so users can enter the same
workspace. The server maintains these sessions (e.g. in a sessions MySQL table) and uses
Socket.IO rooms so that events (code edits, chat) in one session go only to participants of that
session.
• Real-Time Chat. A text chat sidebar integrated with the editor lets collaborators discuss code.
When a user sends a chat message, the client emits it via Socket.IO and the server broadcasts it
to others. This pairs natural discussion with coding. (For inspiration, tutorials often implement a
real-time chat with Node.js and MySQL by emitting Socket.IO events on each message and
inserting them into a database 6 .)
• Syntax Highlighting & Editor Features. The code editor will provide syntax highlighting, line
numbers, and other niceties. For instance, Ace supports 110+ languages and features like
1
multiple cursors and themes 5 7 . We’ll configure the editor mode (e.g. JavaScript, Python)
based on user choice.
• Persistence (Saving/Loading). At least the final code or snapshots should be saved. For
example, when a session ends or periodically, the current code can be saved to MySQL. One
table (e.g. code_snapshots ) might store the latest code text per session. Alternatively, a
lightweight real-time DB (or just in-memory) can hold edits while broadcasting, with MySQL used
for final persistence.
Beyond the basics, we can add advanced features:
• Voice/Video Chat. Using WebRTC, peers can also share voice (and video) during the session.
WebRTC is an HTML5 spec for peer-to-peer audio/video (and data) communication 8 . In
practice, we’d use Node.js + Socket.IO as a signaling server, and have clients use the WebRTC API
to establish direct media streams 9 . For example, a demo stacks Express, Socket.IO, and
WebRTC so that “the app allows us to stream audio and video to the connected device” 9 . This
is optional but can make collaboration richer.
• File Sharing. Users could upload/share files (e.g. images, data files). We could implement an
Express file-upload endpoint (using a middleware like multer) and store file metadata in MySQL.
Then collaborators can download shared files through the UI.
• GitHub Integration. Allow linking to GitHub: users can log in via GitHub OAuth, browse
repositories, and pull in code. We’d use GitHub’s rich REST API (for which GitHub provides “loads
of utility-rich APIs… for everything” 10 ) to fetch repo contents or commit changes back. For
example, after authenticating, our app could list a user’s repos, let them select a project, and
load files into the editor. Commits and pull requests could also be made via GitHub API.
• Additional Tools. We might integrate an in-app terminal (shared via WebSockets), code
execution (run the code on server and show output), or AI-assisted coding. But these are beyond
minimal scope; voice, file, and GitHub cover the main extras requested.
System Architecture
The system consists of: - Frontend (Browser): A web page with the code editor (Ace/CodeMirror), chat
panel, and UI buttons. The editor raises events on edits. A Socket.IO client runs in the browser to send/
receive real-time events. - Backend (Node.js + Express): An Express server serves the web page and
static assets. It also hosts the Socket.IO server. When clients connect or send messages, the Socket.IO
server handles these events. - Database (MySQL): A MySQL database stores user accounts (if any),
session metadata, chat logs, and saved code. The Node server connects to MySQL (using a library like
mysql2 ) to read/write data.
Communication flow: 1. A user opens the app (served by Express). The client JavaScript establishes a
Socket.IO connection to the Node server. 2. The user joins or creates a session (room). The client emits a
“join room” event (with a session ID) to the server. 3. The server adds the client’s socket to a Socket.IO
room for that session, and may fetch any saved code from MySQL to send to the new client. 4. As the
user types or edits, the editor triggers an event. The client-side JS emits this event (e.g. “code change”
with diff or full text) to the server. 5. The Node server receives the edit event and broadcasts it to all
other sockets in the same room (so their editors update in real-time). Optionally, the server can also
save the change (e.g. append to DB or a file). 6. If the user sends a chat message, similarly the client
2
emits it and the server broadcasts to the room (and logs it in DB). 7. All connected clients update their
UI accordingly (apply code changes, display new chat messages).
(For example, in one Node.js example, on receiving a 'new note' event the server does
db.query('INSERT INTO notes ...') to save it and also broadcasts to all sockets 6 . We’ll do
analogous logic for code edits and chat messages.)
Technical Stack and Setup
1. Node.js & Express: Install Node.js (v18+ is fine). Initialize your project:
mkdir CodeCollab && cd CodeCollab
npm init -y
npm install express socket.io mysql2
2. Express will serve our static files (HTML/CSS/JS) and handle HTTP (e.g. login routes).
3. Socket.IO enables real-time websockets. (Socket.IO is a JavaScript library for real-time
applications 2 .)
4. mysql2 is a MySQL client for Node.js 11 . We’ll use it to run queries.
5. MySQL Database: Install and run MySQL Server. Create a database (e.g. codecollab ). Then
design tables, for example:
6. users (id, username, password_hash, created_at).
7. sessions (id, name, owner_id, created_at).
8. session_users (session_id, user_id) – which users are in which session.
9. messages (id, session_id, user_id, text, timestamp).
10. code_snapshots (id, session_id, content, timestamp).
11. (Optionally) files (id, session_id, filename, url).
In Node we connect with something like:
const mysql = require('mysql2');
const db = mysql.createConnection({
host: 'localhost', user: 'root', database: 'codecollab'
});
db.connect(err => { if (err) console.error(err); });
(This follows the example of setting up MySQL in Node 12 .)
1. Server (server.js): In your Express/Socket.IO setup:
const express = require('express');
const http = require('http');
const { Server } = require('socket.io');
const mysql = require('mysql2');
3
const app = express();
const server = http.createServer(app);
const io = new Server(server);
// Serve static files from 'public' directory
app.use(express.static('public'));
// (Optional) Routes for login, GitHub OAuth, etc.
// Socket.IO logic:
io.on('connection', (socket) => {
console.log('Client connected');
socket.on('joinSession', (sessionId) => {
socket.join(sessionId);
// Load existing code for session from DB and emit to this socket
db.query('SELECT content FROM code_snapshots WHERE session_id=?
ORDER BY timestamp DESC LIMIT 1', [sessionId], (err, results) => {
if (results.length) {
socket.emit('loadCode', results[0].content);
}
});
});
socket.on('codeEdit', (data) => {
// data = { sessionId, content }
socket.to(data.sessionId).emit('updateCode', data.content);
// Optionally, save to DB or file here.
db.query('INSERT INTO code_snapshots (session_id, content) VALUES
(?, ?)', [data.sessionId, data.content]);
});
socket.on('chatMessage', (data) => {
// data = { sessionId, userId, message }
io.to(data.sessionId).emit('newMessage', data);
db.query('INSERT INTO messages (session_id, user_id, text) VALUES
(?, ?, ?)', [data.sessionId, data.userId, data.message]);
});
});
server.listen(3000, () => console.log('Server listening on port 3000'));
This shows the core loop: on a new client, they join a room ( sessionId ); when a code edit or
chat comes in, broadcast it to that room and insert into MySQL 6 . The exact schema and
events can be adjusted, but this pattern (listening on Socket.IO and using db.query to store) is
standard 6 .
2. Client (public/index.html + JS): Create an HTML page with the code editor and chat. For
example:
4
<!-- public/index.html -->
<!DOCTYPE html><html><head>
<title>CodeCollab</title>
<!-- Include Ace from CDN -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.9.6/
ace.js"></script>
<!-- Include Socket.IO client -->
<script src="/socket.io/socket.io.js"></script>
</head><body>
<h1>Real-Time Code Collaboration</h1>
<div id="editor" style="height:400px; width:80%;"></div>
<textarea id="chat" rows="10" cols="80" readonly></textarea><br>
<input id="msgInput" type="text"><button id="sendBtn">Send</button>
<script>
const socket = io();
const sessionId = prompt("Enter session ID or create new:");
socket.emit('joinSession', sessionId);
// Set up Ace editor
const editor = ace.edit("editor");
editor.session.setMode("ace/mode/javascript");
editor.setTheme("ace/theme/monokai");
// When editor content changes, emit to server (with some
throttling)
editor.session.on('change', () => {
const code = editor.getValue();
socket.emit('codeEdit', { sessionId, content: code });
});
// Receive updates from others
socket.on('updateCode', (code) => {
// (In a real app, skip if the change came from this client to
avoid loops.)
editor.setValue(code, -1);
});
// Chat
document.getElementById('sendBtn').onclick = () => {
const text = document.getElementById('msgInput').value;
socket.emit('chatMessage', { sessionId, userId: 'User1', message:
text });
document.getElementById('msgInput').value = '';
};
socket.on('newMessage', (data) => {
const chatBox = document.getElementById('chat');
chatBox.value += (data.userId + ": " + data.message + "\n");
});
5
// Load initial code
socket.on('loadCode', (code) => {
editor.setValue(code, -1);
});
</script>
</body></html>
Here, we prompt for a session ID, join it, and wire up the editor’s change events to emit
codeEdit . When updateCode is received from the server, we update the editor. We also send
and display chat messages. This is a minimal example; in practice you’d handle loops (so a user’s
own edits aren’t broadcast back to them) and maybe send diffs instead of full code for
performance.
Detailed Build Steps
1. Initialize Project: Install Node and MySQL. Create a new directory, run npm init , and install
dependencies ( express , socket.io , mysql2 , and optionally dotenv for config, or
passport-github2 for GitHub auth).
2. Database Setup: In MySQL, create the database and tables. For example:
CREATE TABLE sessions (id VARCHAR(50) PRIMARY KEY, name VARCHAR(255),
owner_id INT, created_at DATETIME);
CREATE TABLE users (id INT AUTO_INCREMENT PRIMARY KEY, username
VARCHAR(100), password_hash VARCHAR(255));
CREATE TABLE session_users (session_id VARCHAR(50), user_id INT,
PRIMARY KEY(session_id,user_id));
CREATE TABLE messages (id INT AUTO_INCREMENT PRIMARY KEY, session_id
VARCHAR(50), user_id INT, text TEXT, timestamp DATETIME DEFAULT
CURRENT_TIMESTAMP);
CREATE TABLE code_snapshots (id INT AUTO_INCREMENT PRIMARY KEY,
session_id VARCHAR(50), content LONGTEXT, timestamp DATETIME DEFAULT
CURRENT_TIMESTAMP);
Adjust as needed. Use foreign keys if desired. This allows saving session details, chat, and code.
(Storing every keystroke to DB is too heavy; we usually send code to other clients immediately and
either save snapshots periodically or just save when the session ends.)
3. Server Code: As shown above, create server.js to set up Express and Socket.IO. Use
io.on('connection') to handle new clients. Within, handle custom events:
4. joinSession : use socket.join(sessionId) to isolate rooms.
5. codeEdit : broadcast to socket.to(sessionId) and save.
6. chatMessage : broadcast to io.to(sessionId) (everyone, including sender) and save.
7. Optionally handle user disconnects, track connected users (see [27†L86-L94] for user count
example). This matches patterns from Node-Socket.IO chats (the code from Mark Shust 6 is
similar to our new note logic).
6
8. Frontend Code: In public/index.html , include the code editor. In our example we used Ace
via CDN 5 . You could also use CodeMirror or the Monaco Editor (powers VS Code). Initialize the
editor (e.g. ace.edit("editor") ) and set its mode/theme. Then add JavaScript to connect
with const socket = io() (Socket.IO client library) and implement the event handling logic
as above.
9. Collaboration Logic: The key is broadcasting edits. You have choices:
10. Full-text approach: On every change (or at intervals), send the entire code text to server, which
sends it to others. Simple but can lag with large files. Safwan’s tutorial used a timed interval to
read from a file and broadcast 13 .
11. Delta/patch approach: Compute and send only edits (differences). This is more complex; it’s
how OT/CRDT systems work.
12. Operational Transform / CRDT: Libraries like ShareDB (OT) or Yjs (CRDT) can handle complex
merging of concurrent edits. For example, CodeMirror’s collab example uses OT on a central
server 14 . We could integrate such a library for robustness, but for a basic project, sending
whole document changes (perhaps throttled) is acceptable.
13. User Authentication (Optional): If you want logins, use Express routes and a library like
express-session or JWT for sessions. You could allow GitHub OAuth (using something like
passport-github2 ) so users log in with GitHub. This ties into GitHub integration: after OAuth,
you can call GitHub APIs (which “provide loads of utility-rich APIs” 10 ) to fetch the user’s
repositories or perform commits.
14. Additional Features:
15. Voice Chat: Use WebRTC for peer-to-peer audio. The general approach is to use Socket.IO to
signal WebRTC offers/answers between peers, then have them connect directly. (Tutorials on
WebRTC with Node often use socket.io for signaling 9 .) Clients call
navigator.getUserMedia({ audio: true }) and share the streams. This is a significant
addition, so it can be a “stretch goal.”
16. File Sharing: Add an Express POST endpoint (e.g. /upload ) using multer to accept file
uploads. Store uploaded files on the server or cloud storage, and keep metadata (filename,
owner, session) in MySQL. Clients can list/download these files as part of the session.
17. GitHub Integration: After OAuth login, use GitHub’s REST API to list repos ( GET /user/
repos ) and file contents ( GET /repos/{owner}/{repo}/contents/{path} ). You can let
the user pick a repo and branch, then fetch its code into the editor. To push changes, use
GitHub’s API to create or update files. The stateful.com tutorial notes that GitHub APIs cover
“almost every workflow” 10 , so you have full flexibility to integrate.
18. Testing Locally: You can run node server.js (or use nodemon for auto-restart). Open
http://localhost:3000 in multiple browser windows or devices, and test editing/typing. As
in the Microsoft example, if you type in one window you should see it reflected in the other
instantly 15 .
7
Deployment
Finally, host your app on a server so others can use it. Many platforms support Node.js:
• Render.com: Offers free Node deployments. It doesn’t offer a built-in MySQL, so you’d use an
external MySQL host (for example, a free service like freemysqlhosting.net) and configure its
credentials as environment variables 16 .
• Railway.app: Another free Node host. Railway easily lets you attach a MySQL instance (Railway’s
documentation says you can deploy a Node.js app and use a database like MySQL 17 ). You just
connect your Git repo, specify npm start , and add environment vars for DB.
• Fly.io: Can deploy via Docker or buildpacks. It’s more complex but has a free tier.
• Glitch.com: Quick and easy for prototyping: it lets you remix a Node project and has an in-
browser IDE. (Note Glitch’s free apps “go to sleep after 5 minutes of inactivity” and have storage
limits 18 , so it’s only for demos.)
• AWS / GCP / Azure: Using their free tiers, you could spin up a VM or use managed App Services.
But that’s more setup.
Deployment steps (example on Render): Push your code to GitHub. On Render’s dashboard, create a
new Web Service, connect your repo, and set build/start commands (e.g. npm install and npm
start ). Add environment variables for your MySQL host/user/password so the Node app can connect.
Deploy, and Render will give you a URL. Your app should now be accessible online. (On Railway, the
process is similar: connect GitHub, select Node project, and it will detect the build automatically 17 .)
Summary
Building a real-time code collaboration tool involves combining a web-based code editor with real-time
networking. The core components are: Node.js with Socket.IO for the backend, MySQL for
persistence, and a frontend code editor like Ace or CodeMirror. Key features include synchronized
editing, multi-user chat, and session management. Advanced extras can include WebRTC-based voice
chat and GitHub connectivity. By setting up an Express server, wiring Socket.IO events for “code change”
and “chat message”, and storing shared data in MySQL, you can create a platform where programmers
can work on code together live. The examples and tutorials referenced here (e.g. streaming code via
Socket.IO 19 6 , using Ace 5 ) provide concrete guidance on each part of the system.
Sources: Technical references were drawn from official docs and developer tutorials, including
explanations of collaborative editing 4 2 , examples of Node.js+Socket.IO+MySQL implementations
6 , and platform feature descriptions 20 21 used to inspire our feature set. These illustrate industry-
standard practices for building real-time apps. By following these guidelines step by step, you should be
able to implement and deploy a working real-time code collaboration platform from scratch.
8
1 20 Replit: Real-Time Coding in Your Browser | FatCat Remote
https://fatcatremote.com/it-glossary/replit
2 3 Introduction | Socket.IO
https://socket.io/docs/v3/
4 14 CodeMirror Collaborative Example
https://codemirror.net/examples/collab/
5 7 Ace - The High Performance Code Editor for the Web
https://ace.c9.io/
6 12 Creating a Node.js server/client with Socket.IO & MySQL | Mark Shust
https://markshust.com/2013/11/07/creating-nodejs-server-client-socket-io-mysql/
8 9 How to write a video chat app using WebRTC Node.js
https://tsh.io/blog/how-to-write-video-chat-app-using-webrtc-and-nodejs/
10 Using the GitHub API in Node.js: A Comprehensive Tutorial • Stateful
https://stateful.com/blog/github-api-nodejs
11 MySQL2 | Quickstart
https://sidorares.github.io/node-mysql2/docs
13 19 Real time editor with Node.js and Socket.io | by Hussain Safwan | Medium
https://safwan-du16.medium.com/real-time-editor-with-node-js-and-socket-io-78a57c194dc8
15 Build a real-time code-streaming app by using Socket.IO and host it on Azure | Microsoft Learn
https://learn.microsoft.com/en-us/azure/azure-web-pubsub/socketio-build-realtime-code-streaming-app
16 Deploy express app to Render with MySQL database | by FinalGirl321 | Medium
https://medium.com/@megan.m/now-that-heroku-isnt-free-anymore-we-are-all-looking-for-new-places-to-host-our-apps-
bf4b6738792b
17 18 Best Node JS free hosting services out there - DEV Community
https://dev.to/zipy/best-node-js-free-hosting-services-out-there-29kc
21 Exploring the Best Tools for Real-Time Code Collaboration - DEV Community
https://dev.to/surajondev/exploring-the-best-tools-for-code-collaboration-2755