Creating a Real-Time Chat App with Next.js and WebSockets

Mohammadaliasghar
2 min readSep 8, 2023

--

Introduction:

In this comprehensive tutorial, we’ll walk through the process of building a real-time chat application using Next.js and WebSockets. Real-time features are vital for modern applications, and Next.js combined with WebSockets provides a robust solution for creating interactive and collaborative experiences.

Prerequisites:

Before we begin, ensure you have Node.js and npm (Node Package Manager) installed on your system. You can download them from nodejs.org.

Setting Up a New Next.js Project:

Create a new Next.js project by running the following commands in your terminal:

npx create-next-app real-time-chat-app
cd real-time-chat-app

Install additional dependencies for managing WebSocket connections:

npm install socket.io-client socket.io

Creating the WebSocket Server:

Create a WebSocket server that will handle real-time communication. Create a new folder named server in the project root directory and create a server.js file inside it:

// server/server.js
const http = require('http');
const server = http.createServer((req, res) => {
// Handle HTTP requests if needed
});

const { Server } = require('socket.io');
const io = new Server(server);

io.on('connection', (socket) => {
console.log('A user connected');

// Handle chat messages
socket.on('chat message', (message) => {
io.emit('chat message', message); // Broadcast the message to all connected clients
});

socket.on('disconnect', () => {
console.log('A user disconnected');
});
});

server.listen(3001, () => {
console.log('WebSocket server listening on port 3001');
});

Creating the Chat Interface:

In the pages folder, create a new file named index.js for the chat interface:

// pages/index.js
import React, { useState, useEffect } from 'react';
import io from 'socket.io-client';

const socket = io('http://localhost:3001'); // Replace with your server URL

const Index = () => {
const [messages, setMessages] = useState([]);
const [newMessage, setNewMessage] = useState('');

useEffect(() => {
// Listen for incoming messages
socket.on('chat message', (message) => {
setMessages((prevMessages) => [...prevMessages, message]);
});
}, []);

const sendMessage = () => {
socket.emit('chat message', newMessage);
setNewMessage('');
};

return (
<div>
<h1>Real-Time Chat</h1>
<div>
{messages.map((message, index) => (
<div key={index}>{message}</div>
))}
</div>
<input
type="text"
value={newMessage}
onChange={(e) => setNewMessage(e.target.value)}
/>
<button onClick={sendMessage}>Send</button>
</div>
);
};

export default Index;

Running the Application:

Start your Next.js application and the WebSocket server:

npm run dev

Your real-time chat application should now be running at http://localhost:3000. Open it in multiple browser tabs or devices to see real-time messages in action.

Conclusion:

Congratulations! You’ve built a real-time chat application using Next.js and WebSockets from scratch. This is a fundamental example, but you can extend it by adding user authentication, message history, and more features to create a full-fledged chat application.

Stay tuned for more tutorials where we’ll explore advanced real-time application development techniques and tackle common challenges!

--

--

Mohammadaliasghar

Skilled Software Engineer | Innovator | Karachi, Pakistan 🇵🇰 | Coding for Success 🚀