2024-04-16
2219
#nextjs
Doğacan Bilgili
90502
Apr 16, 2024 ⋅ 7 min read

Implementing WebSocket communication in Next.js

Doğacan Bilgili A software developer who is also into 3D-modeling and animation.

Recent posts:

Rxjs Adoption Guide: Overview, Examples, And Alternatives

RxJS adoption guide: Overview, examples, and alternatives

Get to know RxJS features, benefits, and more to help you understand what it is, how it works, and why you should use it.

Emmanuel Odioko
Jul 26, 2024 ⋅ 13 min read
Decoupling Monoliths Into Microservices With Feature Flags

Decoupling monoliths into microservices with feature flags

Explore how to effectively break down a monolithic application into microservices using feature flags and Flagsmith.

Kayode Adeniyi
Jul 25, 2024 ⋅ 10 min read
Lots of multi-colored blue and purplish rectangles.

Animating dialog and popover elements with CSS @starting-style

Native dialog and popover elements have their own well-defined roles in modern-day frontend web development. Dialog elements are known to […]

Rahul Chhodde
Jul 24, 2024 ⋅ 10 min read
Using Llama Index To Add Personal Data To Large Language Models

Using LlamaIndex to add personal data to LLMs

LlamaIndex provides tools for ingesting, processing, and implementing complex query workflows that combine data access with LLM prompting.

Ukeje Goodness
Jul 23, 2024 ⋅ 5 min read
View all posts

23 Replies to "Implementing WebSocket communication in Next.js"

  1. Great article! Works great on localhost. I seem to be stuck at deployment though. I assume that since serverless solutions such as Vercel cannot run this then either can netlify or amplify etc? Right? What would be a good hosting solution for a nextjs app that uses socket.io like how you have outlined here?

      1. I had a website on vercel. I was trying to do that. As you said it works locally but it was not working on prod. :/ It seems heroku is different but I do not want to move my project there. I wish Vercel provide us the same thing :/

        1. That’s because Vercel runs serverless functions; they’re not meant to run 24/7 nor are they a single instance (they scale up and down). You need a custom server if you want to do WebSockets, and Vercel doesn’t support hosting custom servers.

          Next.js is good for handling requests and sending responses, if you want to do WebSockets, use a 3rd party service like Pusher or host your own solution beside Next.js.

    1. Thanks for your comment. Since Socket.io is built on top of the WebSocket protocol, we don’t feel the title is inaccurate or misleading.

      1. It is misleading because when searching for information about the ‘ws’ package (aka WebSocket) one gets this article, which talks about Socket.IO. The API offered by the 2 packages are different so this article is misleading.

  2. apparently it doesn’t like the wrapping of the socketInitializer function. I get the following:

    Warning: useEffect must not return anything besides a function, which is used for clean-up.

    It looks like you wrote useEffect(async () => …) or returned a Promise. Instead, write the async function inside your effect and call it immediately:

    useEffect(() => {
    async function fetchData() {
    // You can await here
    const response = await MyAPI.getData(someId);
    // …
    }
    fetchData();
    }, [someId]); // Or [] if effect doesn’t need props or state

    also, the Google and Twitter login mechanisms on this site are broken

  3. this is not working in my localhost, first i’ve write the codes that not worked, then i’ve copy all codes and paste , that not works too….

  4. Thank you for the article

    I’m struggling to see *why* this is working though (even though I can see that it does).

    According to Next-JS, the res object is a `http.ServerResponse` object. This does indeed contain a `socket` which is a `net.Socket object` (https://nodejs.org/api/net.html#class-netsocket).

    The documentation never mentions a `server` property on `net.Socket` though. where is that coming from? Why isn’t it documented in Node, how did you figure out it exists, why is Typescript also denying it exists? etc. etc.

    I’m happy it works, but it feels weird to use something that (as far as I can see) is an undocumented hidden feature 🙂

  5. Could you explain the lifecycle of the API route? From my understanding each client will have a separate response object, thus a separate SocketIO instance? For how long will it stay active?

    Seems to me if I wish to do client-client communication I will need a customer server.

    “`
    const SocketHandler = (req, res) => {
    if (res.socket.server.io) {
    console.log(‘Socket is already running’)
    } else {
    console.log(‘Socket is initializing’)
    const io = new Server(res.socket.server)
    res.socket.server.io = io
    }
    res.end()
    }
    “`

    1. You are correct. I left a comment above where I explain that yes, you need a custom server to handle this. Also, WebSockets won’t let you set up P2P/client-client communication, you can look into WebRTC for that.

  6. This isn’t working, I keep getting a 404 localhost:3000/socket.io?EIO=4&transport=polling&t=OWzE3BU 404 (N

Leave a Reply