Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 37 ยท Capacitor and Native APIs

Push Notifications, Local Notifications and Haptics

Register for push notifications with Capacitor, handle tokens and taps, schedule local notifications and add haptic feedback to make Ionic apps feel native.

Notifications bring users back and haptics make taps feel real. Capacitor has plugins for push notifications (sent by a server through Firebase Cloud Messaging or Apple's service), local notifications (scheduled by the app itself) and haptics (small vibrations). Push needs server setup and has the most moving parts, so this lesson explains the flow first and then the code.

How push works

Your app never receives push messages directly from your server. The platform vendor sits in the middle:

sequenceDiagram
    participant A as App
    participant P as Push service (FCM / APNs)
    participant S as Your server
    A->>P: register()
    P-->>A: device token
    A->>S: send token with the user id
    S->>P: send message to token
    P-->>A: deliver notification
    A->>A: user taps, pushNotificationActionPerformed

The token identifies one app installation on one device. Tokens change, so servers must be able to update them.

Android uses Firebase Cloud Messaging (FCM). iOS uses Apple Push Notification service (APNs), and you need a paid Apple developer account, an APNs key and the "Push Notifications" capability enabled in Xcode. On Android 13 and later, apps must also ask for the POST_NOTIFICATIONS permission at run time.

Registering for push

Terminal
npm install @capacitor/push-notifications
npx cap sync
TypeScript
import { PushNotifications } from '@capacitor/push-notifications';

export async function initPush(sendTokenToServer: (t: string) => Promise<void>) {
  let permission = await PushNotifications.checkPermissions();
  if (permission.receive === 'prompt') {
    permission = await PushNotifications.requestPermissions();
  }
  if (permission.receive !== 'granted') return;

  await PushNotifications.addListener('registration', (token) => {
    sendTokenToServer(token.value);
  });
  await PushNotifications.addListener('registrationError', (err) => {
    console.error('Push registration failed', err.error);
  });
  await PushNotifications.addListener('pushNotificationReceived', (notification) => {
    // App is in the foreground: show an in-app toast instead of a system banner
    showToast(notification.title ?? 'New message');
  });
  await PushNotifications.addListener('pushNotificationActionPerformed', (action) => {
    // User tapped the notification: navigate using the data payload
    const route = action.notification.data?.route;
    if (route) router.navigateByUrl(route);
  });

  await PushNotifications.register();
}

Notice the order: listeners first, then register(). If you register first, you can miss the token event.

Push payloads are not a safe place for secrets or full private content. Send an id and let the app fetch details over HTTPS after the user opens it. Never trust data.route blindly either: validate it against the routes your app knows.

Local notifications

Local notifications need no server. They are good for reminders, timers and "you have an unsaved draft".

TypeScript
import { LocalNotifications } from '@capacitor/local-notifications';

await LocalNotifications.requestPermissions();
await LocalNotifications.schedule({
  notifications: [
    {
      id: 101,
      title: 'Water the plants',
      body: 'It is Monday morning.',
      schedule: { at: new Date(Date.now() + 60_000) },   // in one minute
      extra: { route: '/tabs/plants' },
    },
  ],
});
await LocalNotifications.cancel({ notifications: [{ id: 101 }] });

Ids are integers you choose. Scheduling with an id that exists replaces the old one, which is handy for "reschedule on edit". Android also needs a channel (importance, sound) for notifications to appear with the right priority.

Haptics

TypeScript
import { Haptics, ImpactStyle, NotificationType } from '@capacitor/haptics';

await Haptics.impact({ style: ImpactStyle.Light });          // button press
await Haptics.notification({ type: NotificationType.Success }); // saved
await Haptics.selectionStart(); await Haptics.selectionChanged(); await Haptics.selectionEnd(); // picker scroll

Use haptics sparingly: confirm a destructive action, acknowledge a save, tick a picker. Constant vibration is annoying, and some users disable it. Always make sure the feature still works without it (for example on the web or in a simulator, where it does nothing).

Stand-in: a push client and a fake server

This model reproduces the token flow, foreground versus tap events, and the rule that listeners must be added before registering.

JS The push token flow

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Stand-in: scheduling reminders

A local scheduler has to sort by time, replace by id and cancel. This one uses a virtual clock so the output is predictable.

JS A local notification scheduler

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does the device token identify?

    Servers map users to tokens, and a user can have many tokens.
  2. 2. Why add push listeners before calling register()?

    The token may arrive immediately, and an event with no listener is lost.
  3. 3. A notification arrives while the app is open. Which event fires?

    Received is for foreground delivery; ActionPerformed is for taps.
  4. 4. What happens if you schedule a local notification with an existing id?

    Ids are unique keys, so reusing one updates that notification.

Summary

  • Push goes app, then FCM or APNs, then your server; the token links them.
  • Register listeners first, then call register(); validate data from payloads.
  • Local notifications are scheduled on the device and use integer ids.
  • Haptics should confirm important actions, not decorate everything.
  • Android 13+ and iOS both need run-time notification permission.

Next: State Management in Ionic Apps