Skip to content

createAdapter(pubClient, subClient) breaks subClient.connect(): "Error: Cannot send commands in PubSub mode" #436

Closed
@akifd

Description

@akifd

package.json

    "@socket.io/redis-adapter": "7.1.0",
    "redis": "4.0.1",
    "socket.io": "4.4.0"

The Redis itself is running in Docker with the image redis:6.2.6-alpine3.15.

Here is the code that doesn't work for some reason:

import { Server } from 'socket.io'
import { createClient } from 'redis'
import { createAdapter } from '@socket.io/redis-adapter'

const io = new Server()
const pubClient = createClient({url: `redis://redis:6379/1`})
const subClient = pubClient.duplicate()

io.adapter(createAdapter(pubClient, subClient))

Promise.all([pubClient.connect(), subClient.connect()]).then(() => {
  io.listen(9003)
  console.log('Listening on port 9003...')

  async function redisTest() {
    await subClient.subscribe('channel', (message) => {
      console.log('Received message', message)
    })
    await pubClient.publish('channel', 'Hello')
    await pubClient.publish('channel', 'World!')
  }
  redisTest()
})

The code gives me the following error:

/code/node_modules/@node-redis/client/dist/lib/client/commands-queue.js:68
            return Promise.reject(new Error('Cannot send commands in PubSub mode'));
                                  ^

Error: Cannot send commands in PubSub mode
    at RedisCommandsQueue.addCommand (/code/node_modules/@node-redis/client/dist/lib/client/commands-queue.js:68:35)
    at RedisSocket.socketInitiator (/code/node_modules/@node-redis/client/dist/lib/client/index.js:304:81)
    at RedisSocket._RedisSocket_connect (/code/node_modules/@node-redis/client/dist/lib/client/socket.js:122:77)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async Commander.connect (/code/node_modules/@node-redis/client/dist/lib/client/index.js:156:9)
    at async Promise.all (index 1)

If I remove the line io.adapter(createAdapter(pubClient, subClient)), it starts working again:

Listening on port 9003...
Received message Hello
Received message World!

If I remove the subClient.connect(), but leave the adapter, it doesn't crash, but I obviously won't receive the published messages:

Listening on port 9003...

Do I just need to downgrade some packages or why might I have this problem? It feels like the README is using outdated packages, as an example, the Redis createClient now takes the url option instead of the host and port mentioned in the README.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions