***Backend Setup & Structure (Implementation Plan)*******************
- npm init -y
- npm install express mongoose jsonwebtoken bcryptjs cors dotenv
- Folder Structure
- setup .env
Files Uses**
A. app.js
This file will: -Initialize express -Load middleware (JSON, CORS) -Load routes (/api/auth, /api/documents) -Connect global error handler
B. server.js
This file is the entrypoint. It will: -Import app.js -Start HTTP server -Later: attach Socket.io to HTTP server -Listen on PORT -This separation allows Socket.io to be added cleanly in Step 4.
C. config/db.js
This file will: -Use mongoose.connect() -Log DB connection success -Handle DB connection errors
D. models/User.js
User fields: -name -email -passwordHash -timestamps -User pre-save hooks & methods: -Hash password -Compare password
E. models/Document.js
Document fields: -title -content (Quill Delta JSON) -owner (userId) -collaborators: [] -timestamps
Indexes: -owner + updatedAt
F. controllers/auth.controller.js
Contains 2 functions: -register -Check if email exists -Hash password -Save user -Return JWT -LOGIN -Verify user email -Compare password -Return JWT
G. controllers/document.controller.js
Functions: -createDocument -getDocuments (user documents) -getDocumentById -updateDocument (title or content) -deleteDocument -None of these handle real-time — only database state.
H. routes/auth.routes.js Routes: -POST /register -POST /login
I. routes/document.routes.js Routes: -Protected routes -Apply auth middleware
Handle: -POST / -GET / -GET /:id -PUT /:id -DELETE /:id
J. middleware/auth.middleware.js This will: -Read Authorization: Bearer -Verify token -Attach user info -Throw 401 if invalid
K. middleware/error.middleware.js This will: -Catch thrown errors -Return uniform JSON:
L. utils/generateToken.js Function: -Takes userId -Returns signed JWT token
M. services/document.service.js (optional but clean) Handles: -Business logic -Fetching documents -Checking permissions -Updating content
Cleaner controllers → better structure.
End*****************************************
Code****
- App.Js
- Server.js
- config/db.js
- models/User.js
- models/Document.js
- utils/generateToken.js
- middleware/auth.middleware.js
- middleware/error.middleware.js
- controllers/auth.controller.js
- controllers/document.controller.js
- routes/auth.routes.js
- routes/document.routes.js ( Here we protect the routes using router.use(auth) )
---------------------------------------------End---------------------------------
IMPORTANT
CommonJS - exports.updateDocument = ( require() is used to import - Express, Node.js default) ES Modules (ESM) - export const updateDocument ( import is used to import - React, Next.js, modern Node )
**********Real Time Collaboration
HIGH LEVEL PLAN
- Attach Socket.io to your existing HTTP server (same server used by Express).
- Authorize every socket connection with the JWT (same secret used by REST).
- Let clients join a document room (a Socket.io room keyed by documentId).
- When a client emits an edit delta, broadcast it to other clients in the same room.
- Keep a server-side (in-memory) latest snapshot for each active document and debounce saves to MongoDB.
- Broadcast cursor positions and presence events.
- Handle disconnects, reconnection, and simple conflict-safety considerations.
Execution
- create a xyz.socket.js and use it in STEP 2.
- Attach Socket.io to the HTTP server
- Configure xyz.socket.js