Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • TypeScript
  • Vue.js
  • D3.js
  • Collect.js
  • Underscore.js
  • Moment.js
  • Ember.js
  • Tensorflow.js
  • Fabric.js
  • JS Formatter
  • JavaScript
  • Web Technology
Open In App
Next Article:
How To Create an App Using ChatGPT
Next article icon

Create a Chat App with Vue.js

Last Updated : 07 May, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we will explore how to build a real-time chat application using Socket.IO and Vue.js. Socket.IO is a popular library that enables real-time, bidirectional, and event-based communication between the client and the server. By integrating Socket.IO with Vue.js, we can create a seamless and interactive chat experience for users.

Prerequisites

  • Node.js
  • Vue.js
  • Socket.IO-client

Approach

  • Set up a Vue.js project.
  • Install the socket.io-client module to communicate with the Socket.IO server.
  • Create Vue.js components for the chat form and message display.
  • Implement the client-side event emission and handling in the Vue.js components.
  • Set up the server-side event listeners and message broadcasting.

Steps for the Vue.js project

Step 1: Run the command to create a Vue.js app

npm init vue@latest

Step 2: Give name to your project and go to that project

cd my-chat-app

Step 3: Install the required dependencies:

Install the Socket.IO library for real-time communication

npm install socket.io npm install socket.io-client

update dependencies looks like:

"dependencies": {         "socket.io": "^4.7.5",         "socket.io-client": "^4.7.5",         "vue": "^3.4.21"       },

Project Structure:

project structure

Step 4: Set up the server-side code:

Create a new directory called server in the project root. and navigate to the server directory:

mkdir server cd server

Project structure:

Screenshot-2024-04-28-225416

Step 5: Initialize a new Node.js project and install the required dependencies:

npm init -y npm install socket.io http

Updated dependencies looks like:

"dependencies": {         "http": "^0.0.1-security",         "socket.io": "^4.7.5"       }

Step 6: Create a new file called index.js and add the following code:

//server/index.js const http = require('http'); const fs = require('fs'); const socketIo = require('socket.io');  const port = 5000; const server = http.createServer((req, res) => {   if (req.url === '/') {     fs.readFile(__dirname + '/index.html', (err, data) => {       if (err) {         res.writeHead(500);         res.end('Error loading index.html');       } else {         res.writeHead(200, { 'Content-Type': 'text/html' });         res.end(data);       }     });   } });  const io = socketIo(server, {   cors: {
// Replace with your client-side URL origin: 'http://localhost:5173', methods: ['GET', 'POST'] } }); io.on('connection', (socket) => { console.log('A user connected'); socket.on('send message', (chat) => { io.emit('send message', chat); }); }); server.listen(port, () => { console.log(`Server is listening at the port: ${port}`); });

Step 7: Integrate the Vue.js components. add these codes into respective files.

