Skip to content

Listning to incoming events #11

@Igal-Kleiner

Description

@Igal-Kleiner

A client needs to send socket events to the server and the server has to listen to the incoming events. Socket.io implements the following methods: .on, .once, off, removeAllListeners. In Strapi v3 I was able to use them as follows:

const io = require('socket.io')(strapi.server, {
  // optional config
})

io.on('connection', function(socket) {
  socket.on('someCommand', () => {
    // ...do something here
  })
})

Alas, it is no longer possible with v4. And the StrapIO plugin currently doesn't support this much needed functionality.

I tried the solution you suggested in your Discord channel:

process.nextTick(() => {
  const _strapio = (require("strapio"))(strapi, {
    cors: { origin: "*", methods: ["GET", "POST"] },
  });

  _strapio.io.on('connection', () => {
    console.log('user connected')
  })

  strapi.io = _strapio.io
})

But getting this error: TypeError: Cannot read property 'on' of undefined. There's no io property on the object returned by the plugin.

Metadata

Metadata

Assignees

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions