DEV Community

Cover image for Building a chat app with Socket.io and React 🚀

Building a chat app with Socket.io and React 🚀

Nevo David on August 15, 2022

Like this article? Follow me on X: https://x.com/nevodavid What is this article about? We have all encountered chat over the web, tha...
Collapse
 
nevodavid profile image
Nevo David

What should I write about next?

Collapse
 
joelbonetr profile image
JoelBonetR 🥇

You could fork the same project and just change the implementation details to "vanilla" websockets to see the differences with socket.io! 😁

Collapse
 
nevodavid profile image
Nevo David

It's good to understand vanilla websockets, but I don't think it's so practical 🤣
You would now use it in production most chances 🙈

Thread Thread
 
joelbonetr profile image
JoelBonetR 🥇

Hahaha it depends on the case, here I found a good TL; DR on that 😁

Thread Thread
 
nevodavid profile image
Nevo David

Don't forget that in socket.io they also implemented long polling for old browsers :)

Thread Thread
 
joelbonetr profile image
JoelBonetR 🥇 • Edited

The way socket.io actually works is by assuming those are AJAX requests and once some communications had been exchanged it switches the protocol, thus it's not a protocol downgrade but an upgrade (you can check that in the network tab of chrome dev tools), also check the link in the last comment for more details. Is it convenient?

Well, web sockets has a good browser support so It depends on the use case of this "workaround" being more or less harmful.

Also note that socket.io has 4 different versions and both client and server need to implement the same version as far as I can remember, hence as soon as v5 appears you'll need to provide both v4 and v5 versions to avoid current clients software breaking and to provide latest stable version for new customers or customers that want to migrate (thinking on the use-case of providing just a backend as service).

Thread Thread
 
sorindezzy profile image
Raita Dezideriu

Wooow dude that’s so very Amazing 98% ? That says a lots mate

Thread Thread
 
joelbonetr profile image
JoelBonetR 🥇

Basically any browser version released in 2012 or newer (more or less) except from Opera Mini which I don't even know why they keep adding it to the metrics 😅

Thread Thread
 
nevodavid profile image
Nevo David

It's true and not true, it's like saying that compare to the population of the world, you child will be chinese, it's most likely not true :)
So while it's true that if you target the whole world with your app that might be the case.
But try to do the same for old enterprise companies, and I promise you, you will find some Windows XP :D

Thread Thread
 
joelbonetr profile image
JoelBonetR 🥇

😂😂
Well, that it's compatible with any browser version released in 2012 or newer is absolutely true. Some people around the world using older versions is a completely different topic 😁

I'd rather prefer the connection to be tested with the "newest" protocol and downgrade it if there's any incompatibility instead doing the opposite. It will add a delay to people with very very old devices and software and speed up the rest.

My logic is that people with very very old devices and software are already used to the slowness 😳I know it by experience, had a Pentium II with a 56Kb modem for more than 10 years, on those waiting times 100-200ms won't harm much, it's a little % overall 😅

Collapse
 
pusoy profile image
Jmaglinte

Integrate *MongoDB * :D

Collapse
 
nevodavid profile image
Nevo David

Haha, that's a good idea!

Thread Thread
 
pusoy profile image
Jmaglinte

Thank you! can't wait for the next one.

Collapse
 
kumard3 profile image
Kumar Deepanshu

Trpc with next js

Collapse
 
radualexandrub profile image
Radu-Alexandru B

how to build a 3 paged app using Sanity.io and Next.js

Collapse
 
lexiebkm profile image
Alexander B.K.

I think I need to start writing a real-time app, so this article is interesting. Although I may have seen other real-time sample apps, this one still is still worth reading.

Collapse
 
nevodavid profile image
Nevo David

Thank you Alexander! In the next one I will continue this article on how to use Browser Notification on a new chat message, what do you think?

Collapse
 
sorindezzy profile image
Raita Dezideriu

Ya Da Best Mate well done 👍 I love 💕 your talent

Thread Thread
 
nevodavid profile image
Nevo David

Thank you Raita! How are you? :)

Collapse
 
lexiebkm profile image
Alexander B.K.

That is interesting too, but it would be better if you use standard Web API whenever possible, unless you think it will need specific library for that purpose.

Thread Thread
 
nevodavid profile image
Nevo David

What do you mean by "standard Web API whenever possible"? :)

Thread Thread
 
lexiebkm profile image
Alexander B.K.

