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:

react native's new architecture: sync and async rendering

React Native’s New Architecture: Sync and async rendering

React Native’s New Architecture offers significant performance advantages. In this article, you’ll explore synchronous and asynchronous rendering in React Native through practical use cases.

Emmanuel John
Dec 24, 2024 ⋅ 8 min read
Building a Full-Featured Laravel Admin Dashboard with Filament

Building a full-featured Laravel admin dashboard with Filament

Build scalable admin dashboards with Filament and Laravel using Form Builder, Notifications, and Actions for clean, interactive panels.

Kayode Adeniyi
Dec 20, 2024 ⋅ 5 min read
Working With URLs In JavaScript

Working with URLs in JavaScript

Break down the parts of a URL and explore APIs for working with them in JavaScript, parsing them, building query strings, checking their validity, etc.

Joe Attardi
Dec 19, 2024 ⋅ 6 min read
Lazy Loading Vs. Eager Loading

Lazy loading vs. Eager loading

In this guide, explore lazy loading and error loading as two techniques for fetching data in React apps.

Njong Emy
Dec 18, 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