DEV Community

terrierscript
terrierscript

Posted on • Updated on

Subscribe Pusher on the node environment

Pusher is great pub/sub service.

Basically, we need to subscribe pusher with pusher-js, and this library has node platform.
When we need private/presence channel, we need authorize with pusher-http-node.

Problem

Sometimes we need to subscribe private channel on node server.

Pusher have webhooks, but we can't detect only one endpoint in the some case (like IoT, edge device etc...)

Solution

pusher-js client can custom authorizer.
We can create self-auth authorization client.

const Pusher = require("pusher-js/node")
const PusherServer = require("pusher")
const uuid = require("uuid")


const pusherServer = new PusherServer({
  appId: PUSHER_APP_ID,
  key: PUSHER_KEY,
  secret: PUSHER_SECRET,
  cluster: "ap3",
  encrypted: true,
})
// Pusher.logToConsole = true
const pusher = new Pusher(PUSHER_KEY, {
  cluster: "ap3",
  authorizer: (channel) => {
    return {
      authorize: (socketId, callback) => {
        const auth = pusherServer.authenticate(socketId, channel.name, {
          user_id: `server-${uuid.v4()}`, // we require userId when presence channel
        })
        callback(false, auth)
      },
    }
  },
})

Top comments (0)