Introduction:
In this guide, we'll explore how to create a basic real-time chat application using Next.js and WebSockets. Real-time capabilities are essential for contemporary applications, and the combination of Next.js with WebSockets offers a powerful solution for building 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 } = require('socket.io');
const server = http.createServer((req, res) => {
// Handle HTTP requests if needed
});
const io = new Server(server);
io.on('connection', (socket) => {
console.log('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('User disconnected');
});
});
server.listen(3001, () => {
console.log('WebSocket server listening on port 3001');
});
Creating the Chat Interface
Update main page with following code in Next.js app:
// 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.
Top comments (2)
How would this setup handle user authentication if I wanted to add that feature? Great guide, by the way!
Thank you! This is just a basic example.
SocketIO has this good article for JWT auth that you can refer: socket.io/how-to/use-with-jwt