You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
@@ -12,26 +12,27 @@ You'll learn how to set up an Ably Realtime client with push notification suppor
12
12
13
13
1.[Sign up](https://ably.com/signup) for an Ably account.
14
14
2. Create a [new app](https://ably.com/accounts/any/apps/new), and create your first API key in the **API Keys** tab of the dashboard.
15
-
3. Your API key will need the `publish` and `subscribe` capabilities. For sending push notifications from your app, you'll also need the `push-admin` capability.
16
-
4. For channel-based push, add a rule for the channel with **Push notifications enabled** checked. In the dashboard left sidebar: **Configuration** → **Rules** → **Add** or **Edit** a rule, then enable the Push notifications option. See [rules](/docs/channels#rules) for details.
15
+
* Your API key needs the `publish`, `subscribe` capabilities.
16
+
* Also add the `push-admin` capability if you're using the same API key to send a push notification. In production this would more likely be a server using a different API key.
17
+
3. Add a rule to a channel so you can test sending push notification via a channel. Select [**Rules**](https://ably.com/accounts/any/apps/any/app_namespaces) in the Ably dashboard, add a new rule and enable the **Push notifications** option.
18
+
4. Install [Node.js](https://nodejs.org/) 18 or higher.
17
19
5. A modern browser that supports the [Push API](https://developer.mozilla.org/en-US/docs/Web/API/Push_API) (Chrome, Firefox, or Edge recommended).
Then install the Ably SDK and React hooks package:
52
53
53
-
<Code>
54
+
<Codefixed="true">
54
55
```shell
55
56
npm install ably
56
57
```
@@ -65,7 +66,7 @@ Because the Ably SDK runs in the browser, the component must not be server-side
65
66
Create `src/app/push/page.tsx` as the entry point:
66
67
67
68
<Code>
68
-
```javascript
69
+
```react
69
70
'use client';
70
71
71
72
import dynamic from 'next/dynamic';
@@ -78,10 +79,10 @@ export default function PushPage() {
78
79
```
79
80
</Code>
80
81
81
-
Then create `src/app/push/PushApp.tsx`. Because this module is only ever loaded client-side (due to `ssr: false`), it is safe to instantiate the Ably client at module scope. In a production app you would instead use `useAbly` from within a component to avoid creating a global client instance:
82
+
Then create `src/app/push/PushApp.tsx`. Because this module is only ever loaded client-side (due to `ssr: false`), it is safe to instantiate the Ably client at module scope:
82
83
83
84
<Code>
84
-
```javascript
85
+
```react
85
86
'use client';
86
87
87
88
import * as Ably from 'ably';
@@ -92,7 +93,7 @@ import { PushActivationBanner } from './PushActivationBanner';
92
93
import { ChannelSubscription } from './ChannelSubscription';
93
94
import { NotificationLog } from './NotificationLog';
94
95
95
-
constCHANNEL_NAME='exampleChannel1';
96
+
const CHANNEL_NAME = 'my-first-push-channel';
96
97
97
98
const client = new Ably.Realtime({
98
99
key: '{{API_KEY}}', // Do not use an API key in production — use token authentication instead
@@ -140,14 +141,35 @@ Key configuration options:
140
141
-**`plugins`**: The `AblyPushPlugin` enables push notification support.
141
142
-**`pushServiceWorkerUrl`**: Path to the service worker file. In Next.js, files in `public/` are served from the root, so `/service-worker.js` maps to `public/service-worker.js`.
142
143
143
-
`PushActivationBanner` sits directly under `AblyProvider` and handles device-level push activation. `ChannelSubscription` sits inside a `ChannelProvider`, which scopes it to `exampleChannel1`.
144
+
`PushActivationBanner` sits directly under `AblyProvider` and handles device-level push activation. `ChannelSubscription` sits inside a `ChannelProvider`, which scopes it to `my-first-push-channel`.
145
+
146
+
Create `src/app/push/NotificationLog.tsx` as a presentational component with no Ably dependency:
## Step 2: Set up push notifications <aid="step-2"/>
146
168
147
169
Create `src/app/push/PushActivationBanner.tsx`. This component uses the `usePushActivation` hook to activate and deactivate the device.
148
170
149
171
<Code>
150
-
```javascript
172
+
```react
151
173
'use client';
152
174
153
175
import { useEffect } from 'react';
@@ -194,18 +216,14 @@ export function PushActivationBanner({ onLog, onDeviceChange }: { onLog: (msg: s
194
216
195
217
-**`activate`**: Registers the browser for push notifications. Requests notification permission, registers the service worker, and records the device with Ably.
196
218
-**`deactivate`**: Removes the device registration from Ably's servers. Call this only on explicit user opt-out.
197
-
- **`localDevice`**: The current `LocalDevice` if activated, `null` otherwise. Reactive — updates immediately when `activate` or `deactivate` is called, and is re-populated from `localStorage` on page load if the device was activated in a prior session. Here it is propagated upward via `onDeviceChange` so the parent can display the device ID above the log.
-**`localDevice`**: The current `LocalDevice` if activated, `null` otherwise. Reactive — updates immediately when `activate` or `deactivate` is called, and is re-populated from `localStorage` on page load if the device was activated in a prior session.
200
220
201
221
A service worker runs in the background and receives push notifications even when the page is not open. In Next.js, place the service worker in `public/` so it is served from the root path.
202
222
203
-
### Create the service worker <a id="step-3-service-worker"/>
When a notification is clicked, the handler closes the notification, looks for an existing window, sends it the notification data via `postMessage`, and focuses it. If no window exists, it opens a new one.
276
292
277
-
### Handle notifications in the component <a id="step-3-handle-notifications"/>
Add a `useEffect` to `PushApp.tsx` to receive messages forwarded from the service worker and write them to the log:
280
296
281
297
<Code>
282
-
```javascript
298
+
```react
283
299
import { useEffect, useState } from 'react';
284
300
285
301
// Inside PushApp, after the log function:
@@ -307,105 +323,20 @@ useEffect(() => {
307
323
308
324
This listener is placed in `PushApp` rather than in a child component because push events are not channel-specific — a notification can arrive for any channel, or directly by device or client ID.
309
325
310
-
### Build the notification log <a id="step-3-notification-log"/>
311
-
312
-
Create `src/app/push/NotificationLog.tsx` as a presentational component with no Ably dependency:
Navigate to `http://localhost:3000/push` in your browser. Click **Activate Push**, grant notification permission, and wait for the device ID to appear.
342
-
343
-
### Test push notifications <a id="step-3-test"/>
344
-
345
-
Once the device is activated, publish a test push notification directly to your client ID using the [Ably CLI](/docs/platform/tools/cli):
notification: { title: 'Test push', body: 'Hello from code!' },
364
-
data: { foo: 'bar' },
365
-
},
366
-
);
367
-
```
368
-
</Code>
369
-
370
-
A native browser notification should appear and the log should display the received push event. You can also send to the specific device ID shown in the log:
371
-
372
-
<Code>
373
-
```shell
374
-
ably push publish --device-id <your-device-id> \
375
-
--title "Test push" \
376
-
--body "Hello from CLI!"
377
-
```
378
-
</Code>
379
-
380
-
<Code>
381
-
```javascript
382
-
await client.push.admin.publish(
383
-
{ deviceId: client.device().id },
384
-
{
385
-
notification: { title: 'Test push', body: 'Hello from code!' },
386
-
},
387
-
);
388
-
```
389
-
</Code>
390
-
391
-
<Aside data-type='note'>
392
-
Sending push notifications using `deviceId` or `clientId` requires the `push-admin` capability on your APIkey. In production, send push notifications from your backend server rather than from the client.
393
-
</Aside>
394
-
395
-
## Step 4: Subscribe to channel push <a id="step-4"/>
326
+
## Step 3: Subscribe to channel push notifications <aid="step-3"/>
396
327
397
328
Create `src/app/push/ChannelSubscription.tsx`. This component uses two hooks:
398
329
399
330
-`usePush` to manage push subscriptions for the channel and expose `isActivated`
400
331
-`useChannel` to subscribe to realtime messages on the same channel
`usePush` returns `isActivated` — a reactive boolean shared with `usePushActivation` via a module-level store. When `PushActivationBanner` calls `activate()`, all `usePush` instances update automatically, so the subscribe buttons enable without any extra wiring.
466
397
467
-
To test channel push, subscribe to the channel in the UI then publish a push notification to the channel using the [Ably CLI](/docs/platform/tools/cli):
398
+
Run your app on a real device or compatible browser:
468
399
469
-
<Code>
400
+
<Codefixed="true">
470
401
```shell
471
-
ably push publish --channel exampleChannel1 \
402
+
npm run dev
403
+
```
404
+
</Code>
405
+
406
+
Navigate to `http://localhost:3000/push` in your browser.
407
+
408
+
## Step 4: Publish a push notification <aid="step-4"/>
409
+
410
+
In the app click **Activate Push** and wait until the status message displays your device ID.
411
+
412
+
### Publish directly to your device <aid="step-4-direct"/>
413
+
414
+
Publish a push notification directly to your client ID (or device ID using `--device-id` instead of `--client-id`) via the [Ably CLI](/docs/platform/tools/cli):
When publishing from code, the `push` object must be included in the `extras`ofthe realtime message. The`extras.push` object has two parts:
438
+
If you click **Unsubscribe from Channel**, the device no longer receives push notifications for that channel. Send the same command again and verify that no notification is received.
496
439
497
-
-`notification`: Contains `title` and `body` displayed in the browser notification.
498
-
-`data`: Custom key-value pairs delivered to the service worker but not shown directly.
440
+
To see the full list of options for sending push notifications with the Ably CLI, run `ably push publish --help` or see the [Ably CLI push documentation](/docs/cli/push). To send push notifications from your own server code instead of the CLI, see [Push notification publishing](https://ably.com/docs/push/publish).
499
441
500
442

0 commit comments