← すべてのガイド

プッシュ通知

プッシュ通知の導入ガイド

Hibira Push で iOS、Android、ブラウザに通知を送れます。API は Beams 互換で、公式の Beams サーバー SDK はエンドポイントを指定するだけで動作し、当社のクライアント SDK はホストを設定できるようにした Beams SDK のフォークです。

サインインすると、スニペットが自分のエンドポイントに置き換わり、アプリのページではインスタンス ID も入ります。 サインイン

仕組み

  • ポータルのアプリのページでプッシュ通知をオンにすると、インスタンス ID、シークレットキー、エンドポイントが発行されます。
  • 各デバイスやブラウザはクライアント SDK で登録し、news や order-1024 のようなトピックであるインタレストを購読します。サーバーはインタレストに配信し、デバイスがサインイン中のユーザーにひも付いていればユーザー ID にも配信できます。
  • インスタンス ID とエンドポイントはアプリに入れます。シークレットキーはすべてのデバイスに配信できるため、サーバーの環境変数 HIBIRA_PUSH_SECRET_KEY にだけ置き、アプリやリポジトリには入れないでください。
  • プッシュはすべてのプランに含まれます。プランによって、登録できるデバイスとブラウザの数と配信の速さが決まります。

1. 認証情報をアップロード

Apple(APNs)
Apple Developer の Certificates, Identifiers & Profiles › Keys で、Apple Push Notifications service(APNs)を有効にしたキーを作成し、.p8 ファイルをダウンロードします。アプリのページの「プッシュ通知 › Apple(APNs)」で、キー ID、チーム ID、アプリのバンドル ID を入力し、環境を選んで .p8 ファイルをアップロードします。 Xcode から実行するビルドには「開発(サンドボックス)」、TestFlight と App Store のビルドには「本番」を選んでください。
Android(FCM)
Firebase コンソールで「プロジェクトの設定 › サービス アカウント」を開き、「新しい秘密鍵を生成」をクリックします。JSON ファイルを「プッシュ通知 › Android(FCM)」にアップロードし、同じプロジェクトの google-services.json を Android アプリに追加します。
Web Push
アップロードは不要です。VAPID キーはプッシュをオンにしたときに作成されます。サイトは HTTPS で配信する必要があります(開発中は localhost で動作します)。

キーとサービスアカウントは暗号化して保存され、二度と表示されません。

2. デバイスとブラウザを登録

クライアント SDK

プラットフォーム

Chrome、Edge、Firefox、Opera、Safari 16.4 以降に、標準の Web Push と Service Worker で配信。 @hibira-io/push-web ↗

  1. インストール

    npm install @hibira-io/push-web
  2. Service Worker を追加

    // public/service-worker.js, served at https://your-site/service-worker.js
    importScripts('https://cdn.jsdelivr.net/npm/@hibira-io/push-web@1/dist/service-worker.js');
    self.HibiraPush.endpoint = 'https://ws.hibira.io';
  3. ブラウザを登録

    import { Client } from '@hibira-io/push-web';
    
    const push = new Client({
      instanceId: 'YOUR_INSTANCE_ID',
      endpoint: 'https://ws.hibira.io',
    });
    
    // Browsers only show the permission prompt after a click or tap.
    document.querySelector('#enable-notifications').addEventListener('click', async () => {
      await push.start();
      await push.addDeviceInterest('hello');
    });
  4. サインイン中のユーザーをひも付け

    import { TokenProvider } from '@hibira-io/push-web';
    
    // After sign-in. Your backend answers GET /push/user-token?user_id=... (see the server guide).
    await push.setUserId(currentUser.id, new TokenProvider({ url: '/push/user-token' }));
    
    // On sign-out, so the next person on this browser doesn't get their notifications.
    await push.stop();
Web 用のエージェント用プロンプト

Claude Code、Cursor、GitHub Copilot などの AI コーディングエージェントに貼り付けてください。インスタンス ID とエンドポイントが含まれ、シークレットキーは環境変数のままです。

