logologo
  • AI Tools

    DB Query GeneratorMock InterviewResume BuilderLearning Path GeneratorCheatsheet GeneratorAgentic Prompt GeneratorCompany ResearchCover Letter Generator
  • XpertoAI
  • MVP Ready
  • Resources

    CertificationsTopicsExpertsCollectionsArticlesQuestionsVideosJobs
logologo

Elevate Your Coding with our comprehensive articles and niche collections.

Useful Links

  • Contact Us
  • Privacy Policy
  • Terms & Conditions
  • Refund & Cancellation
  • About Us

Resources

  • Xperto-AI
  • Certifications
  • Python
  • GenAI
  • Machine Learning

Interviews

  • DSA
  • System Design
  • Design Patterns
  • Frontend System Design
  • ReactJS

Procodebase © 2024. All rights reserved.

Level Up Your Skills with Xperto-AI

A multi-AI agent platform that helps you level up your development skills and ace your interview preparation to secure your dream job.

Launch Xperto-AI

WebSocket Integration in NestJS

author
Generated by
ProCodebase AI

10/12/2024

NestJS

Sign in to read full article

In the world of modern web applications, real-time communication is a key feature that enhances user experience and improves interactivity. WebSockets provide a way to achieve this by establishing a persistent connection between the client and the server. In this blog post, we will explore how to integrate WebSocket functionality into your NestJS application, enabling real-time updates and interaction.

What are WebSockets?

WebSockets are a communication protocol that allows for full-duplex communication channels over a single TCP connection. Unlike traditional HTTP requests where the client must initiate the communication, WebSockets enable servers to push updates to clients, which is particularly useful for applications like chat systems, live notifications, collaborative tools, and more.

Setting Up a NestJS Application

Before diving into WebSocket integration, let's make sure you have a basic NestJS application set up. If you haven’t done this yet, you can create a new NestJS project using the Nest CLI:

npm i -g @nestjs/cli nest new my-websocket-app cd my-websocket-app

Installing Required Packages

NestJS provides a built-in package for WebSocket integration, but for added functionality, we can use socket.io. To install it, run:

npm install @nestjs/websockets socket.io

Creating a WebSocket Gateway

A gateway in NestJS acts as a WebSocket server. It listens for incoming connections and handles messages. Let's create a simple WebSocket gateway:

  1. Generate the Gateway

    You can use the Nest CLI to generate a new gateway:

    nest generate gateway chat

    This will create a chat.gateway.ts file in your project.

  2. Implementing the Gateway

    Inside chat.gateway.ts, you can implement the WebSocket event listeners and emitters. Here’s an example:

    import { WebSocketGateway, WebSocketServer, SubscribeMessage, MessageBody, OnGatewayInit, Socket, } from '@nestjs/websockets'; import { Server } from 'socket.io'; @WebSocketGateway() export class ChatGateway implements OnGatewayInit { @WebSocketServer() server: Server; afterInit(server: Server) { console.log('WebSocket Initialized'); } @SubscribeMessage('message') handleMessage(client: Socket, payload: { sender: string; message: string }) { console.log(`Received message: ${payload.message} from ${payload.sender}`); this.server.emit('message', payload); } }

    In this code:

    • The @WebSocketGateway() decorator marks the class as a WebSocket gateway.
    • The afterInit method logs a message when the WebSocket server is initialized.
    • The handleMessage method listens for incoming message events from clients, logs the data, and then emits the message to all connected clients.

Connecting from the Client

To test our WebSocket gateway, we need a client that can connect to it. You can use vanilla JavaScript or a framework of your choice. Here’s a simple HTML file that demonstrates how to connect to the WebSocket server and send messages:

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>WebSocket Client</title> <script src="/socket.io/socket.io.js"></script> </head> <body> <input id="sender" type="text" placeholder="Your name" /> <input id="message" type="text" placeholder="Enter message" /> <button id="sendBtn">Send Message</button> <div id="messages"></div> <script> const socket = io('http://localhost:3000'); // Adjust the port if needed socket.on('message', ({ sender, message }) => { const messagesDiv = document.getElementById('messages'); messagesDiv.innerHTML += `<p><strong>${sender}:</strong> ${message}</p>`; }); document.getElementById('sendBtn').onclick = function () { const sender = document.getElementById('sender').value; const message = document.getElementById('message').value; socket.emit('message', { sender, message }); document.getElementById('message').value = ''; // Clear input }; </script> </body> </html>

Running the Application

  1. Start the NestJS application:

    npm run start
  2. Open your browser and navigate to the HTML file you created. You can open multiple tabs to simulate different clients.

  3. Enter a name and a message in the input fields, click the send button, and watch as messages appear in real-time across all connected clients.

Conclusion

Integrating WebSockets in your NestJS application allows for real-time communication, enhancing user interaction significantly. With the simple setup demonstrated above, you can build chat applications, live notifications, or collaborative platforms easily. The power of WebSockets in conjunction with the structured framework of NestJS opens up exciting possibilities for modern web development.

Keep experimenting with different events and message types to suit your application's needs. Happy coding!

Popular Tags

NestJSWebSocketReal-time applications

Share now!

Like & Bookmark!

Related Collections

  • NestJS Mastery: Modern Backend Development

    10/12/2024 | NestJS

Related Articles

  • Performance Optimization in NestJS Applications

    10/12/2024 | NestJS

  • Working with Databases using TypeORM in NestJS

    10/12/2024 | NestJS

  • Authentication with Passport in NestJS

    10/12/2024 | NestJS

  • Setting Up a NestJS Project

    10/12/2024 | NestJS

  • Understanding Middleware in NestJS

    10/12/2024 | NestJS

  • Caching in NestJS with Redis

    10/12/2024 | NestJS

  • Dependency Injection in NestJS

    10/12/2024 | NestJS

Popular Category

  • Python
  • Generative AI
  • Machine Learning
  • ReactJS
  • System Design