CSS
/* style.css */  body {     background-color: #464e46;     margin: 0;     padding: 0;     font-family: Arial, sans-serif; }  .container {     max-width: 400px;     margin: 80px auto;     padding: 20px;     background-color: white;     border-radius: 10px;     box-shadow: 0 0 10px rgba(0, 0, 0, 0.1); }  .logo {     text-align: center;     font-size: 24px;     font-weight: bold;     margin-bottom: 20px;     color: #008000; }  .form { display: flex; flex-direction: column; align-items: center; }  .input {     border: 1px solid #ccc;     border-radius: 5px;     padding: 10px;     margin-bottom: 10px;     width: 100%; }  .button {     background-color: #008000;     color: white;     border: none;     border-radius: 5px;     padding: 10px;     width: 100%;     cursor: pointer; }  .messageArea {     margin-top: 20px;     border: 1px solid #ccc;     border-radius: 5px;     padding: 10px;     height: 200px;     overflow-y: scroll; }  .message {     margin-bottom: 5px; }  .username {     font-weight: bold;     color: #005180; } 
JavaScript
//ChatForm.vue  <template>   <form class="form" @submit.prevent="sendMessage">     <input class="input" type="text"             placeholder="Name"              v-model="username" />     <input class="input" type="text"             placeholder="Message"            v-model="message" />     <button class="button">Send Message</button>   </form> </template>  <script> import { io } from 'socket.io-client';  export default {   data() {     return {       username: '',       message: '',       socket: io('http://localhost:5000'),     };   },   methods: {     sendMessage() {       if (this.message && this.username) {         this.socket.emit('send message',         { username: this.username,         content: this.message });         this.message = '';       }     },   }, }; </script> 
JavaScript
//ChatMessage.vue  <template>   <div class="messageArea">     <p class="message" v-for="message in messages"                        :key="message.id">       <span class="username">{{ message.username }}:</span>       <span class="content">{{ message.content }}</span>     </p>   </div> </template>  <script> import { io } from 'socket.io-client';  export default {   data() {     return {       messages: [],       socket: io('http://localhost:5000'),     };   },   mounted() {     this.socket.on('send message', (message) => {       this.messages.push(message);     });   }, }; </script> 
JavaScript
/App.vue  <template>   <div class="container">     <h1 class="logo">GeeksforGeeks ChatApp</h1>     <ChatForm />     <ChatMessage />   </div> </template>  <script> import ChatForm from './components/ChatForm.vue'; import ChatMessage from './components/ChatMessage.vue';  export default {   components: {     ChatForm,     ChatMessage,   }, }; </script>  <style> @import './style.css'; </style> 

Step 8: Start the development server:

In the project root directory, run the following command to start the Vue.js development server

npm run dev

Step 9: In a separate terminal, navigate to the server directory and start the server

node index.js

The application should now be running, and you can access it at http://localhost:3000. The server-side code is running at http://localhost:5000 and handling the real-time communication using Socket.IO.

Output:

chat


Next Article
How To Create an App Using ChatGPT

A

ashishrew7vh
Improve
Article Tags :
  • Project
  • JavaScript
  • Web Technologies
  • Vue.JS
  • JavaScript-Projects

Similar Reads

  • Create an Image Gallery App with Vue.js
    In this tutorial, we'll walk through the process of building an image gallery application using Vue.js. We'll explore different approaches to displaying images and provide the complete executable code for each one of them. Table of Content Using Vue components to create the galleryUsing Vue CDN to c
    3 min read
  • How To Create an App Using ChatGPT
    In the domain of Artificial Intelligence, generative AI has emerged exponentially in the recent past, and ChatGPT has disrupted the industry completely. ChatGPT is used to generate plagiarism-free content for learning and knowledgeful purposes. But you can also create software applications using it.
    9 min read
  • Create a Chatbot App using React-Native
    Creating a chatbot app using React Native will be an exciting project. In this article, we are going to implement a Chatbot App using React Native. Chatbot App is a mobile application that answers the user's questions on the basis of their previous learning or content provided by developers. It help
    4 min read
  • How to Create a Group Chat in Discord
    How to Start a Group Chat on Discord- Quick StepsOpen Discord App or Web AppGo to the Friends TabClick on '+' create DM IconSelect Friends > Click Start DMStart Group ChatDiscord has emerged as a popular platform that offers a variety of features to bring communities and friends together. One of
    7 min read
  • How To Create a Popup Chat Window With CSS?
    One of the many ways to assist your users actively is by adding a popup chat window on your website. This tutorial will walk you through the process of building a basic but useful popup chat box with HTML, CSS, and JavaScript. Approach:Design the layout with the "Open Chat," header, message input, a
    3 min read
  • How to Create a Chat App Using socket.io in NodeJS?
    Socket.io is a JavaScript library that enables real-time, bidirectional, event-based communication between the client and server. It works on top of WebSocket but provides additional features like automatic reconnection, broadcasting, and fallback options. What We Are Going to Create?In this article
    5 min read
  • Vue.js Composition API with Templates
    Vue.js is a progressive javascript framework for developing web user interfaces. It is a versatile framework providing high speed and performance. We can create Single Page Applications as well as Full Stack applications. The Composition API allows author to Vue components using imported functions r
    3 min read
  • Vue.js Custom Directives with Components
    Vue.js is a progressive javascript framework for developing web user interfaces. It is a performant, approachable, and versatile framework. We can create Single Page Applications as well as Full Stack applications. It is built on top of HTML, CSS, and Javascript which makes it easier for developers
    3 min read
  • Build a Movie App with VueJS
    We will build a movie application using Vue.js. By the end, you'll have a fully functional movie app that will allow users to search for movies, view their details, and get information such as title, year, rating, and plot. Prerequisites:Vue.jsNode.js and npm are installed on your system.Approach Vu
    5 min read
  • Build a Calculator with VueJS
    We'll learn how to build a simple calculator app using Vue.js. A calculator is a fundamental tool for performing mathematical calculations, and building one using Vue.js is a great way to understand the basics of Vue.js components, data binding, and event handling. Step-by-step guide to set up the p
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences