What is @nestjs/websockets?
@nestjs/websockets is a module for the NestJS framework that provides WebSocket capabilities. It allows developers to create real-time, event-driven applications using WebSockets, which are essential for applications requiring instant data updates, such as chat applications, live notifications, and online gaming.
What are @nestjs/websockets's main functionalities?
WebSocket Gateway
This feature allows you to create a WebSocket gateway that listens for incoming WebSocket connections and messages. The `@WebSocketGateway` decorator is used to define a WebSocket gateway, and the `@SubscribeMessage` decorator is used to handle specific message events.
```typescript
import { WebSocketGateway, WebSocketServer, SubscribeMessage, MessageBody } from '@nestjs/websockets';
import { Server } from 'socket.io';
@WebSocketGateway()
export class ChatGateway {
@WebSocketServer()
server: Server;
@SubscribeMessage('message')
handleMessage(@MessageBody() message: string): void {
this.server.emit('message', message);
}
}
```
WebSocket Client
This feature allows you to create a WebSocket client that can connect to a WebSocket server. The `@WebSocketClient` decorator is used to define a WebSocket client, and the `OnGatewayInit`, `OnGatewayConnection`, and `OnGatewayDisconnect` interfaces are used to handle client lifecycle events.
```typescript
import { Injectable } from '@nestjs/common';
import { WebSocketClient, OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect } from '@nestjs/websockets';
import { Socket } from 'socket.io-client';
@Injectable()
@WebSocketClient()
export class ChatClient implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect {
private client: Socket;
afterInit(client: Socket) {
this.client = client;
console.log('WebSocket client initialized');
}
handleConnection(client: Socket) {
console.log('Client connected:', client.id);
}
handleDisconnect(client: Socket) {
console.log('Client disconnected:', client.id);
}
}
```
Custom WebSocket Server
This feature allows you to create a custom WebSocket server using the `ws` library. The `@WebSocketGateway` decorator can accept a custom server instance, and you can handle connection and message events directly.
```typescript
import { WebSocketGateway, WebSocketServer } from '@nestjs/websockets';
import { Server } from 'ws';
@WebSocketGateway({ server: new Server({ port: 8080 }) })
export class CustomGateway {
@WebSocketServer()
server: Server;
constructor() {
this.server.on('connection', (socket) => {
socket.on('message', (message) => {
console.log('Received message:', message);
});
});
}
}
```
Other packages similar to @nestjs/websockets
socket.io
Socket.IO is a popular library for real-time web applications. It enables real-time, bidirectional, and event-based communication between web clients and servers. Compared to @nestjs/websockets, Socket.IO is more general-purpose and can be used with various frameworks, while @nestjs/websockets is specifically designed for use with the NestJS framework.
ws
The `ws` package is a simple and fast WebSocket library for Node.js. It provides a bare-bones WebSocket server and client implementation. Compared to @nestjs/websockets, `ws` is lower-level and requires more manual setup, whereas @nestjs/websockets provides a more integrated and higher-level API within the NestJS framework.
A progressive Node.js framework for building efficient and scalable web applications. :cat:
Description
Nest is a framework for building efficient, scalable Node.js web applications. It uses modern JavaScript, is built with TypeScript (preserves compatibility with pure JavaScript) and combines elements of OOP (Object Oriented Progamming), FP (Functional Programming), and FRP (Functional Reactive Programming).
Under the hood, Nest makes use of Express, allowing for easy use of the myriad third-party plugins which are available.
Philosophy
In recent years, thanks to Node.js, JavaScript has become the “lingua franca” of the web for both front and backend applications, giving rise to awesome projects like Angular, React and Vue which improve developer productivity and enable the construction of fast, testable, extensible frontend applications. However, on the server-side, while there are a lot of superb libraries, helpers and tools for Node, none of them effectively solve the main problem - the architecture.
Nest aims to provide an application architecture out of the box which allows for effortless creation of highly testable, scalable, loosely coupled and easily maintainable applications.
Features
- Built with TypeScript (compatible with pure JavaScript + Babel)
- Easy to learn - syntax similar to Angular
- Familiar - based on well-known libraries (Express / socket.io)
- Dependency Injection - built-in asynchronous IoC container with a hierarchical injector
- WebSockets module (based on socket.io, but you can bring your own library, by making use of
WsAdapter
) - Modular - defines an easy to follow module definition pattern so you can split your system into reusable modules
- Reactive microservice support with message patterns (built-in transport via TCP / Redis, but other communication schemes can be implemented with
CustomTransportStrategy
) - Exception layer - throwable web exceptions with status codes, exception filters
- Pipes - synchronous & asynchronous (e.g. validation purposes)
- Guards - attach additional logic in a declarative manner (e.g. role-based access control)
- Interceptors - built on top of RxJS
- Testing utilities (both e2e & unit tests)
Installation
Install the TypeScript Starter Project with Git:
$ git clone https://github.com/nestjs/typescript-starter.git project
$ cd project
$ npm install
$ npm run start
Install the JavaScript (Babel) Starter Project with Git:
$ git clone https://github.com/nestjs/javascript-starter.git project
$ cd project
$ npm install
$ npm run start
Start a New Project from Scratch with NPM:
$ npm i --save @nestjs/core @nestjs/common @nestjs/microservices @nestjs/websockets @nestjs/testing reflect-metadata rxjs
Documentation & Quick Start
:books: Documentation & Tutorial
Backers
I am on a mission to provide an architecture to create truly flexible, scalable and loosely coupled systems using the Node.js platform. It takes a lot of time, so if you want to support me, please become a backer / sponsor. I appreciate your help. Thanks! :heart_eyes:
People
License
MIT