NestJS is one of the things I have been playing around a bit in the recent days. Here’s how you can create a websocket application quickly on NestJS.
Did I say this is a sample app that serves no real-world value other than poking around the application?
Setup project in NestJS
First.. install NextJS if you have not done so.
yarn global add @nestjs/cli
Create a new project.
nest new websocket-proj
Now, install support for sockets.
cd websocket-proj
yarn add -D @types/socket.io
yarn add @nestjs/websockets @nestjs/platform-socket.io
Open the folder websocket-proj in VS Code. We can delete everything in the src folder except app.module.ts and main.ts.
Add websocket functions
Add an app gateway using Nest CLI.
nest g gateway App
This adds two files app.gateway.spec.ts and app.gateway.ts. The latter looks like the below -
import { SubscribeMessage, WebSocketGateway } from "@nestjs/websockets";
import { Logger } from "@nestjs/common";
@WebSocketGateway()
export class AppGateway implements OnGatewayInit {
// export class AppGateway {
@SubscribeMessage("message")
handleMessage(client: any, payload: any): string {
return "Hello world!";
}
}
The generator also adds reference of the gateway file in app.module.ts. Your app module will look like below.
import { Module } from "@nestjs/common";
import { AppGateway } from "./app.gateway";
@Module({
imports: [],
controllers: [],
providers: [AppGateway],
})
export class AppModule {}
Change app.gateway.ts -
- extend AppGateway to implement
OnGatewayInit - log a string when initialized
import {
SubscribeMessage,
WebSocketGateway,
OnGatewayInit,
} from "@nestjs/websockets";
import { Logger } from "@nestjs/common";
@WebSocketGateway(3001)
export class AppGateway implements OnGatewayInit {
private logger: Logger = new Logger("AppGateway");
afterInit(server: any) {
// throw new Error('Method not implemented.'); - comment this
this.logger.log("Initialized");
}
// export class AppGateway {
@SubscribeMessage("message")
handleMessage(client: any, payload: any): string {
return "Hello world!";
}
}
Start server in dev mode.
yarn start:dev
The server starts and you see this beautiful message.

You could now use any web socket client to subscribe to a message on port 3001 and get “hello world” back.