Real-time chat is one of the most popular features in modern applications, allowing users to communicate instantly. In this tutorial, weβll walk through how to implement a real-time chat app using Next.js with WebSockets.
WebSockets allow for two-way communication between the client and server, making them perfect for real-time features. Letβs dive into building this in Next.js! π
π οΈ Step 1: Setting Up a Next.js App
First, you need a Next.js app. If you donβt have one yet, you can set it up like this:
npx create-next-app@latest real-time-chat
cd real-time-chat
npm install
Now, we have a basic Next.js app ready.
βοΈ Step 2: Installing Socket.io
We'll use Socket.io to handle WebSockets. Install the necessary packages for both the client and server:
npm install socket.io socket.io-client
This will install the server-side Socket.io package and the client-side socket.io-client package.
π Step 3: Setting Up the Server-Side WebSocket in Next.js
Next.js uses its API routes to manage server-side logic, which is where weβll handle WebSocket connections.
- Create a new API route at
pages/api/socket.js
:
import { Server } from "socket.io";
export default function handler(req, res) {
if (!res.socket.server.io) {
console.log("Starting socket.io server...");
const io = new Server(res.socket.server);
res.socket.server.io = io;
io.on("connection", (socket) => {
console.log("User connected", socket.id);
socket.on("message", (msg) => {
socket.broadcast.emit("message", msg); // Send message to all except sender
});
socket.on("disconnect", () => {
console.log("User disconnected", socket.id);
});
});
}
res.end();
}
This API route initializes the Socket.io server when a client connects. It listens for message
events and broadcasts them to all other clients.
π» Step 4: Connecting the Client-Side WebSocket
Now, weβll set up the client-side connection to the WebSocket server. In your Next.js app, create a chat component in components/Chat.js
:
import { useEffect, useState } from "react";
import io from "socket.io-client";
let socket;
export default function Chat() {
const [message, setMessage] = useState("");
const [messages, setMessages] = useState([]);
useEffect(() => {
socket = io();
// Listen for messages from the server
socket.on("message", (msg) => {
setMessages((prev) => [...prev, msg]);
});
return () => {
socket.disconnect();
};
}, []);
const sendMessage = () => {
socket.emit("message", message); // Send message to server
setMessages((prev) => [...prev, message]); // Add your message to the chat
setMessage(""); // Clear input field
};
return (
<div>
<h1>Real-Time Chat</h1>
<div>
{messages.map((msg, index) => (
<div key={index}>{msg}</div>
))}
</div>
<input
value={message}
onChange={(e) => setMessage(e.target.value)}
placeholder="Type a message..."
/>
<button onClick={sendMessage}>Send</button>
</div>
);
}
This component handles the client-side logic:
- It connects to the Socket.io server.
- Sends and receives messages in real-time.
π Step 5: Update pages/_app.js
to Initialize WebSocket
To ensure the WebSocket server is initialized, we need to make a request to our API route when the app starts:
// pages/_app.js
import { useEffect } from "react";
import "../styles/globals.css";
function MyApp({ Component, pageProps }) {
useEffect(() => {
fetch("/api/socket"); // Initialize the WebSocket server
}, []);
return <Component {...pageProps} />;
}
export default MyApp;
By making a call to the api/socket
route in useEffect
, we ensure that the WebSocket server starts as soon as the app is loaded.
π§ͺ Step 6: Testing the Real-Time Chat
You can now test your chat app by running your Next.js development server:
npm run dev
Open multiple browser windows to http://localhost:3000
, and youβll see real-time communication between them! π₯³
π Conclusion
Using Next.js and Socket.io, we've built a simple real-time chat app. This setup allows you to extend the app with more features like user authentication, rooms, and more complex events.
WebSockets are incredibly powerful for any real-time feature in your apps. Whether it's a chat app, live notifications, or real-time collaboration, this setup provides a great starting point for real-time web applications.
π Additional Resources:
Feel free to experiment and add more advanced features to your chat app! What real-time feature are you planning to build next? Let me know in the comments! π¬
Top comments (3)
ππππππππππππππ
Can I collaborate?
Yeah, sure.