A real-time chat application server built with Node.js, Express, TypeScript, and Socket.IO.
- Real-time messaging with Socket.IO
- Room-based chat system
- User join/leave notifications
- Typing indicators
- REST API endpoints
- TypeScript support
- CORS enabled for frontend integration
- Node.js (v16 or higher)
- npm or yarn
-
Clone or download this project
-
Install dependencies:
npm install
-
Create a
.envfile in the root directory:PORT=3001 CLIENT_URL=http://localhost:3000 NODE_ENV=development, MONGODB_URI, JWT_SECRET, FIREBASE_PROJECT_ID, FIREBASE_PRIVATE_KEY_ID FIREBASE_CLIENT_EMAIL, FIREBASE_CLIENT_ID, REDIS_URL, REDIS_PASSWORD, REDIS_PORT, JWT_EXPIRES_IN
npm run dev- Start development server with hot reloadnpm run build- Build TypeScript to JavaScriptnpm start- Start production servernpm test- Run tests
Start the development server:
npm run devThe server will start on http://localhost:3001 (or the port specified in your .env file).
GET /- Server status and infoGET /api/users- Get all connected usersGET /api/rooms- Get all active rooms
-
join- Join a chat roomsocket.emit("join", { username: "John", room: "general" });
-
sendMessage- Send a messagesocket.emit("sendMessage", { message: "Hello world!", room: "general" });
-
typing- Send typing indicatorsocket.emit("typing", { isTyping: true, room: "general" });
-
changeRoom- Change to a different roomsocket.emit("changeRoom", { newRoom: "random" });
userJoined- User joined the roomuserLeft- User left the roomnewMessage- New message receiveduserTyping- User typing indicatorroomUsers- List of users in current room
Here's a basic example of how to connect from a client:
import { io } from "socket.io-client";
const socket = io("http://localhost:3001");
// Join a room
socket.emit("join", { username: "YourName", room: "general" });
// Listen for messages
socket.on("newMessage", (message) => {
console.log("New message:", message);
});
// Send a message
socket.emit("sendMessage", { message: "Hello everyone!" });
// Listen for user events
socket.on("userJoined", (data) => {
console.log(`${data.username} joined the chat`);
});
socket.on("userLeft", (data) => {
console.log(`${data.username} left the chat`);
});├── src/
│ └── index.ts # Main server file
├── dist/ # Compiled JavaScript (generated)
├── package.json # Dependencies and scripts
├── tsconfig.json # TypeScript configuration
└── README.md # This file
PORT- Server port (default: 3001)CLIENT_URL- Allowed CORS origin (default: http://localhost:3000)NODE_ENV- Environment mode (development/production)
-
Build the TypeScript code:
npm run build
-
Start the production server:
npm start
- Fork the repository
- Create a feature branch
- Make your changes
- Test thoroughly
- Submit a pull request
ISC