A Node.js backend application built with Express and Socket.io, providing authentication and real-time chat functionality.
- Express.js - Web framework for Node.js
- Socket.io - Real-time bidirectional event-based communication
- TypeScript - Type safety and modern JavaScript features
- MongoDB/Database - Data persistence
- JWT - Authentication tokens
- Node.js (version 16 or higher)
- npm or yarn package manager
- MongoDB database (local or cloud)
- Clone the repository
git clone <repository-url>
cd <project-name>- Install dependencies
npm install
# or
yarn install- Create environment file
cp .env.example .envConfigure your environment variables in .env:
JWT_SECRET=<jwt_secret>
DB_URL=<mongodb_connection_string>- Start the development server
npm run dev
# or
yarn devThe server will start on http://localhost:5000 by default (no env provided)
src/
├── config/ # Configuration files
│ ├── db.js # Database connection setup
│ └── environment.js # Environment variables loader (centralized process.env)
├── controllers/ # Route handlers and business logic
│ ├── authController.js # Authentication logic (login, register, etc.)
│ ├── chatController.js # Chat-related API endpoints
│ └── errorHandler.js # Global error handling middleware
├── middlewares/ # Custom middleware functions
│ └── catchAsync.js # Async error handling wrapper
├── models/ # Database models/schemas
│ └── userModel.ts # User data model
├── routes/ # API route definitions
│ ├── authRoutes.js # Authentication endpoints
│ └── socketio.js # Socket.io event handlers
└── utils/ # Utility functions and helpers
Create a .env file in the root directory with the following variables:
JWT_SECRET=<jwt_secret>
DB_URL=<mongodb_connection_string>Replace the placeholders with your actual values:
<jwt_secret>- A secure random string for JWT token signing<mongodb_connection_string>- Your MongoDB connection URL
Configuration Features:
- Centralized environment loading through
config/environment.js - Costly
process.envcalls are optimized and cached - Database connection managed in
config/db.js
npm run dev- Start development server with hot reloadnpm run build- Build TypeScript to JavaScriptnpm run start- Start production servernpm run lint- Run ESLintnpm run test- Run tests
POST /api/auth/register # User registration
POST /api/auth/login # User login
POST /api/auth/logout # User logout
GET /api/auth/me # Get current user
GET /api/chat/messages # Get chat messages
POST /api/chat/messages # Send message
register- Register user with JWT token for online statusprivate-message- Send private message to specific user
unauthorized- Invalid token responseonline_users- Updated list of online usersprivate-message- Receive private message from another useruser_offline- User not available for messaging
socket.emit('register', jwt_token);Registers the user with their JWT token to track online status and enable messaging.
socket.emit('private-message', {
recipientSocketId: 'socket_id',
token: 'jwt_token',
message: 'message_content',
});Sends a private message to a specific user using their socket ID.
socket.on('online_users', (users) => {
// users object contains: { userId: { name, socketId, role } }
});Receives updated list of all online users with their details.
socket.on('private-message', (data) => {
// data: { sender: userId, message: content, timestamp: ISO_string }
});Receives a private message from another user.
- Authentication - JWT-based user authentication
- Real-time Chat - Live messaging with Socket.io
- Error Handling - Centralized error management
- Type Safety - TypeScript support for models
- Async Handling - Proper async/await error catching
- Database Integration - MongoDB connection and models
- CORS Support - Cross-origin resource sharing
- Environment Management - Optimized environment variable handling
- Global error handler in
controllers/errorHandler.js - Async wrapper middleware
catchAsyncfor route handlers - Consistent error response format
- Connection setup in
config/db.js - TypeScript models for type safety
- User model with authentication features
- Real-time event handling in
routes/socketio.js - Room-based chat functionality
- Connection management and user presence
The project follows a modular structure with clear separation of concerns:
- Config: Environment and database setup
- Controllers: Business logic and request handling
- Middlewares: Reusable middleware functions
- Models: Data structures and database schemas
- Routes: API endpoints and Socket.io events
- Utils: Helper functions and utilities