Add Hibira push notifications to this Web project. Hibira Push sends to iOS (APNs), Android (FCM) and browsers (Web Push) through a Beams-compatible API, so it works with the Hibira client SDK (here: @hibira-io/push-web, https://github.com/hibira-io/hibira-push-web).

Connection details:
- Instance ID: YOUR_INSTANCE_ID
- Endpoint: https://ws.hibira.io
- No secret key: it belongs on the server, never in this app

What to do:
1. Look at the project first (framework version, package manager, config and env conventions, where similar integrations live) and follow what it already does.
2. Install @hibira-io/push-web (it replaces @pusher/push-notifications-web; the API is the same apart from the import and the endpoint option).
3. Serve service-worker.js from the site root (for example public/service-worker.js in Vite, Next.js or Create React App) with the importScripts line and the endpoint from the reference.
4. Create one shared push client module and call start() from a user action such as an "Enable notifications" button, never on page load: browsers block permission prompts that are not triggered by a click.
5. If the app has signed-in users, call setUserId with a TokenProvider pointing at the backend token endpoint after sign-in, and stop() on sign-out.
6. Web Push needs HTTPS (localhost is fine for development); on iPhone and iPad it works only once the site is added to the Home Screen.
7. Read the instance ID and endpoint from the project's config or environment, and add placeholder entries to .env.example (or its equivalent).
8. Always set the endpoint above. The Pusher Beams SDKs and their defaults point at pusher.com.
9. If YOUR_INSTANCE_ID above is still a placeholder, keep it as a config placeholder and tell me where to fill it in rather than inventing a value.
10. Subscribe test devices to the "hello" interest so the portal's Send a test reaches them.
11. When you are done, list the files you changed and tell me how to check it works: on the Hibira portal app page, Push notifications › Send a test to the hello interest.

Reference setup from the Hibira push notifications guide (adapt it to the project's structure):

Install:

```shell
npm install @hibira-io/push-web
```

Add the service worker:

```js
// public/service-worker.js, served at https://your-site/service-worker.js
importScripts('https://cdn.jsdelivr.net/npm/@hibira-io/push-web@1/dist/service-worker.js');
self.HibiraPush.endpoint = 'https://ws.hibira.io';
```

Register the browser:

```js
import { Client } from '@hibira-io/push-web';

const push = new Client({
  instanceId: 'YOUR_INSTANCE_ID',
  endpoint: 'https://ws.hibira.io',
});

// Browsers only show the permission prompt after a click or tap.
document.querySelector('#enable-notifications').addEventListener('click', async () => {
  await push.start();
  await push.addDeviceInterest('hello');
});
```

Link the signed-in user:

```js
import { TokenProvider } from '@hibira-io/push-web';

// After sign-in. Your backend answers GET /push/user-token?user_id=... (see the server guide).
await push.setUserId(currentUser.id, new TokenProvider({ url: '/push/user-token' }));

// On sign-out, so the next person on this browser doesn't get their notifications.
await push.stop();
```

3. サーバーから配信

サーバー SDK

言語

公式の Beams サーバー SDK を使い、エンドポイントを指定して Node.js から配信。 @pusher/push-notifications-server ↗

  1. インストール

    npm install @pusher/push-notifications-server
  2. インタレストに配信

    const PushNotifications = require('@pusher/push-notifications-server');
    
    const beams = new PushNotifications({
      instanceId: 'YOUR_INSTANCE_ID',
      secretKey: process.env.HIBIRA_PUSH_SECRET_KEY,
      endpoint: 'ws.hibira.io',
    });
    beams.protocol = 'https'; // the SDK switches to http when an endpoint is set
    
    await beams.publishToInterests(['hello'], {
      apns: { aps: { alert: { title: 'Hello', body: 'Hello, world!' } } },
      fcm: { notification: { title: 'Hello', body: 'Hello, world!' } },
      web: { notification: { title: 'Hello', body: 'Hello, world!', deep_link: 'https://your-site.example/' } },
    });
  3. ユーザートークンのエンドポイントを追加

    // Express: the client SDKs call GET /push/user-token?user_id=...
    app.get('/push/user-token', requireLogin, (req, res) => {
      if (req.query.user_id !== String(req.user.id)) return res.sendStatus(401);
      res.json(beams.generateToken(String(req.user.id))); // { token: '...' }
    });
  4. サインイン中のユーザーに配信

    await beams.publishToUsers(['user-1'], {
      apns: { aps: { alert: { title: 'Order shipped', body: 'Order #1024 is on its way.' } } },
      fcm: { notification: { title: 'Order shipped', body: 'Order #1024 is on its way.' } },
      web: { notification: { title: 'Order shipped', body: 'Order #1024 is on its way.' } },
    });
Node.js 用のエージェント用プロンプト

Claude Code、Cursor、GitHub Copilot などの AI コーディングエージェントに貼り付けてください。インスタンス ID とエンドポイントが含まれ、シークレットキーは環境変数のままです。

Add Hibira push notifications to this Node.js project. Hibira Push sends to iOS (APNs), Android (FCM) and browsers (Web Push) through a Beams-compatible API, so it works with the official Beams server SDKs pointed at the Hibira endpoint (here: @pusher/push-notifications-server, https://github.com/pusher/push-notifications-node).

Connection details:
- Instance ID: YOUR_INSTANCE_ID
- Endpoint: https://ws.hibira.io
- Secret key: read it from the HIBIRA_PUSH_SECRET_KEY environment variable (server-side only)

What to do:
1. Look at the project first (framework version, package manager, config and env conventions, where similar integrations live) and follow what it already does.
2. Create one shared module that builds the PushNotifications client from environment variables, with the endpoint option and beams.protocol set as in the reference (without them the SDK talks to pusher.com, or to the endpoint over plain http).
3. If the app has signed-in users, add the token route behind the project's existing authentication middleware; it must refuse a user_id that is not the signed-in user's.
4. Publish from the places that should notify (jobs, controllers, event handlers) through the shared module, and log the publish ID it returns.
5. Read the instance ID and endpoint from the project's config or environment, and add placeholder entries to .env.example (or its equivalent). Never commit the secret key or send it to a browser or mobile app.
6. Always set the endpoint above. The Pusher Beams SDKs and their defaults point at pusher.com.
7. If YOUR_INSTANCE_ID above is still a placeholder, keep it as a config placeholder and tell me where to fill it in rather than inventing a value.
8. Subscribe test devices to the "hello" interest so the portal's Send a test reaches them.
9. When you are done, list the files you changed and tell me how to check it works: on the Hibira portal app page, Push notifications › Send a test to the hello interest.

Reference setup from the Hibira push notifications guide (adapt it to the project's structure):

Install:

```shell
npm install @pusher/push-notifications-server
```

Publish to an interest:

```js
const PushNotifications = require('@pusher/push-notifications-server');

const beams = new PushNotifications({
  instanceId: 'YOUR_INSTANCE_ID',
  secretKey: process.env.HIBIRA_PUSH_SECRET_KEY,
  endpoint: 'ws.hibira.io',
});
beams.protocol = 'https'; // the SDK switches to http when an endpoint is set

await beams.publishToInterests(['hello'], {
  apns: { aps: { alert: { title: 'Hello', body: 'Hello, world!' } } },
  fcm: { notification: { title: 'Hello', body: 'Hello, world!' } },
  web: { notification: { title: 'Hello', body: 'Hello, world!', deep_link: 'https://your-site.example/' } },
});
```

Add the user token endpoint:

```js
// Express: the client SDKs call GET /push/user-token?user_id=...
app.get('/push/user-token', requireLogin, (req, res) => {
  if (req.query.user_id !== String(req.user.id)) return res.sendStatus(401);
  res.json(beams.generateToken(String(req.user.id))); // { token: '...' }
});
```

Publish to a signed-in user:

```js
await beams.publishToUsers(['user-1'], {
  apns: { aps: { alert: { title: 'Order shipped', body: 'Order #1024 is on its way.' } } },
  fcm: { notification: { title: 'Order shipped', body: 'Order #1024 is on its way.' } },
  web: { notification: { title: 'Order shipped', body: 'Order #1024 is on its way.' } },
});
```

4. サインイン中のユーザー

ある人が使うすべてのデバイスに届けるには、各デバイスを自社のユーザー ID にひも付けます。クライアント SDK は ?user_id=… を付けてトークンのエンドポイントを呼び出します。エンドポイントはリクエストがそのサインイン中のユーザーからのものか確認し、シークレットキーから generateToken で作ったトークンを返します(どの Beams サーバー SDK にもあります)。あとはインタレストの代わりにユーザー ID に配信します。ユーザーを削除すると、そのデバイスのひも付けはすべて解除されます。

ユーザーがサインアウトしたら stop を呼び、同じデバイスの次の人にその人の通知が届かないようにしてください。

5. テスト送信

アプリのページの「プッシュ通知 › テスト送信」で、インタレスト(上のスニペットでは hello)、タイトル、本文を入力して「テスト送信」をクリックします。そのインタレストを購読しているデバイスに数秒で届き、購読者メーターに登録済みのデバイスとブラウザの数が表示されます。

トラブルシューティング

デバイスやブラウザが購読者に表示されない
クライアントがこのアプリのインスタンス ID とエンドポイントで start を呼んでいるか、ユーザーが通知を許可しているかを確認してください。Android では、google-services.json がアップロードしたサービスアカウントと同じ Firebase プロジェクトのものである必要があります。
iPhone・iPad に何も届かない
APNs の環境はビルドと一致させてください:Xcode から実行するビルドは「開発(サンドボックス)」、TestFlight と App Store は「本番」です。バンドル ID はアプリと完全に一致し、アプリのターゲットで Push Notifications ケイパビリティを有効にする必要があります。
start() が「service worker missing」で失敗する
/service-worker.js はサイトのルートに置き、HTTPS で配信し、Web ガイドの importScripts の行を入れてください。サブフォルダの Service Worker はそのフォルダしか制御できません。
iPhone の Safari で許可を求められない
iOS/iPadOS 16.4 以降の Web Push は、サイトをホーム画面に追加してからでないと動作せず、許可のプロンプトはタップから出す必要があります。
サーバー SDK がまだ pusher.com に接続する、または http で失敗する
endpoint オプションを設定してください。Node.js SDK はさらに beams.protocol = 'https' が必要で、Go SDK では WithCustomBaseURL を使います。
配信が 401 を返す
サーバーが誤ったシークレットキー、または猶予期間を過ぎたローテーション前のキーを使っています。アプリのページから現在のキーをコピーしてください。
配信が 429 を返す
プランの上限を超える速さで配信しています。Retry-After の時間だけ待ち、1 件ずつリクエストするのではなく、1 回の配信で最大 100 個のインタレストまたは 1,000 人のユーザーを指定してください。
デバイスの登録が 402 を返す
アプリがプランの購読者数の上限に達しています。プランをアップグレードするか、離脱したユーザーを削除してそのデバイスを取り除いてください。
setUserId が失敗する
トークンのエンドポイントは、問い合わせられた user_id について、このアプリのシークレットキーで generateToken が返す JSON を 200 で返す必要があります。別のユーザーにひも付いたデバイスは、先に stop を呼んでください。

Pusher Beams から移行しますか?クライアント SDK のパッケージを当社のものに替え、サーバー SDK にエンドポイントを設定し、APNs キーと FCM サービスアカウントをアップロードして、ユーザーがアプリを更新するまで両方のサービスに配信してください。デバイスは初回起動時に登録し直します。 Pusher からの移行 →