VOOZH about

URL: https://www.geeksforgeeks.org/node-js/how-to-manage-users-in-socket-io-in-node-js/

⇱ How to Manage Users in Socket.io in Node.js ? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to Manage Users in Socket.io in Node.js ?

Last Updated : 3 Jun, 2026

In a real-time application, the server needs a way to keep track of who is connected and how to communicate with them individually or in groups. Socket.io handles this by assigning each client a unique connection and allowing the server to manage these connections efficiently. User management in Socket.io typically involves the following steps:

  • Map users to socket IDs: Link socket.id with user data (e.g., username).
  • Track active users: Store connected users in an object or map.
  • Remove on disconnect: Delete user data when the disconnect event fires.
  • Send targeted messages: Use socket IDs to emit events to specific users.
  • Group with rooms: Use rooms to manage communication for multiple users.

Steps to Create Application

Backend Setup

Step 1: Initialize the project using the command

npm init

Step 2 : Install the requires dependencies:

npm i cors express nodemon socket.io http

Project Structure for Backend:

👁 Image

The updated dependencies in package.json file of backend will look like:

{
"dependencies": {
"cors": "^2.8.5",
"express": "^4.18.2",
"http": "^0.0.1-security",
"nodemon": "^3.0.1",
"socket.io": "^4.7.2"
}
}

Example: Socket.on listens for a join event emitted by the frontend; the backend then emits a message event to notify that the user joined. It also handles connection, messaging, and user management functions like add, remove, and get users.

Frontend Setup:

Step 1: Install react for frontend using this command in terminal

npx create react-app client

Step 2: After react installed, install dependencies for Project inside client folder.

cd client
npm i query-string react-emoji react-router socket.io-client

Project Structure for frontend:

👁 Image

The updated dependencies in package.json file of frontend will look like:

 "dependencies": {
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"query-string": "^8.1.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-emoji": "^0.5.0",
"react-router": "^6.17.0",
"react-scripts": "5.0.1",
"socket.io-client": "^4.7.2",
"web-vitals": "^2.1.4"
},

Step 3: Inside App.js, create routes for the pages join page and chat page and import the components for both pages to display on that route.

Filename: App.js

Output: Open the browser and type localhost 3000 to see the application running.

Comment

Explore