0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Web Push通知(VAPID)でFXトレードアラートを実装した

0
Posted at

はじめに

FXトレード中に損失が閾値を超えたらプッシュ通知で知らせる機能を実装しました。
Web Push API と VAPID 認証の実装手順を解説します。

Web Push の仕組み

ブラウザ → Push Server (Google/Mozilla) → Service Worker → 通知表示

VAPID(Voluntary Application Server Identification)を使うことで、
アプリサーバーの認証情報なしにプッシュ通知を送れます。

VAPID キーの生成

npx web-push generate-vapid-keys

出力される公開鍵・秘密鍵を環境変数に設定します。

Service Worker の登録

// pushNotifications.js
export async function registerPushSubscription(vapidPublicKey) {
  const registration = await navigator.serviceWorker.ready

  const subscription = await registration.pushManager.subscribe({
    userVisibleOnly: true,
    applicationServerKey: urlBase64ToUint8Array(vapidPublicKey),
  })

  // サブスクリプション情報をSupabaseに保存
  await supabase.from('push_subscriptions').upsert({
    user_id: userId,
    endpoint: subscription.endpoint,
    keys: subscription.toJSON().keys,
  })

  return subscription
}

Service Worker での通知受信

// sw.js
self.addEventListener('push', event => {
  const data = event.data?.json() ?? {}
  event.waitUntil(
    self.registration.showNotification(data.title ?? 'アラート', {
      body: data.body,
      icon: '/icon-192.png',
    })
  )
})

Supabase Edge Function からの送信

// supabase/functions/send-alert/index.ts
import webpush from 'npm:web-push'

webpush.setVapidDetails(
  'mailto:your@email.com',
  Deno.env.get('VAPID_PUBLIC_KEY'),
  Deno.env.get('VAPID_PRIVATE_KEY'),
)

await webpush.sendNotification(subscription, JSON.stringify({
  title: '損失アラート',
  body: `${accountName}: ${loss.toFixed(0)}円の損失が発生しました`,
}))

まとめ

Web Push + VAPID でサーバーサイドからブラウザへのプッシュ通知を実装できました。
Supabase Edge Functions と組み合わせることで、サーバーレスな通知システムが構築できます。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?