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
Steps to Create an Express.js Application
Creating an Express.js application involves several steps that guide you through setting up a basic server to handle complex routes and middleware. Express.js is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications. Hereâs a
10 min read
Movie Web Application with ReactJS
React Movie APP is a movie web application project that involves creating components to display a list of movies and details about each movie along with a search functionality. Preview Image of Final Output: Approach for React Movie AppTo create the movie web application in React we will be using an
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