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:

How To Use Lazy Initialization Pattern With Rust 1.80

How to use the lazy initialization pattern with Rust 1.80

Efficient initializing is crucial to smooth-running websites. One way to optimize that process is through lazy initialization in Rust 1.80.

Yashodhan Joshi
Nov 18, 2024 ⋅ 5 min read
React logo on a bubbly orange background. Guide on building adaptive and responsive UIs in React Native for diverse devices.

Creating adaptive and responsive UIs in React Native

Design React Native UIs that look great on any device by using adaptive layouts, responsive scaling, and platform-specific tools.

Chinwike Maduabuchi
Nov 15, 2024 ⋅ 9 min read
Enhancing Two-Way Data Binding In Angular

Enhancing two-way data binding in Angular

Angular’s two-way data binding has evolved with signals, offering improved performance, simpler syntax, and better type inference.

Alexander Godwin
Nov 14, 2024 ⋅ 6 min read
Hand holding purple sticky notes for CSS sticky positioning guide.

Troubleshooting CSS sticky positioning

Fix sticky positioning issues in CSS, from missing offsets to overflow conflicts in flex, grid, and container height constraints.

Ibadehin Mojeed
Nov 13, 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