Backend API for a real-time chat application built with Node.js, Express, MongoDB, and Socket.IO. It handles authentication, user profiles, private messaging, image uploads, and online user presence.
- JWT-based authentication with httpOnly cookies
- User signup, login, logout, and auth verification
- Profile picture upload with Multer + Cloudinary
- Private 1:1 messaging between users
- Message image uploads with Multer + Cloudinary
- Real-time delivery and online presence using Socket.IO
- MongoDB persistence with Mongoose models
- Node.js
- Express.js
- MongoDB
- Mongoose
- Socket.IO
- Cloudinary
- Multer
- bcryptjs
- JSON Web Token (JWT)
- cookie-parser
- cors
- dotenv
- nodemon
backend/
├── src/
│ ├── controllers/
│ ├── lib/
│ ├── middleware/
│ ├── models/
│ ├── routes/
│ ├── seeds/
│ └── index.js
├── package.json
└── README.md- Install dependencies
cd backend
npm install- Create a
.envfile in the backend root
PORT=5001
MONGO_URI=your_mongodb_connection_string
JWT_SECRET=your_jwt_secret
CLIENT_URL=http://localhost:5173
CLOUDINARY_CLOUD_NAME=your_cloud_name
CLOUDINARY_API_KEY=your_api_key
CLOUDINARY_API_SECRET=your_api_secret- Start the development server
npm run devPOST /api/auth/signup- Register a new userPOST /api/auth/login- Log in and receive auth cookiePOST /api/auth/logout- Clear auth cookieGET /api/auth/check- Get the currently authenticated userPUT /api/auth/update-profile- Update profile picture usingmultipart/form-data
GET /api/messages/users- Get all users except the logged-in userGET /api/messages/:id- Get conversation messages with a specific userPOST /api/messages/send/:id- Send a message to a user using JSON text ormultipart/form-datawith an image
Body:
{
"fullName": "John Doe",
"email": "john@example.com",
"password": "password123"
}Body:
{
"email": "john@example.com",
"password": "password123"
}- Content-Type:
multipart/form-data - Field name:
profilePic
- Content-Type:
multipart/form-data - Text field:
text - Image field:
image
Socket.IO is used for live chat updates and online presence.
- Connection query includes
userId
getOnlineUsers- Sends the list of currently connected user IDsnewMessage- Broadcasts a newly sent message to the receiver
protectRoute- Verifies JWT cookie and protects private routesupload.middleware.js- Handles image uploads with Multer memory storageerror.middleware.js- Central error handler for upload and server errors
emailfullNamepasswordprofilePic- timestamps
senderIdreceiverIdtextimage- timestamps
- Authenticated routes require cookies enabled on the client.
- Images are uploaded to Cloudinary; the database stores the returned secure URL.
- The server currently allows image uploads up to 5 MB through Multer.
- Make sure the frontend uses the same field names:
profilePicfor profile updates andimagefor chat attachments.
npm run dev- Start the backend in development mode with nodemon