0Pricing
Node.js Backend Development Bootcamp · Lesson

Gateway Configuration

Configure WebSocket gateways in NestJS, handling connection events, messages, and room management.

Unlocking Real-time with Gateways

Welcome back! In the previous lesson, we learned about WebSockets. Now, let's dive into how NestJS makes real-time communication easy with Gateways.

Think of a Gateway as a special controller for WebSocket connections. It listens for messages from clients and sends responses back, enabling dynamic, two-way communication.

Creating Your First Gateway

To create a Gateway, we use the @WebSocketGateway() decorator. This decorator marks a class as a WebSocket gateway.

By default, NestJS uses Socket.IO. You can specify a port, namespace, or other options. Let's start with a basic gateway:

import { WebSocketGateway,
         WebSocketServer } from '@nestjs/websockets';
import { Server } from 'socket.io';

// src/events.gateway.ts
@WebSocketGateway(3001) // Listens on port 3001 for WS
export class EventsGateway {
  @WebSocketServer() server: Server;
}

// src/app.module.ts (minimal)
import { Module } from '@nestjs/common';
import { EventsGateway } from './events.gateway';

@Module({
  providers: [EventsGateway],
})
export class AppModule {}

// src/main.ts (minimal)
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  await app.listen(3000); // HTTP app, WS runs alongside
}
bootstrap();

All lessons in this course

  1. Introduction to WebSockets
  2. WebSockets with NestJS
  3. Implementing Socket.IO in Node.js
  4. Gateway Configuration
  5. Building a Real-time Chat Application
  6. Real-time Chat Application
← Back to Node.js Backend Development Bootcamp