Because you mentioned about browser notification, I searched in MDN if there was a tools for that purpose. So I mean like this one : developer.mozilla.org/en-US/docs/W...
Of course, you are free to use other tools, library you have found suitable for that purpose.

Thread Thread
 
nevodavid profile image
Nevo David

It will probably be "web-push" library that wraps all those tools

Thread Thread
 
lexiebkm profile image
Alexander B.K.

Nice, I am waiting for that.
Actually, I also want to see how you handle global state management if there are cases for that. Specifically, how you use Redux, because I am learning Redux with the recommended way mentioned in the Redux doc, i.e using Redux Toolkit (RTK) and RTK Query.
But it is just fine if you don't use it in that app.

Thread Thread
 
nevodavid profile image
Nevo David

Anything specific you would like to build with Redux?

Thread Thread
 
lexiebkm profile image
Alexander B.K.

In my last project, I didn't use it, because I didn't learn it, it would take longer time before I could really use it. For global state management, I used a lib named reactN by Charles Stover which was easy to use.
But now that I realize in what case Redux is suitable for, I think I am going to use it for my nearest project.

Collapse
 
topninja profile image
Michael

Hi, novu team.
This is so great.
I also checked your packages on github, 7.3k stars - so amzing.
Btw I want to know about nove.co platform's pricing.
This is free platform? I signed on platform but there's no payment setup.

Collapse
 
nevodavid profile image
Nevo David

Hi Michael! We are currently on an open beta, we will introduce pricing very soon :)

Collapse
 
renanfranca profile image
Renan Franca • Edited

Could it be self hosted for free at heruko?

Thread Thread
 
nevodavid profile image
Nevo David

Not sure about Heruko, but I imagine you can.
It uses Mongodb, Redis :)
Try and let me know if it works for you!

Collapse
 
sachinchaurasiya profile image
Sachin Chaurasiya

This is amazing, thanks for sharing @nevodavid

Collapse
 
nevodavid profile image
Nevo David

Thank you Sachin!
Are you planning on building one? :)

Collapse
 
sachinchaurasiya profile image
Sachin Chaurasiya

Yes , planning to build one in this weekend:)

Collapse
 
minaprogrammer profile image
MinaProgrammer • Edited

useEffect(() => {
socket.on('messageResponse', (data) => setMessages([...messages, data]));
}, [socket, messages]);
You put messages is an array that maybe cause an infinite loop

useEffect(() => {
socket.on('messageResponse', (data) => setMessages(mess=>[...mess, data]));
}, [socket]);

Collapse
 
nevodavid profile image
Nevo David

If you are building a chat app, make sure you post it here?

Collapse
 
sorindezzy profile image
Raita Dezideriu

Could you tell me what really difference is between Facebook chat Messenger and your Chat that you just created please ?

Collapse
 
nevodavid profile image
Nevo David

A lot, but I can't tell you for sure as I don't know the facebook architecture.
But for starter, they are probably using a database 😅

Collapse
 
iamndeleva profile image
iamndeleva

Great article Nevo

Collapse
 
nevodavid profile image
Nevo David

Thank you, iamndeleva!
How are you? :)

Collapse
 
iamndeleva profile image
iamndeleva

I'm doing good ! Actually building similar chat application only that I'm incorporating a database and messaging will depend on whether the user is authenticated or not

Collapse
 
murtuzaalisurti profile image
Murtuzaali Surti

this is awesome! I might build one in the future, and might use novu as a notification system!! 👀

Collapse
 
nevodavid profile image
Nevo David

Haha that would be cool!
Maybe we can collaborate on a project :)

Collapse
 
sorindezzy profile image
Raita Dezideriu

Wooow

Thread Thread
 
sorindezzy profile image
Raita Dezideriu

Indeed love 💕 it very much it can be somehow Unicorn 🦄 you know !!

Collapse
 
joelbonetr profile image
JoelBonetR 🥇

Nice one! Liked reading that post, recommending it right now 👌😁

Collapse
 
nevodavid profile image
Nevo David

Thank you very much Joel!

Collapse
 
nevodavid profile image
Nevo David

Hi Everybody!
I have released the second part here:
dev.to/novu/building-a-chat-browse...

Collapse
 
kings5660 profile image
Kingsley

Super project. Thank you for posting. Tremendous work

Collapse
 
nevodavid profile image
Nevo David

Thank you Kingsley, feel free to fork it :)

