In today’s interconnected world, real-time communication is a crucial feature for many web applications. If you’re building a chat application or adding chat functionality to your site, you might find it beneficial to use WebSockets. In this post, we’ll explore how to implement a real-time chat socket using Express.js for the backend and Next.js for the front end.
My Portfolio Website: https://padamthapa.com.np/
GitHub Link: https://github.com/Padam7890
Overview
We’ll create a simple chat application with the following technologies:
- Express.js: For the backend, managing socket connections and handling messages.
- Next.js: For the front end, displaying messages and handling user input.
- Socket.io: A library that enables real-time communication between web clients and servers.
Setting Up the Backend with Express.js
Here’s a detailed post about implementing a chat socket using Express and Next.js:
1. Initialize a New Project
Start by creating a new directory for your project and initializing a new Node.js project:
mkdir chat-app-backend
cd chat-app-backend
npm init -y
2. Install Dependencies
Install Express and Socket.io:
npm install express socket.io
3. Create the Express Server
Create a file named server.js
and set up your Express server with Socket.io:
// server.js
const express = require('express');
const http = require('http');
const socketIo = require('socket.io');
const app = express();
const server = http.createServer(app);
const io = socketIo(server);
app.use(express.static('public'));
io.on('connection', (socket) => {
console.log('New client connected');
socket.on('message', (msg) => {
console.log('Message received:', msg);
io.emit('message', msg); // Broadcast the message to all clients
});
socket.on('disconnect', () => {
console.log('Client disconnected');
});
});
const PORT = process.env.PORT || 3001;
server.listen(PORT, () => console.log(`Server running on port ${PORT}`));
In this setup:
- We create an Express server and attach Socket.io to it.
- We listen for incoming connections and handle messages.
- When a message is received, it is broadcast to all connected clients.
Setting Up the Frontend with Next.js
Next, we’ll create the frontend application using Next.js and integrate it with our Socket.io backend.
1. Initialize a New Next.js Project
Create a new Next.js project:
npx create-next-app@latest chat-app-frontend
cd chat-app-frontend
2. Install Socket.io Client
Install the Socket.io client library:
npm install socket.io-client
3. Create the Chat Component
Create a components/ChatComponent.js
file for the chat functionality:
// components/ChatComponent.js
import React, { useState, useEffect } from 'react';
import io from 'socket.io-client';
const backendServer = 'http://localhost:3001';
let socket;
const ChatComponent = () => {
const [messages, setMessages] = useState([]);
const [input, setInput] = useState('');
useEffect(() => {
socket = io(backendServer);
socket.on('message', (msg) => {
setMessages((prevMessages) => [...prevMessages, msg]);
});
return () => {
socket.disconnect();
};
}, []);
const sendMessage = (e) => {
e.preventDefault();
if (input.trim()) {
socket.emit('message', input);
setInput('');
}
};
return (
<div>
<h1>Chat Application</h1>
<div>
<h2>Messages:</h2>
<ul>
{messages.map((msg, index) => (
<li key={index}>{msg}</li>
))}
</ul>
<form onSubmit={sendMessage}>
<input
value={input}
onChange={(e) => setInput(e.target.value)}
placeholder="Type your message"
/>
<button type="submit">Send</button>
</form>
</div>
</div>
);
};
export default ChatComponent;
In this component:
- We establish a socket connection to the backend.
- We listen for messages and update the state accordingly.
- We handle user input and send messages to the backend when the form is submitted.
4. Integrate the Chat Component into Your Application
Modify src/app/page.js
to include the ChatComponent
:
/ src/app/page.js
import Head from 'next/head';
import ChatComponent from '../components/ChatComponent';
export default function Home() {
return (
<div>
<Head>
<title>Chat Application</title>
<meta name="description" content="Real-time chat application with Next.js and Express" />
<link rel="icon" href="/favicon.ico" />
</Head>
<main>
<h1>Welcome to the Chat App</h1>
<ChatComponent />
</main>
</div>
);
}
Conclusion
In this tutorial, we have created a simple real-time chat application using Express.js and Next.js. By setting up a Socket.io server and client, we facilitated real-time communication between users. This basic setup can be extended with features like user authentication, message persistence, and more sophisticated UI components.
Feel free to experiment and enhance the application according to your needs. Happy coding!