# Node.js 從 Pusher 遷移：保留 pusher 套件，只換主機

> 把 Express、Fastify、NestJS 或 Serverless 後端從 Pusher Channels 移走：只改一個建構式，授權和 Webhook 處理不用動，不中斷地切換。

Source: https://hibira.io/zh-tw/topics/migrate-from-pusher-nodejs
Updated: 2026-11-18

使用 Pusher Channels 的 Node.js 後端，會在 Express、Fastify、NestJS、Worker 或 Serverless 函式裡用 `pusher` 套件發佈。這個套件接受 `host` 選項，所以搬到相容 Pusher 的服務時，只要改一個建構式和背後的環境變數。觸發、授權處理和 Webhook 處理都不變，網頁或 React Native 應用裡的 pusher-js 也一樣。

## 哪些要改、哪些不用

| 應用的部分 | 要改嗎 | 怎麼做 |
| --- | --- | --- |
| `trigger()` 和 `triggerBatch()` | 不用 | 不用動 |
| 使用 `authorizeChannel()` 和 `authenticateUser()` 的授權處理 | 不用 | 不用動，簽章相同 |
| 用 `pusher.get()` 查詢頻道 | 不用 | 不用動 |
| `new Pusher({...})` | 要 | 把 `cluster` 換成 `host` |
| pusher-js 用戶端 | 要 | 加上 `wsHost` 和新的 Key |
| 允許的來源 | 新增 | 在應用登記你的網域；免費方案需要完整的來源網址 |

## 步驟 1：用戶端

```js
import Pusher from 'pusher';

export const pusher = new Pusher({
  appId: process.env.PUSHER_APP_ID,
  key: process.env.PUSHER_APP_KEY,
  secret: process.env.PUSHER_APP_SECRET,
  host: process.env.PUSHER_HOST ?? 'ws.hibira.io',
  useTLS: true,
});

await pusher.trigger('orders', 'order-shipped', { id: 1024 });
await pusher.triggerBatch([
  { channel: 'orders', name: 'order-shipped', data: { id: 1024 } },
  { channel: 'private-user-7', name: 'notice', data: { text: 'Shipped' } },
]);
```

一個批次最多 10 個事件。選項說明在 [pusher-http-node 的 README](https://github.com/pusher/pusher-http-node)，於 2026-11-18 確認。

## 步驟 2：在 Express 處理授權與 Webhook

```js
app.post('/pusher/auth', express.urlencoded({ extended: false }), requireUser, (req, res) => {
  const { socket_id, channel_name } = req.body;
  if (channel_name.startsWith('presence-')) {
    return res.json(pusher.authorizeChannel(socket_id, channel_name, { user_id: req.user.id, user_info: { name: req.user.name } }));
  }
  res.json(pusher.authorizeChannel(socket_id, channel_name));
});

app.post('/pusher/webhooks', express.raw({ type: 'application/json' }), (req, res) => {
  const webhook = pusher.webhook({ headers: req.headers, rawBody: req.body.toString('utf8') });
  if (!webhook.isValid()) return res.sendStatus(401);
  for (const e of webhook.getEvents()) console.log(e.name, e.channel);
  res.sendStatus(200);
});
```

Webhook 路由必須讀取原始內容：如果 JSON 解析器先執行，位元組會被改動，簽章就對不上了。

## 步驟 3：用戶端程式

瀏覽器和 React Native 裡的 pusher-js 都用同樣的選項：

```js
const client = new Pusher(PUSHER_KEY, {
  cluster: 'mt1',
  wsHost: 'ws.hibira.io',
  wsPort: 443,
  wssPort: 443,
  forceTLS: true,
  enabledTransports: ['ws', 'wss'],
  channelAuthorization: { endpoint: '/pusher/auth', transport: 'ajax' },
});
```

## 步驟 4：不中斷地切換

另外保留一個用舊憑證建立的 `Pusher` 用戶端，在用戶端更新的這一兩天同時發佈到兩邊。等 Pusher 後台看不到連線就移除它，並在新應用加上你的 Webhook 網址。

## 更多 Node.js 資源

[Node.js 指南](https://hibira.io/zh-tw/guides/node)把設定整理在一頁，[NestJS 套件](https://hibira.io/zh-tw/guides/nestjs)提供全域模組，附有頻道授權和 Webhook 的裝飾器。部署前可以用 [WebSocket 測試工具](https://hibira.io/zh-tw/tools/websocket-tester)在瀏覽器連線，檢查 Key、主機和頻道。

## 常見問題

### 需要換套件嗎？

不用。官方 `pusher` 套件加上 `host` 選項就能用，官方 pusher-js 用戶端也一樣，不需要額外安裝任何東西。

### 在 AWS Lambda 或其他 Serverless 函式裡能用嗎？

可以。每次觸發都是一個 HTTPS 請求，Node.js 能發請求的地方都能用。記得在函式結束前 await 這個 Promise，否則請求可能被中斷。

### 切換期間發佈的事件會怎樣？

如果同時發佈到兩個服務，每個用戶端都會從自己連著的服務收到每個事件一次。沒有這樣做的話，還連著 Pusher 的用戶端在重新載入前，會收不到只送往新服務的事件。

### 頻道和事件名稱的限制一樣嗎？

一樣。頻道名稱最長 164 個字元，同樣用前綴決定頻道類型。事件資料和 Pusher 一樣，通常是裝著 JSON 的字串。
