DEV Community

terrierscript
terrierscript

Posted on • Edited 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)
      },
    }
  },
})

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs