[v4] Strapi and socket.io

System Information
  • Strapi Version: 4.0.2
  • Operating System: Win10
  • Database: PostgreSQL

In v3 I followed this guide to connect socket.io to Strapi and it worked great. Now I try to adapt it to v4. Since I can’t use ./config/functions/bootstrap.js file any more, I thought I have to put the relevant code in ./src/index.js file, in side bootstrap() method. And that was the content of my file:

module.exports = {

  register(/*{ strapi }*/) {},

  bootstrap({ strapi }) {
    const io = require('socket.io')(strapi.server, {
      cors: {
        origin: 'http://localhost:3000',
        methods: ['GET', 'POST'],
        allowedHeaders: ['my-custom-header'],
        credentials: true
      }
    })
    
    io.on('connection', function(socket) {
      // ...rest of the code
    })

    strapi.io = io
  },
};

And my app crashed with this error: TypeError: server.listeners is not a function I tried to do it with setTimeout, with process.nextTick() - always the same result, same error.

So how do I do it? How do I connect socket.io to Strapi and have the io property on the strapi object?

i need this too, but unable to get it working

I had the same problem, but figured it out by looking at this: strapio/index.js at 2a1b465c06a25c3ad5afb82d08185dc65f4b6b4b · larsonnn/strapio · GitHub

Add .httpServer to the end of strapi.server

const io = require('socket.io')(strapi.server.httpServer);

Wow, thanks so much! Looks like it worked!

I tried adding httpServer but it is not working