Collapse
 
nevodavid profile image
Nevo David

Did you build your native chat in your app, or used something like intercom?

Collapse
 
nevodavid profile image
Nevo David

Just a quick reminder if you can help me out with a star on Novu ❤️❤️❤️❤️
github.com/novuhq/novu

Collapse
 
godwin_nj profile image
Amadi Godwin

Thanks for this , it was really helpful .

while building, if you want to remove user name that's typing on the body of that chat, setup another event with an empty string as its data , listen on both ends

 useEffect(() => {
    socket.on("typingResponse", (data) => setTypingStatus(data));
    setTimeout(() => {
      socket.on("noTypingResponse", (data) => setTypingStatus(data));
    }, 5000);
  }, [socket]);
Enter fullscreen mode Exit fullscreen mode
Collapse
 
kevinguo profile image
Kevin Guo

Scaling Socket.IO apps on Azure. 🥳⚡️📣
Azure now officially supports Socket.IO. No more deploying and managing "adapter" component on the server side. Simplified architecture for the happy developer.Learn more about Socket.IO on Azure

Collapse
 
victoria_mostova profile image
Victoria Mostova

Thanks for sharing your article on building a chat app with Socket.io and React! Your detailed walkthrough and code examples make it easy to understand how to make a messaging app with these technologies. It's a valuable resource for developers looking to implement real-time chat functionality in their projects.

Collapse
 
andrewbaisden profile image
Andrew Baisden

Superb article thanks for sharing! Socket.io and React is a good combination.

Collapse
 
johnruss profile image
JohnRuss

hi everyone 🖐
i have a question about where i can host express socket.io app ?
as i find out i can't on vercel or netlify. One another choise was heroku but heroku has ephemeral fs disk storage when i need persisted one. At this point i'm reading about "render" where i can buy persisted disk storage and i think it even supports socket.io 😎
So have anyone any advice ?

Collapse
 
dollieperry profile image
DolliePerry
Collapse
 
jurrevandenberg profile image
Raccoon

Thank you for the great article. I have one question. When someone is typing it shows the message but I can't figure out how to remove the is typing when the person isn't typing. Do you have an idea?

Collapse
 
shpinat479 profile image
AlexanderShpilka • Edited

I just did this:

useEffect(() => {
    const timer = setTimeout(() => {
      if (typingStatus) {
        setTypingStatus('')
      }
    }, 3000)

    return () => {
      clearTimeout(timer)
    }
}, [typingStatus])
Enter fullscreen mode Exit fullscreen mode
Collapse
 
khushbu11web profile image
Khushbu11-web

Hello, In server side (index.js) please correct http.listen otherwise server is not getting socket.ID

Collapse
 
dahaldiwash2 profile image
Diwash Dahal

Well written article, Nevo.
Very insightful

Collapse
 
fabriciooak profile image
Fabricio Carvalho

I tried to replicate this on Vue 3 and is working good!

Collapse
 
devangtomar profile image
Devang Tomar

Great content.. thanks for sharing 🙌

Collapse
 
shrns profile image
sharans

Well, the explanation is quite amazing, it took only 30 min to build the app as u gave me all the resources and stuff, I signed in to this site especially to thank you

Collapse
 
kasiviswanadh119 profile image
Kasi Viswanadh Duvva

Can i get live link

Collapse
 
khushbu11web profile image
Khushbu11-web

I am getting this error and I can not find a solution for this :
Uncaught TypeError: Cannot read properties of undefined (reading 'on')

Collapse
 
charumehta0215 profile image
charumehta0215

Wow! Its so amazing.

Collapse
 
mainakkaniam profile image
Mainak Mukherjee

thanks sir , you were really a lifesaver

Collapse
 
sonvu profile image
Sơn Vũ

ádasdsad

Collapse
 
ministryofjavascript profile image
Ministry of JavaScript

Anyone wants me to create a video series on it? Btw great post.

Collapse
 
bui378 profile image
Alain

This is very useful example to integration websocket.

Collapse
 
sugandi06 profile image
sugandi06

what if i use laravel for ther server and the client is react js? is it possible?

Collapse
 
iasadkhan profile image
Asad

Hey, its an awesome project and I learned a lot, just needed to ask what if I want to deploy it and test with my friends? where should I deploy the server?

Collapse
 
blaze_26 profile image
Blaze

Please I want to get the direct source code link for download.