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:

Using Pavex For Rust Web Development

Using Pavex for Rust web development

The Pavex Rust web framework is an exciting project that provides high performance, great usability, and speed.

Ukeje Goodness
May 10, 2024 ⋅ 6 min read
Using The Resizeobserver Api In React For Responsive Designs

Using the ResizeObserver API in React for responsive designs

With ResizeObserver, you can build aesthetic React apps with responsive components that look and behave as you intend on any device.

Emmanuel Odioko
May 9, 2024 ⋅ 11 min read
Creating JavaScript Tables Using Tabulator

Creating JavaScript tables using Tabulator

Explore React Tabulator to create interactive JavaScript tables, easily integrating pagination, search functionality, and bulk data submission.

Emmanuel John
May 9, 2024 ⋅ 7 min read
How To Create Heatmaps In Javascript: Exploring The Heat Js Library

How to create heatmaps in JavaScript: The Heat.js library

This tutorial will explore the application of heatmaps in JavaScript projects, focusing on how to use the Heat.js library to generate them.

Oghenetega Denedo
May 8, 2024 ⋅ 7 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