官方套件 · 自動化與基礎架構

為即時 Next.js 應用打造的 Vercel 整合

在 Vercel 專案加入 Hibira 整合並選擇(或建立)一個 app,它的 app ID、金鑰、密鑰與主機就會以環境變數加進專案。重新部署後,從 route handler 發布事件,用 pusher-js 訂閱。

  • 寫入 HIBIRA_APP_ID、HIBIRA_APP_KEY、HIBIRA_APP_SECRET、HIBIRA_HOST、HIBIRA_CLUSTER,以及給瀏覽器用的 NEXT_PUBLIC_HIBIRA_APP_KEY、NEXT_PUBLIC_HIBIRA_HOST,套用到 Production、Preview 與 Development。
  • 新建的 app 會接受各專案 .vercel.app 網域的連線。自訂網域與預覽網址請到 app 頁面的 Allowed origins 加入。
  • Next.js 範例的 Deploy with Vercel 按鈕會一併安裝這個整合,複製的 demo 不用手動複製金鑰就能跑。

登入後,範例程式碼會自動帶入您的叢集主機。 登入

  1. 安裝

    https://vercel.com/integrations/hibira/new
      → Add Integration → pick a team and its projects
      → sign in to Hibira → pick an app or create one → Connect
    Redeploy the projects so they load the new variables.
  2. 從 route handler 發布

    // app/api/orders/route.js
    import Pusher from 'pusher';
    
    const pusher = new Pusher({
      appId: process.env.HIBIRA_APP_ID,
      key: process.env.HIBIRA_APP_KEY,
      secret: process.env.HIBIRA_APP_SECRET,
      host: process.env.HIBIRA_HOST,
      useTLS: true,
    });
    
    export async function POST(req) {
      const order = await req.json();
      await pusher.trigger('orders', 'order.created', order);
      return Response.json({ ok: true });
    }
  3. 使用

    'use client';
    import Pusher from 'pusher-js';
    
    const pusher = new Pusher(process.env.NEXT_PUBLIC_HIBIRA_APP_KEY, {
      cluster: 'hkg',
      wsHost: process.env.NEXT_PUBLIC_HIBIRA_HOST,
      forceTLS: true,
      enabledTransports: ['ws', 'wss'],
    });
    
    pusher.subscribe('orders').bind('order.created', (order) => {
      console.log('New order', order);
    });

開始之前

  • 變數在連接時寫入。之後若輪替 app 密鑰,請到專案設定更新 HIBIRA_APP_SECRET 並重新部署。
  • 只從伺服器程式(route handler、server action)發布;HIBIRA_APP_SECRET 絕不能進到用戶端元件。

請使用儀表板中的應用程式 Key;Secret 只放在你的伺服器上。頻道、事件與授權端點的用法和 Pusher 完全相同。 免費建立帳號 →