I want to share a simple chat application that I've made using next js and socket-io.
To achieve this I've used Next.js and Socket.IO.
Next.js is a framework that most notably allows us to write server-rendered React apps easily.
First step : creating the next application.
The command : npx create-next-app (we choose the name of app )
In next js we just need to add a file in pages folder to have all the routing stuff ....
We modify the existing file index.js.
firstly we import the necessary libraries
In this work I've used functional components, much easier and more fun than class components, so we create the App component, we define some states that we need later.
1) a state to save the connected user list.
2) a state to save the message that we send.
3) a state to save the received messages.
After that we create the basic functions for communication between clients and server.
For each new client do :
1) in a useEffect hook we emit a login event to the server.
2) the server says:"Hi", and he sends the list of logged clients and also returns some information of the logged client such as socket_id.
Every client can send messages to all the users by emitting sendMsg event.
finally we render the connected users and an input to send messages.
that's all for the front part, we move to the second one which is the server and the event management.
we create a simple node server.
the mission of the server is to respond to all the events which come from the clients.
We use an array to save the user information (a real database for serious things is more suitable)
We manage the connection and disconnection events by adding or removing the client from the clients array respectively.
When the server catch the SendMsg event, it broadcast it to all the logged client (we can create rooms if we want more control or just emit it to a specific client by passing his socket id)
The git repo :
In the root folder there are two folders :D
The first folder : socket-io-server
It contains the io socket server. in order to run the server, run the commands bellow :
- npm install
- npm start
The second folder : NextChat
It contains the next js chat application. In order to run the application, run the commands bellow :
- npm install
- npm run dev
- Go to : http://localhost:9000 (by default)
NextChat is a simple react-based chat application. Each client join the chat can send messages to the other members. The library Socket.IO is used for bi-directional communication between clients. Enjoy.
to see the final result, please click here : NextChat
Thanks for reading.