How sockets work, what you can do with them, and how to implement functionality with NextJS
There is always something else you can add to your application. Maybe you have created a beautiful dashboard but you don’t want your user to refresh the site every time something new happens.
You might want to send a notification when a new message is present. Maybe you’ve always wanted to make a multiplayer real-time game like agar.io.
the possibilities are endless. But for different types of endeavor, you need different sets of tools. In this article I will walk you through the essential steps that you need to take to build a chat application in real time:
If you’re more comfortable working with the code, here it is: github project,
Unless you’re a Linux programmer, there really isn’t much value in knowing all the principles down to sockets, so let’s not dive down the rabbit hole. I am here to give you everything you need so that you can start creating great applications. Sooooo.. what is a socket?
A socket is an endpoint of communication between 2 devices. That is a definition. In my opinion, the easiest way to understand what sockets actually gives us is to compare it to non-socket communication.
Client-server (one-way) communication
Most communication over the Internet in the modern web is of a client-server type – most APIs, and websites work in much the same way. What client-server communication really means is that the client has to ask the server to get an answer. The server has no way of initiating that communication so the server can’t really notify a user about any events.
socket (dual way) communication
In socket communication, once this is established both parties are free to send messages to each other. There is no need to initiate communication after its installation. Now the server can notify the user about the new message, and the user can react to it. In that scenario the communication is based on events.
To set up dual-side communication, we need a server and a client. Since we are using NextJS, our server-side will be placed in the NextJS API folder, while the client-side will be coded into each page that will need it. So overall, we will have one server (it is possible to have more than one server if the traffic is heavy) and one connection per client. Let’s start with the server-side.
socket server code
socket.tsx file in api folder. Since the NextJS API folder acts as a server, we will need to install one here. We check if socket connection is already established
res socket property. Basically, we want to create one server instance for the entire app. As you can see before, we check if the server.io property exists, if so it means we already have a server. If not, we create a new one, and later, we assign the emit handler which I’ll show you in the next step.
It’s worth noting that although we can create events with almost any name, there are some special ones. “Connection” is one of them. There are others like: “connect-error”, “disconnected”, etc. You can see the full list in the document,
Setting separate event handlers on the connection is the right place to do it, as we have to make sure the socket exists, and call the callback function only after the socket is created.
Although you can make all event handlers
onConnection We will do it keeping in mind the clean architecture. Since we only have one event that won’t change much, but if you will have a lot of them it will allow you to structure it well and group them by different functionalities for example. The message handler looks like this:
As you can see the convention is to first define the handlers at the top, and second to assign them to the correct events. This code means that if the client will send
createdMessage The event will be handled by its similarly named functio️n.
That’s all when it comes to server side. Now let’s focus on the client.
All client code is kept in just one file:
index.tsx, We create a global socket variable so that it is not rewritten every time, then we create a message type and set something like
useState value. So far, so good. In
socketInitializer Celebration. Since we are using NextJS API as a server, we need to fetch (
/api/socket) endpoint that will trigger the logic we created in the previous step. This is necessary because in order for a client to connect to the server we must first ensure that the server exists.
Afterwards, we assign an instance of io, assign it to the socket, and create an event listener.
Since we’ve already created a socket server, client, as well as event handlers, fire an event when the user wants to send a message. If you want to notify the other side of the communication pipe you need to call the emit method, where the first parameter is the name of the event, and all of the following are arguments to the callback function. You can have as many as you want, just remember to specify them in the function declaration.
In this particular scenario, we also add the message to our message array that we are displaying in the chat. This is because it doesn’t really make much sense to send it to the server first and then back to the client when we can save it right away. This brings us to the next topic:
Since there are many different possibilities for using socket.io, there are also many different ways to send events. you can
emit For all clients except the sender (like in the example above), you can do
broadcast To include the sender of it, or you can just send it to one room (yes you can have rooms there). You should of course know what you can use, and socket.io has A great cheat sheet in their documentation.
The last part of this tutorial is defining the front end, and it’s pretty simple. We simply iterate over the messages array, display all messages, and send a message if the user presses the send button or the enter key, which you achieve by doing:
Overall the frontend code looks like this:
as you can see
socket.io It’s not scary, and it’s super powerful. It allows you to create interactive real-time dashboards, multiplayer games, and more. In two words, it allows you to build more dynamic websites.
If you want to dive further you can either subscribe to my newsletter, for the next parts of the series, or dive straight into documentation,
feel free to hold me Twitter,
and here is one github repo,
have a nice day.
#Build #realtime #chat #application #Socket.io #NextJS #Szymon #Kolber #July