ExNudge (ExNudge v1.0.1)

View Source

A pure Elixir library for sending Web Push notifications.

This library implements the Web Push Protocol as defined in RFC 8291 with support for VAPID authentication and payload encryption as per RFC 8292.

Quick Start

# Configure VAPID keys in your config
config :ex_nudge,
  vapid_subject: "mailto:your-email@example.com",
  vapid_public_key: "your_public_key",
  vapid_private_key: "your_private_key"

# Send a notification
subscription = %ExNudge.Subscription{
  endpoint: "https://fcm.googleapis.com/fcm/send/...",
  keys: %{
    p256dh: "client_public_key",
    auth: "client_auth_secret"
  },
  metadata: "some_internal_id_or_map"
}

ExNudge.send_notification(subscription, "Hello, World!")

Summary

Functions

Generates a new VAPID key pair for your application.

Sends a web push notification to a single subscription.

Sends web push notifications to multiple subscriptions concurrently.

Types

known_error()

@type known_error() ::
  :subscription_expired
  | :payload_too_large
  | {:request_failed, any()}
  | {:http_error, pos_integer()}

send_options()

@type send_options() :: [
  ttl: pos_integer(),
  concurrency: pos_integer(),
  urgency: :very_low | :low | :normal | :high,
  topic: String.t()
]

send_result()

@type send_result() :: {:ok, HTTPoison.Response.t()} | {:error, atom() | String.t()}

Functions

generate_vapid_keys()

@spec generate_vapid_keys() :: %{public_key: String.t(), private_key: String.t()}

Generates a new VAPID key pair for your application.

Examples

iex> ExNudge.generate_vapid_keys()
%{
  public_key: "BK8nBpIE2tsGVt8...",
  private_key: "aBcDeFgHiJkLmNoPqRsTuVwXyZ..."
}

send_notification(subscription, message, opts \\ [])

@spec send_notification(ExNudge.Subscription.t(), String.t(), send_options()) ::
  send_result()

Sends a web push notification to a single subscription.

Options

  • :ttl - Time to live in seconds (default: 60)
  • :urgency - Message urgency level (default: :normal)
  • :topic - Topic for message replacement

Examples

iex> subscription = %ExNudge.Subscription{...}
iex> ExNudge.send_notification(subscription, "Hello!")
{:ok, %HTTPoison.Response{status_code: 201}}

iex> ExNudge.send_notification(subscription, "Urgent!", urgency: :high, ttl: 300)
{:ok, %HTTPoison.Response{status_code: 201}}

send_notifications(subscriptions, message, opts \\ [])

Sends web push notifications to multiple subscriptions concurrently.

Returns a list of results in the same order as the input subscriptions.

Examples

iex> subscriptions = [sub1, sub2, sub3, sub4]
iex> ExNudge.send_notifications(subscriptions, "Broadcast message")
[
  {:ok, %ExNudge.Subscription{}, %HTTPoison.Response{}},
  {:error, :subscription_expired},
  {:error, :invalid_subscription},
  {:error, %ExNudge.Subscription{}, %HTTPoison.Response{}},
  {:ok, %ExNudge.Subscription{}, %HTTPoison.Response{}}
]