socket-auth-room-manager
v1.0.1
Published
Socket.IO authentication middleware and room management utility with JWT support
Maintainers
Readme
🚀 socket-auth-room-manager
A lightweight and flexible Socket.IO authentication + room management utility with JWT support.
Simplifies:
- 🔐 Socket authentication (JWT + cookies)
- 🏠 Room join/leave management
- 👥 User tracking inside rooms
- ⚡ Emitting events to rooms
- 🧼 Automatic cleanup on disconnect
📦 Installation
npm install socket-auth-room-manager⚡ Quick Start
import { Server } from "socket.io";
import {
socketAuth,
joinRoom,
emitToRoom,
setupDisconnectHandler,
} from "socket-auth-room-manager";
const io = new Server(server, {
cors: { origin: "*" },
});
// 🔐 Attach authentication middleware
io.use(socketAuth({ secret: "your_jwt_secret" }));
io.on("connection", (socket) => {
console.log("User connected:", socket.user);
// 🧼 Handle disconnect cleanup
setupDisconnectHandler(socket);
// 🏠 Join a room
joinRoom(socket, "room1");
// 📡 Emit messages to room
socket.on("message", (msg) => {
emitToRoom(io, "room1", "message", msg);
});
});🔐 Authentication
Supports token from:
socket.handshake.auth.tokenhttpOnly cookies
Example (client)
const socket = io("http://localhost:3000", {
auth: {
token: "your_jwt_token",
},
});🧠 API Reference
🔐 socketAuth(options)
Middleware for authenticating socket connections.
Options:
secret(required): JWT secret keycookieName(optional): default"token"
Usage:
io.use(socketAuth({ secret: "your_secret" }));🏠 joinRoom(socket, roomId)
Adds a user to a room.
joinRoom(socket, "room1");🚪 leaveRoom(socket, roomId)
Removes a user from a room.
leaveRoom(socket, "room1");📡 emitToRoom(io, roomId, event, data)
Broadcasts an event to all users in a room.
emitToRoom(io, "room1", "message", { text: "Hello" });👥 getRoomUsers(roomId)
Returns users inside a room.
const users = getRoomUsers("room1");📊 getRoomSize(roomId)
Returns number of users in a room.
const size = getRoomSize("room1");🗂️ getAllRooms()
Returns all active rooms.
const rooms = getAllRooms();🧼 setupDisconnectHandler(socket)
Automatically removes user from all rooms on disconnect.
setupDisconnectHandler(socket);🧩 Features
- ✅ JWT-based authentication
- 🍪 Cookie support (httpOnly compatible)
- ⚡ Lightweight and fast (in-memory store)
- 🧠 User tracking per room
- 🔄 Automatic cleanup on disconnect
- 🧼 Clean and minimal API design
⚠️ Notes
This package uses in-memory storage → Not suitable for multi-server scaling (use Redis for that)
Designed for simplicity and performance
🚀 Future Improvements
- Redis adapter support
- Role-based rooms
- Rate limiting per room
- Event logging hooks
🤝 Contributing
Contributions are welcome!
- Fork the repo
- Create a new branch
- Commit changes
- Open a pull request
📄 License
MIT © Sarvesh Wani
⭐ Support
If you find this useful, consider giving it a ⭐ on GitHub!
