Create a Chat App with Vue.js
Last Updated :
07 May, 2024
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
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:

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:

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:

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
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 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
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
How to Integrate Vite with Vue.js? Vite provides the flexibility and speed needed for modern web development by offering a fast-build tool and development server. Integrating Vite with Vue.js allows developers to use Viteâs efficient hot module replacement and optimized build processes while working with Vue's reactive framework. Thi
3 min read
Consuming a Rest API with Axios in Vue.js Many times when building an application for the web that you may want to consume and display data from an API in VueJS using JavaScript fetch API, Vue resource, jquery ajax API, but a very popular and most recommended approach is to use Axios, a promise-based HTTP client. Axios is a great HTTP clien
2 min read
How to Setup VideoJS with VueJS? Video.js is a popular javascript library that allows support for various video playback formats on the web. With it, we can embed and customize our video components in our web pages that are made in various frontend frameworks like, Vue.js, React, Angular, etc. In this article, we will learn how to
2 min read
How to create a reporting app with Vue 3 and Composition API ? Vue is an open-source JavaScript front-end framework for building the UI for websites and apps. The main features are an incrementally adaptable architecture that focuses on declarative rendering and component composition. Not long time ago Vue has released new version - Vue 3. The updated framework
3 min read
How to replace jQuery with Vue.js ? In this article, we will see how to replace jQuery with Vue. jQuery: jQuery is a fast and rich JavaScript library. It is an application programming interface (API), a cross-platform JavaScript library designed to improve web browser features. It makes things easier like works across HTML document tr
6 min read