npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

smart-socket-nestjs

v1.1.0

Published

A powerful real-time WebSocket system for NestJS using Socket.IO

Readme

smart-socket-nestjs

npm version License: MIT GitHub stars

Author: Nurul Islam Rimon

A powerful and simple real-time WebSocket library for NestJS using Socket.IO.

Features

  • NestJS Module - Easy integration with forRoot() and forRootAsync()
  • Gateway Decorator - @SocketGateway("namespace") for namespace registration
  • Event Decorator - @SocketEvent("event") for handling socket events
  • Socket Service - Injectable service for emitting events
  • JWT Authentication - Built-in JWT authentication support
  • Room Management - Join/leave rooms and users
  • Redis Adapter - Support for scaling using Redis adapter
  • Typed Events - TypeScript generics support
  • Connection Tracking - Track online users
  • Rate Limiting - Built-in rate limiting

Requirements

  • NestJS 11.x
  • Node.js 18+

Installation

npm install smart-socket-nestjs

Quick Start

1. Import the module

import { SmartSocketModule } from 'smart-socket-nestjs';

@Module({
  imports: [
    SmartSocketModule.forRoot({
      namespace: '/chat',
      cors: {
        origin: '*',
      },
    }),
  ],
})
export class AppModule {}

2. Create a Gateway

import { Controller } from '@nestjs/common';
import { SocketGateway, SocketEvent } from 'smart-socket-nestjs';
import { SmartSocketService, AuthenticatedSocket } from 'smart-socket-nestjs';

@SocketGateway('chat')
export class ChatGateway {
  constructor(private readonly socketService: SmartSocketService) {}

  @SocketEvent('message')
  async handleMessage(socket: AuthenticatedSocket, data: { text: string }) {
    console.log(`User ${socket.user?.id} sent: ${data.text}`);
    
    // Broadcast to all users in the room
    this.socketService.toRoom('room-1', 'new-message', {
      userId: socket.user?.id,
      text: data.text,
    });
  }

  @SocketEvent('join-room')
  async handleJoinRoom(socket: AuthenticatedSocket, data: { room: string }) {
    await this.socketService.joinRoom(socket, data.room);
    socket.emit('joined', { room: data.room });
  }
}

Usage Examples

Module Configuration

Synchronous Configuration

SmartSocketModule.forRoot({
  namespace: '/api',
  cors: {
    origin: '*',
  },
  enableRateLimiting: true,
  rateLimitOptions: {
    windowMs: 60000,
    maxRequests: 100,
  },
  jwtSecret: 'your-secret-key',
  jwtAlgorithm: 'HS256',
  redis: {
    host: 'localhost',
    port: 6379,
  },
}),

Asynchronous Configuration

SmartSocketModule.forRootAsync({
  useFactory: (configService: ConfigService) => ({
    namespace: '/api',
    jwtSecret: configService.get('JWT_SECRET'),
    redis: {
      host: configService.get('REDIS_HOST'),
      port: configService.get('REDIS_PORT'),
    },
  }),
  inject: [ConfigService],
}),

Socket Service Methods

constructor(private readonly socketService: SmartSocketService) {}

// Emit to all clients
this.socketService.emit('event', data);

// Emit to specific room
this.socketService.toRoom('room-id', 'event', data);

// Emit to specific user
this.socketService.toUser(userId, 'event', data);

// Broadcast to all clients
this.socketService.broadcast('event', data);

// Join room
await this.socketService.joinRoom(socket, 'room-id');

// Leave room
await this.socketService.leaveRoom(socket, 'room-id');

// Join user to room
await this.socketService.joinUser(userId, 'room-id');

// Leave user from room
await this.socketService.leaveUser(userId, 'room-id');

// Get all connected users
const users = this.socketService.getConnectedUsers();

// Check if user is online
const online = this.socketService.isOnline(userId);

Using Typed Events

interface ChatMessage {
  id: string;
  text: string;
  userId: string;
}

@SocketGateway('chat')
export class ChatGateway {
  @SocketEvent('message')
  handleMessage(socket: AuthenticatedSocket, data: ChatMessage) {
    // data is typed as ChatMessage
  }
}

JWT Authentication

When JWT is configured, the socket will have access to socket.user:

@SocketGateway('chat')
export class ChatGateway {
  @SocketEvent('private-message')
  handlePrivateMessage(socket: AuthenticatedSocket, data: { to: string; text: string }) {
    // Access authenticated user
    const fromUserId = socket.user?.id;
    console.log(`User ${fromUserId} sending private message`);
  }
}

Client-side connection with JWT:

import { io } from 'socket.io-client';

const socket = io('http://localhost:3000/chat', {
  auth: {
    token: 'your-jwt-token',
  },
});

Redis Adapter for Scaling

SmartSocketModule.forRoot({
  namespace: '/api',
  redis: {
    host: 'localhost',
    port: 6379,
    password: 'redis-password',
    db: 0,
  },
}),

API Reference

Decorators

@SocketGateway(namespace: string, options?: Record<string, unknown>)

Registers a Socket.IO namespace.

@SocketEvent(event: string)

Handles a socket event.

SmartSocketService Methods

| Method | Description | |--------|-------------| | emit(event, data, options?) | Emit to all clients or specific targets | | toUser(userId, event, data, namespace?) | Emit to specific user | | toRoom(room, event, data, namespace?) | Emit to specific room | | broadcast(event, data, namespace?) | Broadcast to all clients | | joinRoom(socket, room) | Join a socket to a room | | leaveRoom(socket, room) | Leave a socket from a room | | joinUser(userId, room, namespace?) | Join user to room | | leaveUser(userId, room, namespace?) | Remove user from room | | getConnectedUsers() | Get all connected users | | isOnline(userId) | Check if user is online | | getUserSocketIds(userId) | Get socket IDs for user |

License

MIT