Table of contents
No headings in the article.
In this tutorial, we will be building a chat app using Next.js, a popular framework for building server-rendered React applications. This chat app will allow users to send messages to each other in real-time, and will also feature a list of online users.
Before we get started, make sure you have the following tools installed on your machine:
Node.js
npm (which comes with Node.js)
Next.js
Once you have these tools installed, let's create a new Next.js project by running the following command in your terminal:
npx create-next-app my-app
This will create a new directory called my-app
with the basic structure of a Next.js app.
Next, let's install the dependencies we will be using for our chat app. We will be using Socket.io for real-time communication, as well as Express for our server. Run the following command to install these dependencies:
npm install socket.io express
Now that we have all the necessary dependencies, let's start building our chat app.
First, we need to create a server that will handle the real-time communication between clients. In the root of your project, create a file called server.js
and add the following code:
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);
server.listen(3000, () => {
console.log('Server listening on port 3000');
});
This code creates an Express server and sets up Socket.io to work with it. The server is then started on port 3000.
Next, let's create a page for our chat app. In the pages
directory of your Next.js project, create a file called chat.js
. This will be the entry point for our chat app.
In chat.js
, add the following code:
import { useEffect } from 'react';
import io from 'socket.io-client';
const Chat = () => {
useEffect(() => {
const socket = io('http://localhost:3000');
}, []);
return (
<div>
<h1>Chat App</h1>
</div>
);
};
export default Chat;
This code imports the useEffect
hook from React and sets up a connection to our Socket.io server.
Now that we have a basic setup for our chat app, let's add some functionality. We will start by displaying a list of online users. To do this, we will need to keep track of the users that are connected to our Socket.io server.
In server.js
, add the following code:
let users = [];
io.on('connection', (socket) => {
console.log('New user connected');
// Add new user to the list of users
users.push(socket.id);
io.emit('updateUsers', users);
// Remove user from the list of users when they disconnect
socket.on('disconnect', () => {
console.log('User disconnected
We will continue with building the chat app in the next part.
Thanks.