HomeGuidesReferenceLearn

Reference version

Expo Notifications iconExpo Notifications

GitHub

npm

A library that provides an API to fetch push notification tokens and to present, schedule, receive and respond to notifications.


expo-notifications provides an API to fetch push notification tokens and to present, schedule, receive and respond to notifications.

Migrating from Expo's LegacyNotifications module? See the migration guide.

Push notifications Platform Compatibility

Android DeviceAndroid EmulatoriOS DeviceiOS SimulatorWeb

Local notifications Platform Compatibility

Android DeviceAndroid EmulatoriOS DeviceiOS SimulatorWeb

Features

  • Schedule a one-off notification for a specific date or some time from now
  • Schedule a notification repeating in some time interval (or a calendar date match on iOS)
  • Get and set the application badge icon number
  • Fetch a native device push token so you can send push notifications with FCM and APNs
  • Fetch an Expo push token so you can send push notifications with Expo
  • Listen to incoming notifications in the foreground and background
  • Listen to interactions with notifications
  • Handle notifications when the app is in the foreground
  • Imperatively dismiss notifications from Notification Center/tray
  • Create, update, and delete Android notification channels
  • Set custom icon and color for notifications on Android

Installation

Terminal
- npx expo install expo-notifications

If you're installing this in a bare React Native app, you should also follow these additional installation instructions.

Usage

Check out the example Snack below to see Notifications in action, make sure to use a physical device to test it. Push notifications don't work on emulators/simulators.

Push Notifications
import { useState, useEffect, useRef } from 'react';
import { Text, View, Button, Platform } from 'react-native';
import * as Device from 'expo-device';
import * as Notifications from 'expo-notifications';

Notifications.setNotificationHandler({
  handleNotification: async () => ({
    shouldShowAlert: true,
    shouldPlaySound: false,
    shouldSetBadge: false,
  }),
});

export default function App() {
  const [expoPushToken, setExpoPushToken] = useState('');
  const [notification, setNotification] = useState(false);
  const notificationListener = useRef();
  const responseListener = useRef();

  useEffect(() => {
    registerForPushNotificationsAsync().then(token => setExpoPushToken(token));

    notificationListener.current = Notifications.addNotificationReceivedListener(notification => {
      setNotification(notification);
    });

    responseListener.current = Notifications.addNotificationResponseReceivedListener(response => {
      console.log(response);
    });

    return () => {
      Notifications.removeNotificationSubscription(notificationListener.current);
      Notifications.removeNotificationSubscription(responseListener.current);
    };
  }, []);

  return (
    <View
      style={{
        flex: 1,
        alignItems: 'center',
        justifyContent: 'space-around',
      }}>
      <Text>Your expo push token: {expoPushToken}</Text>
      <View style={{ alignItems: 'center', justifyContent: 'center' }}>
        <Text>Title: {notification && notification.request.content.title} </Text>
        <Text>Body: {notification && notification.request.content.body}</Text>
        <Text>Data: {notification && JSON.stringify(notification.request.content.data)}</Text>
      </View>
      <Button
        title="Press to schedule a notification"
        onPress={async () => {
          await schedulePushNotification();
        }}
      />
    </View>
  );
}

async function schedulePushNotification() {
  await Notifications.scheduleNotificationAsync({
    content: {
      title: "You've got mail! 📬",
      body: 'Here is the notification body',
      data: { data: 'goes here' },
    },
    trigger: { seconds: 2 },
  });
}

async function registerForPushNotificationsAsync() {
  let token;

  if (Platform.OS === 'android') {
    await Notifications.setNotificationChannelAsync('default', {
      name: 'default',
      importance: Notifications.AndroidImportance.MAX,
      vibrationPattern: [0, 250, 250, 250],
      lightColor: '#FF231F7C',
    });
  }

  if (Device.isDevice) {
    const { status: existingStatus } = await Notifications.getPermissionsAsync();
    let finalStatus = existingStatus;
    if (existingStatus !== 'granted') {
      const { status } = await Notifications.requestPermissionsAsync();
      finalStatus = status;
    }
    if (finalStatus !== 'granted') {
      alert('Failed to get push token for push notification!');
      return;
    }
    token = (await Notifications.getExpoPushTokenAsync()).data;
    console.log(token);
  } else {
    alert('Must use physical device for Push Notifications');
  }

  return token;
}

Configuration

Credentials

Android

Firebase Cloud Messaging credentials are required for all Android apps to receive push notifications in your app (except when testing in Expo Go). For more information, see how to get FCM credentials for your app.

iOS

To register your iOS device and automatically enable push notifications for your EAS Build, see push notification setup.

App config

To configure expo-notifications, use the built-in config plugin in the app config (app.json or app.config.js) for EAS Build or with npx expo run:[android|ios]. The plugin allows you to configure the following properties that cannot be set at runtime and require building a new app binary to take effect:

Configurable properties

NameDefaultDescription
icon-Only for: 
Android

Local path to an image to use as the icon for push notifications. 96x96 all-white png with transparency.

color#ffffffOnly for: 
Android

Tint color for the push notification image when it appears in the notification tray.

sounds-

Array of local paths to sound files (.wav recommended) that can be used as custom notification sounds.

Here is an example of using the config plugin in the app config file:

app.json
{
  "expo": {
    "plugins": [
      [
        "expo-notifications",
        {
          "icon": "./local/assets/notification-icon.png",
          "color": "#ffffff",
          "sounds": [
            "./local/assets/notification-sound.wav",
            "./local/assets/notification-sound-other.wav"
          ]
        }
      ]
    ]
  }
}
Are you using this library in a bare React Native app?

Learn how to configure the native projects in the installation instructions in the expo-notifications repository.

The iOS APNs entitlement is always set to 'development'. Xcode automatically changes this to 'production' during the archive. Learn more.

Permissions

Android

  • On Android, this module requires permission to subscribe to the device boot. It's used to setup scheduled notifications when the device (re)starts. The RECEIVE_BOOT_COMPLETED permission is added automatically through the library AndroidManifest.xml.

  • Starting from Android 12 (API level 31), to schedule the notification that triggers at the exact time, you need to add <uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM"/> to AndroidManifest.xml. You can read more about the exact alarm permission.

  • On Android 13, app users must opt-in to receive notifications via a permissions prompt automatically triggered by the operating system. This prompt will not appear until at least one notification channel is created. The setNotificationChannelAsync must be called before getDevicePushTokenAsync or getExpoPushTokenAsync to obtain a push token. You can read more about the new notification permission behavior for Android 13 in the official documentation.

Android PermissionDescription

RECEIVE_BOOT_COMPLETED

Allows an application to receive the Intent.ACTION_BOOT_COMPLETED that is broadcast after the system finishes booting.

Allows an application to receive the Intent.ACTION_BOOT_COMPLETED that is broadcast after the system finishes booting. If you don't request this permission, you will not receive the broadcast at that time. Though holding this permission does not have any security implications, it can have a negative impact on the user experience by increasing the amount of time it takes the system to start and allowing applications to have themselves running without the user being aware of them. As such, you must explicitly declare your use of this facility to make that visible to the user.

SCHEDULE_EXACT_ALARM

Allows applications to use exact alarm APIs.

iOS

No usage description is required, see notification-related permissions.

API

import * as Notifications from 'expo-notifications';

Custom notification icon and colors (Android only)

You can configure the notification.icon and notification.color keys in the project's app.json if you are using Expo Prebuild or by using the expo-notifications config plugin directly. These are build-time settings, so you'll need to recompile your native Android app with eas build -p android or npx expo run:android to see the changes.

For your notification icon, make sure you follow Google's design guidelines (the icon must be all white with a transparent background) or else it may not be displayed as intended.

You can also set a custom notification color per-notification directly in your NotificationContentInput under the color attribute.

Set custom notification sounds

Custom notification sounds are only supported when using EAS Build.

To add custom push notification sounds to your app, add the expo-notifications plugin to your app.json file:

app.json
{
  "expo": {
    "plugins": [
      [
        "expo-notifications",
        {
          "sounds": ["local/path/to/mySoundFile.wav"]
        }
      ]
    ]
  }
}

After building your app, the array of files will be available for use in both NotificationContentInput and NotificationChannelInput. You only need to provide the base filename- here's an example using the config above:

await Notifications.setNotificationChannelAsync('new-emails', {
  name: 'E-mail notifications',
  sound: 'mySoundFile.wav', // Provide ONLY the base filename
});

await Notifications.scheduleNotificationAsync({
  content: {
    title: "You've got mail! 📬",
    sound: 'mySoundFile.wav', // Provide ONLY the base filename
  },
  trigger: {
    seconds: 2,
    channelId: 'new-emails',
  },
});

You can also manually add notification files to your Android and iOS projects if you prefer:

Manually adding notification sounds on Android

On Androids 8.0+, playing a custom sound for a notification requires more than setting the sound property on the NotificationContentInput. You will also need to configure the NotificationChannel with the appropriate sound, and use it when sending/scheduling the notification.

For the example below to work, you would place your email-sound.wav file in android/app/src/main/res/raw/.

// Prepare the notification channel
await Notifications.setNotificationChannelAsync('new-emails', {
  name: 'E-mail notifications',
  importance: Notifications.AndroidImportance.HIGH,
  sound: 'email-sound.wav', // <- for Android 8.0+, see channelId property below
});

// Eg. schedule the notification
await Notifications.scheduleNotificationAsync({
  content: {
    title: "You've got mail! 📬",
    body: 'Open the notification to read them all',
    sound: 'email-sound.wav', // <- for Android below 8.0
  },
  trigger: {
    seconds: 2,
    channelId: 'new-emails', // <- for Android 8.0+, see definition above
  },
});
Manually adding notification sounds on iOS

On iOS, all that's needed is to place your sound file in your Xcode project (see the screenshot below), and then specify the sound file in your NotificationContentInput, like this:

await Notifications.scheduleNotificationAsync({
  content: {
    title: "You've got mail! 📬",
    body: 'Open the notification to read them all',
    sound: 'notification.wav',
  },
  trigger: {
    // ...
  },
});
notification.wav inside of app resources in Xcode project organizer

Android push notification payload specification

When sending a push notification, put an object conforming to the following type as data of the notification:

export interface FirebaseData {
  title?: string;
  message?: string;
  subtitle?: string;
  sound?: boolean | string;
  vibrate?: boolean | number[];
  priority?: AndroidNotificationPriority;
  badge?: number;
}

Fetch tokens for push notifications

getExpoPushTokenAsync(options: ExpoTokenOptions): ExpoPushToken

Returns an Expo token that can be used to send a push notification to the device using Expo's push notifications service.

This method makes requests to the Expo's servers. It can get rejected in cases where the request itself fails (for example, due to the device being offline, experiencing a network timeout, or other HTTPS request failures). To provide offline support to your users, you should try/catch this method and implement retry logic to attempt to get the push token later, once the device is back online.

For Expo's backend to be able to send notifications to your app, you will need to provide it with push notification keys. For more information, see credentials in the push notifications setup.

Arguments

This function accepts an optional object allowing you to pass in configuration with the following fields:

  • experienceId (string) -- passing is mandatory. The ID of the experience to which the token should be attributed. Defaults to Constants.manifest.id exposed by expo-constants. When building with EAS Build, or in the bare workflow, this is required and you must provide a value which takes the shape @username/projectSlug, where username is the Expo account that the project is associated with, and projectSlug is your slug from app.json.
  • devicePushToken (DevicePushToken) -- The device push token with which to register at the backend. Defaults to a token fetched with getDevicePushTokenAsync().
  • applicationId (string) -- The ID of the application to which the token should be attributed. Defaults to Application.applicationId exposed by expo-application.
  • development (boolean) -- Makes sense only on iOS, where there are two push notification services: sandbox and production. This defines whether the push token is supposed to be used with the sandbox platform notification service. Defaults to Application.getIosPushNotificationServiceEnvironmentAsync() exposed by expo-application or false. Most probably you won't need to customize that. You may want to customize that if you don't want to install expo-application and still use the sandbox APNs.

Returns

Returns a Promise that resolves to an object with the following fields:

  • type (string) -- Always expo.
  • data (string) -- The push token as a string.

Examples

Fetching the Expo push token and uploading it to a server

import * as Notifications from 'expo-notifications';

export async function registerForPushNotificationsAsync(userId: string) {
  const expoPushToken = await Notifications.getExpoPushTokenAsync({
    experienceId: '@username/example',
  });

  await fetch('https://example.com/', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      userId,
      expoPushToken,
    }),
  });
}

getDevicePushTokenAsync(): DevicePushToken

Returns a native FCM, APNs token or a PushSubscription data that can be used with another push notification service.

Returns

A Promise that resolves to an object with the following fields:

  • type (string) -- Either ios, android or web.
  • data (string or object) -- Either the push token as a string (for type == "ios" | "android") or an object conforming to the type below (for type == "web"):
    {
      endpoint: string;
      keys: {
        p256dh: string;
        auth: string;
      }
    }
    

addPushTokenListener(listener: PushTokenListener): Subscription

In rare situations, a push token may be changed by the push notification service while the app is running. When a token is rolled, the old one becomes invalid and sending notifications to it will fail. A push token listener will let you handle this situation gracefully by registering the new token with your backend right away.

Arguments

A single and required argument is a function accepting a push token as an argument. It will be called whenever the push token changes.

Returns

A Subscription object represents the subscription of the provided listener.

Examples

Registering a push token listener using a React hook

import React from 'react';
import * as Notifications from 'expo-notifications';

import { registerDevicePushTokenAsync } from '../api';

export default function App() {
  React.useEffect(() => {
    const subscription = Notifications.addPushTokenListener(registerDevicePushTokenAsync);
    return () => subscription.remove();
  }, []);

  return (
    // Your app content
  );
}

removePushTokenSubscription(subscription: Subscription): void

Removes a push token subscription returned by an addPushTokenListener call.

Arguments

A single and required argument is a subscription returned by addPushTokenListener.

Listen to notification events

Notification events include incoming notifications, interactions your users perform with notifications (this can be tapping on a notification, or interacting with it via notification categories), and rare occasions when your notifications may be dropped.

A few different listeners are exposed, so we've provided a chart below which will hopefully help you understand when you can expect each one to be triggered:

User interacted with notification?App stateListener(s) triggered
falseForegroundNotificationReceivedListener
falseBackgroundBackgroundNotificationTask
falseKillednone
trueForegroundNotificationReceivedListener & NotificationResponseReceivedListener
trueBackgroundNotificationResponseReceivedListener
trueKilledNotificationResponseReceivedListener

In the chart above, whenever NotificationResponseReceivedListener is triggered, the same would apply to the useLastNotificationResponse hook.

useLastNotificationResponse(): undefined | NotificationResponse | null

A React hook always returns the notification response that was received most recently (a notification response designates an interaction with a notification, such as tapping on it)

If you don't want to use a hook, you can use Notifications.getLastNotificationResponseAsync() instead.

Returns

The hook may return one of these three types/values:

  • undefined -- until we're sure of what to return
  • null -- if no notification response has been received yet
  • a NotificationResponse object -- if a notification response was received

Examples

Responding to a notification tap by opening a URL that could be put into the notification's data (opening the URL is your responsibility and is not a part of the expo-notifications API):

import * as Notifications from 'expo-notifications';
import { Linking } from 'react-native';

export default function App() {
  const lastNotificationResponse = Notifications.useLastNotificationResponse();
  React.useEffect(() => {
    if (
      lastNotificationResponse &&
      lastNotificationResponse.notification.request.content.data.url &&
      lastNotificationResponse.actionIdentifier === Notifications.DEFAULT_ACTION_IDENTIFIER
    ) {
      Linking.openURL(lastNotificationResponse.notification.request.content.data.url);
    }
  }, [lastNotificationResponse]);

  return (
    /*
     * your app
     */
  );
}

addNotificationReceivedListener(listener: (event: Notification) => void): void

Listeners registered by this method will be called whenever a notification is received while the app is running.

Arguments

A single and required argument is a function accepting a notification (Notification) as an argument.

Returns

A Subscription object represents the subscription of the provided listener.

Examples

Registering a notification listener using a React hook

import React from 'react';
import * as Notifications from 'expo-notifications';

export default function App() {
  React.useEffect(() => {
    const subscription = Notifications.addNotificationReceivedListener(notification => {
      console.log(notification);
    });
    return () => subscription.remove();
  }, []);

  return (
    // Your app content
  );
}

addNotificationsDroppedListener(listener: () => void): void

Listeners registered by this method will be called whenever some notifications have been dropped by the server. Applicable only to Firebase Cloud Messaging which we use as a notifications service on Android. It corresponds to onDeletedMessages() callback. More information can be found in Firebase docs.

Arguments

A single and required argument is a function–callback.

Returns

A Subscription object represents the subscription of the provided listener.

addNotificationResponseReceivedListener(listener: (event: NotificationResponse) => void): void

Listeners registered by this method will be called whenever a user interacts with a notification (eg. taps on it).

Arguments

A single and required argument is a function accepting notification response (NotificationResponse) as an argument.

Returns

A Subscription object represents the subscription of the provided listener.

Examples

Register a notification listener using a React hook

import React from 'react';
import { Linking } from 'react-native';
import * as Notifications from 'expo-notifications';

export default function Container() {
  React.useEffect(() => {
    const subscription = Notifications.addNotificationResponseReceivedListener(response => {
      const url = response.notification.request.content.data.url;
      Linking.openURL(url);
    });
    return () => subscription.remove();
  }, []);

  return (
    // Your app content
  );
}

Handle push notifications with React Navigation

If you'd like to deep link to a specific screen in your app when you receive a push notification, you can configure React Navigation's linking prop to do that:

import React from 'react';
import { Linking } from 'react-native';
import * as Notifications from 'expo-notifications';
import { NavigationContainer } from '@react-navigation/native';

export default function App() {
  return (
    <NavigationContainer
      linking={{
        config: {
          // Configuration for linking
        },
        async getInitialURL() {
          // First, you may want to do the default deep link handling
          // Check if app was opened from a deep link
          const url = await Linking.getInitialURL();

          if (url != null) {
            return url;
          }

          // Handle URL from expo push notifications
          const response = await Notifications.getLastNotificationResponseAsync();
          const url = response?.notification.request.content.data.url;

          return url;
        },
        subscribe(listener) {
          const onReceiveURL = ({ url }: { url: string }) => listener(url);

          // Listen to incoming links from deep linking
          Linking.addEventListener('url', onReceiveURL);

          // Listen to expo push notifications
          const subscription = Notifications.addNotificationResponseReceivedListener(response => {
            const url = response.notification.request.content.data.url;

            // Any custom logic to see whether the URL needs to be handled
            //...

            // Let React Navigation handle the URL
            listener(url);
          });

          return () => {
            // Clean up the event listeners
            Linking.removeEventListener('url', onReceiveURL);
            subscription.remove();
          };
        },
      }}>
      {/* Your app content */}
    </NavigationContainer>
  );
}

See more details on React Navigation documentation.

removeNotificationSubscription(subscription: Subscription): void

Removes a notification subscription returned by an addNotification*Listener call.

Arguments

A single and required argument is a subscription returned by addNotification*Listener.

Handle incoming notifications when the app is in the foreground

setNotificationHandler(handler: NotificationHandler | null): void

When a notification is received while the app is running, using this function you can set a callback that will decide whether the notification should be shown to the user or not.

When a notification is received, handleNotification is called with the incoming notification as an argument. The function should respond with a behavior object within 3 seconds, otherwise, the notification will be discarded. If the notification is handled successfully, handleSuccess is called with the identifier of the notification, otherwise (or on timeout) handleError will be called.

The default behavior when the handler is not set or does not respond in time is not to show the notification.

Arguments

The function receives a single argument which should be either null (if you want to clear the handler) or an object of fields:

  • handleNotification ((Notification) => Promise<NotificationBehavior>) -- (required) a function accepting an incoming notification returning a Promise resolving to a behavior (NotificationBehavior) applicable to the notification
  • handleSuccess ((notificationId: string) => void) -- (optional) a function called whenever an incoming notification is handled successfully
  • handleError ((error: Error) => void) -- (optional) a function called whenever handling of an incoming notification fails

Examples

Implementing a notification handler that always shows the notification when it is received

import * as Notifications from 'expo-notifications';

Notifications.setNotificationHandler({
  handleNotification: async () => ({
    shouldShowAlert: true,
    shouldPlaySound: false,
    shouldSetBadge: false,
  }),
});

Handle incoming notifications when the app is not in the foreground

Not supported in Expo Go.

To handle notifications while the app is backgrounded on iOS, you must add remote-notification to the ios.infoPlist.UIBackgroundModes key in your app.json, and add "content-available": 1 to your push notification payload. Under normal circumstances, the "content-available" flag should launch your app if it isn't running and wasn't killed by the user, however, this is ultimately decided by the OS so it might not always happen.

registerTaskAsync(taskName: string): void

When a notification is received while the app is backgrounded, using this function you can set a callback that will be run in response to that notification. Under the hood, this function is run using expo-task-manager. You must define the task first, with TaskManager.defineTask. Make sure you define it in the global scope.

The taskName argument is the string you passed to TaskManager.defineTask as the "taskName". The callback function you define with TaskManager.defineTask will receive an object with the following fields:

  • data: The remote payload delivered by either FCM (Android) or APNs (iOS). See here for details.
  • error: The error (if any) that occurred during execution of the task.
  • executionInfo: JSON object of additional info related to the task, including the taskName.

Example

import * as TaskManager from 'expo-task-manager';
import * as Notifications from 'expo-notifications';

const BACKGROUND_NOTIFICATION_TASK = 'BACKGROUND-NOTIFICATION-TASK';

TaskManager.defineTask(BACKGROUND_NOTIFICATION_TASK, ({ data, error, executionInfo }) => {
  console.log('Received a notification in the background!');
  // Do something with the notification data
});

Notifications.registerTaskAsync(BACKGROUND_NOTIFICATION_TASK);

unregisterTaskAsync(taskName: string): void

Used to unregister tasks registered with registerTaskAsync.

Fetch information about notifications-related permissions

getPermissionsAsync(): Promise<NotificationPermissionsStatus>

Calling this function checks current permissions settings related to notifications. It lets you verify whether the app is currently allowed to display alerts, play sounds, and so on. There is no user-facing effect of calling this.

Returns

It returns a Promise resolving to an object representing permission settings (NotificationPermissionsStatus). On iOS, make sure you properly interpret the permissions response.

Examples

Check if the app is allowed to send any type of notifications (interrupting and non-interrupting–provisional on iOS)

import * as Notifications from 'expo-notifications';

export async function allowsNotificationsAsync() {
  const settings = await Notifications.getPermissionsAsync();
  return (
    settings.granted || settings.ios?.status === Notifications.IosAuthorizationStatus.PROVISIONAL
  );
}

requestPermissionsAsync(request?: NotificationPermissionsRequest): Promise<NotificationPermissionsStatus>

Prompts the user for notification permissions according to request. Request defaults to asking the user to allow displaying alerts, setting badge count and playing sounds.

Arguments

An optional object of conforming to the following interface:

{
  android?: {};
  ios?: {
    allowAlert?: boolean;
    allowBadge?: boolean;
    allowSound?: boolean;
    allowDisplayInCarPlay?: boolean;
    allowCriticalAlerts?: boolean;
    provideAppNotificationSettings?: boolean;
    allowProvisional?: boolean;
    allowAnnouncements?: boolean;
  }
}

Each option corresponds to a different native platform authorization option. To see a list of available options on iOS, see UNAuthorizationOptions. On Android, all available permissions are granted by default, and if a user declines any permission, an app cannot prompt the user to change.

Returns

It returns a Promise resolving to an object represents permission settings (NotificationPermissionsStatus). On iOS, make sure you properly interpret the permissions response.

Examples

Prompts the user to allow the app to show alerts, play sounds, set badge count and let Siri read out messages through AirPods

import * as Notifications from 'expo-notifications';

export function requestPermissionsAsync() {
  return await Notifications.requestPermissionsAsync({
    ios: {
      allowAlert: true,
      allowBadge: true,
      allowSound: true,
      allowAnnouncements: true,
    },
  });
}

Interpret the iOS permissions response

On iOS, permissions for sending notifications are a little more granular than they are on Android. Because of this, you should rely on the NotificationPermissionsStatus's ios.status field, instead of the root status field. This value will be one of the following, accessible under Notifications.IosAuthorizationStatus:

  • NOT_DETERMINED: The user hasn't yet made a choice about whether the app is allowed to schedule notifications
  • DENIED: The app isn't authorized to schedule or receive notifications
  • AUTHORIZED: The app is authorized to schedule or receive notifications
  • PROVISIONAL: The application is provisionally authorized to post noninterruptive user notifications
  • EPHEMERAL: The app is authorized to schedule or receive notifications for a limited amount of time

Manage application badge icon

getBadgeCountAsync(): Promise<number>

Fetches the number currently set as the badge of the app icon on device's home screen. A 0 value means that the badge is not displayed.

Note: Not all Android launchers support application badges. If the launcher does not support icon badges, the method will always resolve to 0.

Returns

It returns a Promise resolving to a number that represents the current badge of the app icon.

setBadgeCountAsync(badgeCount: number, options?: SetBadgeCountOptions): Promise<boolean>

Sets the badge of the app's icon to the specified number. Setting it to 0 clears the badge. On iOS, this method requires that you have requested the user's permission for allowBadge via requestPermissionsAsync, otherwise it will automatically return false.

Note: Not all Android launchers support application badges. If the launcher does not support icon badges, the method will resolve to false.

Arguments

The function accepts a number as the first argument. A value of 0 will clear the badge.

As a second, optional argument you can pass in an object of options configuring behavior applied in Web environment. The object should be of the format:

{
  web?: badgin.Options
}

where the type badgin.Options is an object described in the badgin's documentation.

Returns

It returns a Promise resolving to a boolean representing whether the setting of the badge succeeded.

Schedule notifications

getAllScheduledNotificationsAsync(): Promise<Notification[]>

Fetches information about all scheduled notifications.

Returns

It returns a Promise resolving to an array of objects conforming to the Notification interface.

presentNotificationAsync(content: NotificationContentInput, identifier?: string): Promise<string>

Schedules a notification for immediate trigger.

Note: This method has been deprecated in favor of using an explicit NotificationHandler and the scheduleNotificationAsync method. More info may be found at https://expo.fyi/presenting-notifications-deprecated.

Arguments

The only argument to this function is a NotificationContentInput.

Returns

It returns a Promise resolving with the notification's identifier once the notification is successfully scheduled for immediate display.

Examples

Present the notification to the user (deprecated way)

import * as Notifications from 'expo-notifications';

Notifications.presentNotificationAsync({
  title: 'Look at that notification',
  body: "I'm so proud of myself!",
});

Present the notification to the user (recommended way)

import * as Notifications from 'expo-notifications';

// First, set the handler that will cause the notification
// to show the alert

Notifications.setNotificationHandler({
  handleNotification: async () => ({
    shouldShowAlert: true,
    shouldPlaySound: false,
    shouldSetBadge: false,
  }),
});

// Second, call the method

Notifications.scheduleNotificationAsync({
  content: {
    title: 'Look at that notification',
    body: "I'm so proud of myself!",
  },
  trigger: null,
});

scheduleNotificationAsync(notificationRequest: NotificationRequestInput): Promise<string>

Schedules a notification to be triggered in the future.

Note: Please note that this does not mean that the notification will be presented when it is triggered. For the notification to be presented you have to set a notification handler with setNotificationHandler that will return an appropriate notification behavior. For more information see the example below.

Arguments

The only argument to this method is a NotificationRequestInput describing the notification to be triggered.

Returns

It returns a Promise resolving to a string --- a notification identifier you can later use to cancel the notification or to identify an incoming notification.

Examples

Schedule the notification that will trigger once, in one minute from now

import * as Notifications from 'expo-notifications';

Notifications.scheduleNotificationAsync({
  content: {
    title: "Time's up!",
    body: 'Change sides!',
  },
  trigger: {
    seconds: 60,
  },
});

Schedule the notification that will trigger repeatedly, every 20 minutes

import * as Notifications from 'expo-notifications';

Notifications.scheduleNotificationAsync({
  content: {
    title: 'Remember to drink water!',
  },
  trigger: {
    seconds: 60 * 20,
    repeats: true,
  },
});

Schedule the notification that will trigger once, at the beginning of next hour

import * as Notifications from 'expo-notifications';

const trigger = new Date(Date.now() + 60 * 60 * 1000);
trigger.setMinutes(0);
trigger.setSeconds(0);

Notifications.scheduleNotificationAsync({
  content: {
    title: 'Happy new hour!',
  },
  trigger,
});

cancelScheduledNotificationAsync(identifier: string): Promise<void>

Cancels a single scheduled notification. The scheduled notification of given ID will not trigger.

Arguments

The notification identifier with which scheduleNotificationAsync is resolved when the notification has been scheduled.

Returns

A Promise resolves once the scheduled notification is successfully canceled or if there is no scheduled notification for a given identifier.

Examples

Schedule and then cancel the notification

import * as Notifications from 'expo-notifications';

async function scheduleAndCancel() {
  const identifier = await Notifications.scheduleNotificationAsync({
    content: {
      title: 'Hey!',
    },
    trigger: { seconds: 60, repeats: true },
  });
  await Notifications.cancelScheduledNotificationAsync(identifier);
}

cancelAllScheduledNotificationsAsync(): Promise<void>

Cancels all scheduled notifications.

Returns

A Promise resolves once all the scheduled notifications are successfully canceled or if there are no scheduled notifications.

getNextTriggerDateAsync(trigger: SchedulableNotificationTriggerInput): Promise<number | null>

Allows you to check what will be the next trigger date for given notification trigger input.

Arguments

The schedulable notification trigger you would like to check next trigger date for (of type SchedulableNotificationTriggerInput).

Returns

If the return value is null, the notification won't be triggered. Otherwise, the return value is the Unix timestamp in milliseconds at which the notification will be triggered.

Examples

Calculate next trigger date for a notification trigger

import * as Notifications from 'expo-notifications';

async function logNextTriggerDate() {
  try {
    const nextTriggerDate = await Notifications.getNextTriggerDateAsync({
      hour: 9,
      minute: 0,
    });
    console.log(nextTriggerDate === null ? 'No next trigger date' : new Date(nextTriggerDate));
  } catch (e) {
    console.warn(`Couldn't have calculated next trigger date: ${e}`);
  }
}

Dismiss notifications

getPresentedNotificationsAsync(): Promise<Notification[]>

Fetches information about all notifications present in the notification tray (Notification Center).

This method is not supported on Android below 6.0 (API level 23) – on these devices it will resolve to an empty array.

Returns

A Promise resolves with a list of notifications (Notification) currently present in the notification tray (Notification Center).

dismissNotificationAsync(identifier: string): Promise<void>

Removes notification displayed in the notification tray (Notification Center).

Arguments

The first and only argument to the function is the notification identifier, obtained either in setNotificationHandler or in the listener added with addNotificationReceivedListener.

Returns

Resolves once the request to dismiss the notification is successfully dispatched to the notifications manager.

dismissAllNotificationsAsync(): Promise<void>

Removes all application's notifications displayed in the notification tray (Notification Center).

Returns

Resolves once the request to dismiss the notifications is successfully dispatched to the notifications manager.

Manage notification channels (Android-specific)

Starting in Android 8.0 (API level 26), all notifications must be assigned to a channel. For each channel, you can set the visual and auditory behavior that is applied to all notifications in that channel. Then, users can change these settings and decide which notification channels from your app should be intrusive or visible at all. (source: developer.android.com)

If you do not specify a notification channel, expo-notifications will create a fallback channel for you, named Miscellaneous. We encourage you to always ensure appropriate channels with informative names are set up for the application and to always send notifications to these channels.

Calling these methods is a no-op for platforms that do not support this feature (iOS, Web and Android below version 8.0 (26)).

getNotificationChannelsAsync(): Promise<NotificationChannel[]>

Fetches information about all known notification channels.

Returns

A Promise resolves to an array of channels. On platforms that do not support notification channels, it will always resolve to an empty array.

getNotificationChannelAsync(identifier: string): Promise<NotificationChannel | null>

Fetches information about a single notification channel.

Arguments

The only argument for this method is the channel's identifier.

Returns

A Promise resolves to the channel object (of type NotificationChannel) or to null if there was no channel found for this identifier. On platforms that do not support notification channels, it will always resolve to null.

setNotificationChannelAsync(identifier: string, channel: NotificationChannelInput): Promise<NotificationChannel | null>

Assigns the channel configuration to a channel of a specified name (creating it if need be). This method lets you assign given notification channel to a notification channel group.

Note: For some settings to be applied on all Android versions, it may be necessary to duplicate the configuration across both a single notification and it's respective notification channel. For example, for a notification to play a custom sound on Android versions below 8.0, the custom notification sound has to be set on the notification (through the NotificationContentInput), and for the custom sound to play on Android versions above 8.0, the relevant notification channel must have the custom sound configured (through the NotificationChannelInput). For more information, see "Setting custom notification sounds on Android".

Arguments

First argument to the method is the channel identifier.

Second argument is the channel's configuration of type NotificationChannelInput

Returns

A Promise resolving to the object (of type NotificationChannel) describing the modified channel or to null if the platform does not support notification channels.

deleteNotificationChannelAsync(identifier: string): Promise<void>

Removes the notification channel.

Arguments

First and only argument to the method is the channel identifier.

Returns

A Promise resolving once the channel is removed (or if there was no channel for given identifier).

getNotificationChannelGroupsAsync(): Promise<NotificationChannelGroup[]>

Fetches information about all known notification channel groups.

Returns

A Promise resolving to an array of channel groups. On platforms that do not support notification channel groups, it will always resolve to an empty array.

getNotificationChannelGroupAsync(identifier: string): Promise<NotificationChannelGroup | null>

Fetches information about a single notification channel group.

Arguments

The only argument to this method is the channel group's identifier.

Returns

A Promise resolving to the channel group object (of type NotificationChannelGroup) or to null if there was no channel group found for this identifier. On platforms that do not support notification channels, it will always resolve to null.

setNotificationChannelGroupAsync(identifier: string, channel: NotificationChannelGroupInput): Promise<NotificationChannelGroup | null>

Assigns the channel group configuration to a channel group of a specified name (creating it if need be).

Arguments

First argument to the method is the channel group identifier.

Second argument is the channel group's configuration of type NotificationChannelGroupInput

Returns

A Promise resolving to the object (of type NotificationChannelGroup) describing the modified channel group or to null if the platform does not support notification channels.

deleteNotificationChannelGroupAsync(identifier: string): Promise<void>

Removes the notification channel group and all notification channels that belong to it.

Arguments

First and only argument to the method is the channel group identifier.

Returns

A Promise resolving once the channel group is removed (or if there was no channel group for given identifier).

Manage notification categories (interactive notifications)

Notification categories allow you to create interactive push notifications, so that a user can respond directly to the incoming notification either via buttons or a text response. A category defines the set of actions a user can take, and then those actions are applied to a notification by specifying the categoryIdentifier in the NotificationContent.

image of notification categories on Android and iOS

On iOS, notification categories also allow you to customize your notifications further. With each category, not only can you set interactive actions a user can take, but you can also configure things like the placeholder text to display when the user disables notification previews for your app.

Calling one of the following methods is a no-op on Web.

setNotificationCategoryAsync(identifier: string, actions: NotificationAction[], options: CategoryOptions): Promise<NotificationCategory | null>

Arguments

  • identifier: A string to associate as the ID of this category. You will pass this string in as the categoryIdentifier in your NotificationContent to associate a notification with this category. Don't use the characters : or - in your category identifier. If you do, categories might not work as expected.
  • actions: An array of NotificationActions, which describe the actions associated with this category. Each of these actions takes the shape:
    • identifier: A unique string that identifies this action. If a user takes this action (for example, selects this button in the system's Notification UI), your app will receive this actionIdentifier via the NotificationResponseReceivedListener.
    • buttonTitle: The title of the button triggering this action.
    • textInput: Optional object which, if provided, will result in a button that prompts the user for a text response.
      • submitButtonTitle: (iOS only) A string which will be used as the title for the button used for submitting the text response.
      • placeholder: A string that serves as a placeholder until the user begins typing. Defaults to no placeholder string.
    • options: Optional object of additional configuration options.
      • opensAppToForeground: Boolean indicating whether triggering this action foregrounds the app (defaults to true). If false and your app is killed (not just backgrounded), NotificationResponseReceived listeners will not be triggered when a user selects this action.
      • isAuthenticationRequired: (iOS only) Boolean indicating whether triggering the action will require authentication from the user.
      • isDestructive: (iOS only) Boolean indicating whether the button title will be highlighted a different color (usually red). This usually signifies a destructive action such as deleting data.
  • options: An optional object of additional configuration options for your category (these are all iOS only):
    • previewPlaceholder: Customizable placeholder for the notification preview text. This is shown if the user has disabled notification previews for the app. Defaults to the localized iOS system default placeholder (Notification).
    • intentIdentifiers: Array of Intent Class Identifiers. When a notification is delivered, the presence of an intent identifier lets the system know that the notification is potentially related to the handling of a request made through Siri. Defaults to an empty array.
    • categorySummaryFormat: A format string for the summary description used when the system groups the category’s notifications.
    • customDismissAction: A boolean indicating whether to send actions for handling when the notification is dismissed (the user must explicitly dismiss the notification interface- ignoring a notification or flicking away a notification banner does not trigger this action). Defaults to false.
    • allowInCarPlay: A boolean indicating whether to allow CarPlay to display notifications of this type. Apps must be approved for CarPlay to make use of this feature. Defaults to false.
    • showTitle: A boolean indicating whether to show the notification's title, even if the user has disabled notification previews for the app. Defaults to false.
    • showSubtitle: A boolean indicating whether to show the notification's subtitle, even if the user has disabled notification previews for the app. Defaults to false.
    • allowAnnouncement: A boolean indicating whether to allow notifications to be automatically read by Siri when the user is using AirPods. Defaults to false.

Returns

A Promise resolving to the category you just created.

getNotificationCategoriesAsync(): Promise<NotificationCategory[]>

Fetches information about all known notification categories.

Returns

A Promise resolving to an array of NotificationCategorys. On platforms that do not support notification channels, it will always resolve to an empty array.

deleteNotificationCategoryAsync(identifier: string): Promise<boolean>

Deletes the category associated with the provided identifier.

Arguments

Identifier initially provided to setNotificationCategoryAsync when creating the category.

Returns

A Promise resolving to true if the category was successfully deleted, or false if it was not. An example of when this method would return false is if you try to delete a category that doesn't exist.

Types

DevicePushToken

In simple terms, an object of type: Platform.OS and data: any. The data type depends on the environment -- on a native device it will be a string, which you can then use to send notifications via Firebase Cloud Messaging (Android) or APNs (iOS); on web it will be a registration object (VAPID).

export interface NativeDevicePushToken {
  type: 'ios' | 'android';
  data: string;
}

export interface WebDevicePushToken {
  type: 'web';
  data: {
    endpoint: string;
    keys: {
      p256dh: string;
      auth: string;
    };
  };
}

export type DevicePushToken = NativeDevicePushToken | WebDevicePushToken;

PushTokenListener

A function accepting a device push token (DevicePushToken) as an argument.

Note: You should not call getDevicePushTokenAsync inside this function, as it triggers the listener and may lead to an infinite loop.

ExpoPushToken

Borrowing from DevicePushToken a little bit, it's an object of type: 'expo' and data: string. You can use the data value to send notifications via Expo Notifications service.

export interface ExpoPushToken {
  type: 'expo';
  data: string;
}

Subscription

A common-in-React-Native type to abstract an active subscription. Call .remove() to remove the subscription. You can then discard the object.

export type Subscription = {
  remove: () => void;
};

Notification

An object represents a single notification that has been triggered by some request (NotificationRequest) at some point in time.

export interface Notification {
  date: number;
  request: NotificationRequest;
}

NotificationRequest

An object represents a request to present a notification. It has content — how it's being represented — and a trigger — what triggers the notification. Many notifications (Notification) may be triggered with the same request (eg. a repeating notification).

export interface NotificationRequest {
  identifier: string;
  content: NotificationContent;
  trigger: NotificationTrigger;
}

NotificationContent

An object represents notification's content.

export type NotificationContent = {
  // Notification title - the bold text displayed above the rest of the content
  title: string | null;
  // On iOS - subtitle - the bold text displayed between title and the rest of the content
  // On Android - subText - the display depends on the platform
  subtitle: string | null;
  // Notification body - the main content of the notification
  body: string | null;
  // Data associated with the notification, not displayed
  data: { [key: string]: unknown };
  // Application badge number associated with the notification
  badge: number | null;
  sound: 'default' | 'defaultCritical' | 'custom' | null;
  categoryIdentifier: string | null;
} & (
  | {
      // iOS-specific additions
      // See https://developer.apple.com/documentation/usernotifications/unnotificationcontent?language=objc
      // for more information on specific fields.
      launchImageName: string | null;
      attachments: {
        identifier: string | null;
        url: string | null;
        type: string | null;
      }[];
      summaryArgument?: string | null;
      summaryArgumentCount?: number;
      threadIdentifier: string | null;
      targetContentIdentifier?: string;
    }
  | {
      // Android-specific additions
      // See https://developer.android.com/reference/android/app/Notification.html#fields
      // for more information on specific fields.
      priority?: AndroidNotificationPriority;
      vibrationPattern?: number[];
      // Format: '#AARRGGBB'
      color?: string;
    }
);

NotificationContentInput

An object represents notification content that you pass in to presentNotificationAsync or as a part of NotificationRequestInput.

export interface NotificationContentInput {
  // Fields corresponding to NotificationContent
  title?: string;
  subtitle?: string;
  body?: string;
  data?: { [key: string]: unknown };
  badge?: number;
  sound?: boolean | string;

  // Android-specific fields
  // See https://developer.android.com/reference/android/app/Notification.html#fields
  // for more information on specific fields.
  vibrate?: boolean | number[];
  priority?: AndroidNotificationPriority;
  // Format: '#AARRGGBB', '#RRGGBB' or one of the named colors,
  // see https://developer.android.com/reference/kotlin/android/graphics/Color?hl=en
  color?: string;
  // If set to false, the notification will not be automatically dismissed when clicked.
  // The setting used when the value is not provided or is invalid is true (the notification
  // will be dismissed automatically). Corresponds directly to Android's `setAutoCancel`
  // behavior. In Firebase terms this property of a notification is called `sticky`.
  // See:
  // - https://developer.android.com/reference/android/app/Notification.Builder#setAutoCancel(boolean),
  // - https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages#AndroidNotification.FIELDS.sticky
  autoDismiss?: boolean;
  // If set to true, the notification cannot be dismissed by swipe. This setting defaults
  // to false if not provided or is invalid. Corresponds directly do Android's `isOngoing` behavior.
  // See: https://developer.android.com/reference/android/app/Notification.Builder#setOngoing(boolean)
  sticky?: boolean;

  // iOS-specific fields
  // See https://developer.apple.com/documentation/usernotifications/unmutablenotificationcontent?language=objc
  // for more information on specific fields.
  launchImageName?: string;
  attachments?: {
    url: string;
    identifier?: string;

    typeHint?: string;
    hideThumbnail?: boolean;
    thumbnailClipArea?: { x: number; y: number; width: number; height: number };
    thumbnailTime?: number;
  }[];
}

NotificationRequestInput

An object represents a notification request you can pass into scheduleNotificationAsync.

export interface NotificationRequestInput {
  identifier?: string;
  content: NotificationContentInput;
  trigger: NotificationTriggerInput;
}

AndroidNotificationPriority

An enum corresponding to values appropriate for Android's Notification#priority field.

export enum AndroidNotificationPriority {
  MIN = 'min',
  LOW = 'low',
  DEFAULT = 'default',
  HIGH = 'high',
  MAX = 'max',
}

NotificationTrigger

A union type containing different triggers which may cause the notification to be delivered to the application.

export type NotificationTrigger =
  | PushNotificationTrigger
  | CalendarNotificationTrigger
  | LocationNotificationTrigger
  | TimeIntervalNotificationTrigger
  | DailyNotificationTrigger
  | UnknownNotificationTrigger;

PushNotificationTrigger

An object represents a notification delivered by a push notification system.

On Android under remoteMessage field a JS version of the Firebase RemoteMessage may be accessed. On iOS under payload you may find full contents of UNNotificationContent's userInfo, which is the remote notification payload

export type PushNotificationTrigger = { type: 'push' } & (
  | { payload: Record<string, unknown> } // iOS
  | { remoteMessage: FirebaseRemoteMessage } // Android
  | {}
);

FirebaseRemoteMessage

A Firebase RemoteMessage that caused the notification to be delivered to the app.

export interface FirebaseRemoteMessage {
  collapseKey: string | null;
  data: { [key: string]: string };
  from: string | null;
  messageId: string | null;
  messageType: string | null;
  originalPriority: number;
  priority: number;
  sentTime: number;
  to: string | null;
  ttl: number;
  notification: null | {
    body: string | null;
    bodyLocalizationArgs: string[] | null;
    bodyLocalizationKey: string | null;
    channelId: string | null;
    clickAction: string | null;
    color: string | null;
    usesDefaultLightSettings: boolean;
    usesDefaultSound: boolean;
    usesDefaultVibrateSettings: boolean;
    eventTime: number | null;
    icon: string | null;
    imageUrl: string | null;
    lightSettings: number[] | null;
    link: string | null;
    localOnly: boolean;
    notificationCount: number | null;
    notificationPriority: number | null;
    sound: string | null;
    sticky: boolean;
    tag: string | null;
    ticker: string | null;
    title: string | null;
    titleLocalizationArgs: string[] | null;
    titleLocalizationKey: string | null;
    vibrateTimings: number[] | null;
    visibility: number | null;
  };
}

TimeIntervalNotificationTrigger

A trigger related to an elapsed time interval. May be repeating (see repeats field).

export interface TimeIntervalNotificationTrigger {
  type: 'timeInterval';
  repeats: boolean;
  seconds: number;
}

DailyNotificationTrigger

A trigger related to a daily notification. This is an Android-only type, the same functionality will be achieved on iOS with a CalendarNotificationTrigger.

export interface DailyNotificationTrigger {
  type: 'daily';
  hour: number;
  minute: number;
}

WeeklyNotificationTrigger

A trigger related to a weekly notification. This is an Android-only type, the same functionality will be achieved on iOS with a CalendarNotificationTrigger.

export interface WeeklyNotificationTrigger {
  type: 'weekly';
  weekday: number;
  hour: number;
  minute: number;
}

YearlyNotificationTrigger

A trigger related to a yearly notification. This is an Android-only type, the same functionality will be achieved on iOS with a CalendarNotificationTrigger.

export interface YearlyNotificationTrigger {
  type: 'yearly';
  day: number;
  month: number;
  hour: number;
  minute: number;
}

CalendarNotificationTrigger

A trigger related to a UNCalendarNotificationTrigger, available only on iOS.

export interface CalendarNotificationTrigger {
  type: 'calendar';
  repeats: boolean;
  dateComponents: {
    era?: number;
    year?: number;
    month?: number;
    day?: number;
    hour?: number;
    minute?: number;
    second?: number;
    weekday?: number;
    weekdayOrdinal?: number;
    quarter?: number;
    weekOfMonth?: number;
    weekOfYear?: number;
    yearForWeekOfYear?: number;
    nanosecond?: number;
    isLeapMonth: boolean;
    timeZone?: string;
    calendar?: string;
  };
}

LocationNotificationTrigger

A trigger related to a UNLocationNotificationTrigger, available only on iOS.

export interface LocationNotificationTrigger {
  type: 'location';
  repeats: boolean;
  region: CircularRegion | BeaconRegion;
}

interface Region {
  type: string;
  identifier: string;
  notifyOnEntry: boolean;
  notifyOnExit: boolean;
}

export interface CircularRegion extends Region {
  type: 'circular';
  radius: number;
  center: {
    latitude: number;
    longitude: number;
  };
}

export interface BeaconRegion extends Region {
  type: 'beacon';
  notifyEntryStateOnDisplay: boolean;
  major: number | null;
  minor: number | null;
  uuid?: string;
  beaconIdentityConstraint?: {
    uuid: string;
    major: number | null;
    minor: number | null;
  };
}

UnknownNotificationTrigger

Represents a notification trigger that is unknown to expo-notifications and that it didn't know how to serialize for JS.

export interface UnknownNotificationTrigger {
  type: 'unknown';
}

NotificationTriggerInput

A type represents possible triggers with which you can schedule notifications. A null trigger means that the notification should be scheduled for delivery immediately.

export type NotificationTriggerInput =
  | null
  | ChannelAwareTriggerInput
  | SchedulableNotificationTriggerInput;

SchedulableNotificationTriggerInput

A type represents time-based, schedulable triggers. For these triggers you can check the next trigger date with getNextTriggerDateAsync.

export type SchedulableNotificationTriggerInput =
  | DateTriggerInput
  | TimeIntervalTriggerInput
  | DailyTriggerInput
  | WeeklyTriggerInput
  | YearlyTriggerInput
  | CalendarTriggerInput;

ChannelAwareTriggerInput

A trigger that will cause the notification to be delivered immediately.

export type ChannelAwareTriggerInput = {
  channelId: string;
};

DateTriggerInput

A trigger that will cause the notification to be delivered once at the specified Date. If you pass in a number it will be interpreted as a Unix timestamp.

export type DateTriggerInput = Date | number | { channelId?: string; date: Date | number };

TimeIntervalTriggerInput

A trigger that will cause the notification to be delivered once or many times (depends on the repeats field) after seconds time elapse.

On iOS, when repeats is true, the time interval must be 60 seconds or greater. Otherwise, the notification won't be triggered.

export interface TimeIntervalTriggerInput {
  channelId?: string;
  repeats?: boolean;
  seconds: number;
}

DailyTriggerInput

A trigger that will cause the notification to be delivered once per day.

export interface DailyTriggerInput {
  channelId?: string;
  hour: number;
  minute: number;
  repeats: true;
}

WeeklyTriggerInput

A trigger that will cause the notification to be delivered once every week.

Note: Weekdays are specified with a number from 1 through 7, with 1 indicating Sunday.

export interface WeeklyTriggerInput {
  channelId?: string;
  weekday: number;
  hour: number;
  minute: number;
  repeats: true;
}

YearlyTriggerInput

A trigger that will cause the notification to be delivered once every year.

Note: all properties are specified in JavaScript Date's ranges.

export interface YearlyTriggerInput {
  channelId?: string;
  day: number;
  month: number;
  hour: number;
  minute: number;
  repeats: true;
}

CalendarTriggerInput

A trigger that will cause the notification to be delivered once or many times when the date components match the specified values. Corresponds to native UNCalendarNotificationTrigger.

Note: This type of trigger is only available on iOS.

export interface CalendarTriggerInput {
  channelId?: string;
  repeats?: boolean;
  timezone?: string;

  year?: number;
  month?: number;
  weekday?: number;
  weekOfMonth?: number;
  weekOfYear?: number;
  weekdayOrdinal?: number;
  day?: number;

  hour?: number;
  minute?: number;
  second?: number;
}

NotificationResponse

An object represents user's interaction with the notification.

Note: If the user taps on a notification actionIdentifier will be equal to Notifications.DEFAULT_ACTION_IDENTIFIER.

export interface NotificationResponse {
  notification: Notification;
  actionIdentifier: string;
  userText?: string;
}

NotificationBehavior

An object represents behavior that should be applied to the incoming notification.

export interface NotificationBehavior {
  shouldShowAlert: boolean;
  shouldPlaySound: boolean;
  shouldSetBadge: boolean;
  priority?: AndroidNotificationPriority;
}

On Android, setting shouldPlaySound: false will result in the drop-down notification alert not showing, no matter what the priority is. This setting will also override any channel-specific sounds you may have configured.

NotificationChannel

An object represents a notification channel (feature available only on Android).

export enum AndroidNotificationVisibility {
  UNKNOWN,
  PUBLIC,
  PRIVATE,
  SECRET,
}

export enum AndroidAudioContentType {
  UNKNOWN,
  SPEECH,
  MUSIC,
  MOVIE,
  SONIFICATION,
}

export enum AndroidImportance {
  UNKNOWN,
  UNSPECIFIED,
  NONE,
  MIN,
  LOW,
  DEFAULT,
  HIGH,
  MAX,
}

export enum AndroidAudioUsage {
  UNKNOWN,
  MEDIA,
  VOICE_COMMUNICATION,
  VOICE_COMMUNICATION_SIGNALLING,
  ALARM,
  NOTIFICATION,
  NOTIFICATION_RINGTONE,
  NOTIFICATION_COMMUNICATION_REQUEST,
  NOTIFICATION_COMMUNICATION_INSTANT,
  NOTIFICATION_COMMUNICATION_DELAYED,
  NOTIFICATION_EVENT,
  ASSISTANCE_ACCESSIBILITY,
  ASSISTANCE_NAVIGATION_GUIDANCE,
  ASSISTANCE_SONIFICATION,
  GAME,
}

export interface AudioAttributes {
  usage: AndroidAudioUsage;
  contentType: AndroidAudioContentType;
  flags: {
    enforceAudibility: boolean;
    requestHardwareAudioVideoSynchronization: boolean;
  };
}

export interface NotificationChannel {
  id: string;
  name: string | null;
  importance: AndroidImportance;
  bypassDnd: boolean;
  description: string | null;
  groupId?: string | null;
  lightColor: string;
  lockscreenVisibility: AndroidNotificationVisibility;
  showBadge: boolean;
  sound: 'default' | 'custom' | null;
  audioAttributes: AudioAttributes;
  vibrationPattern: number[] | null;
  enableLights: boolean;
  enableVibrate: boolean;
}

NotificationChannelInput

An object represents a notification channel to be set.

export interface NotificationChannelInput {
  name: string | null;
  importance: AndroidImportance;
  // Optional attributes
  bypassDnd?: boolean;
  description?: string | null;
  groupId?: string | null;
  lightColor?: string;
  lockscreenVisibility?: AndroidNotificationVisibility;
  showBadge?: boolean;
  sound?: string | null;
  audioAttributes?: Partial<AudioAttributes>;
  vibrationPattern?: number[] | null;
  enableLights?: boolean;
  enableVibrate?: boolean;
}

NotificationChannelGroup

An object represents a notification channel group (feature available only on Android).

export interface NotificationChannelGroup {
  id: string;
  name: string | null;
  description?: string | null;
  isBlocked?: boolean;
  channels: NotificationChannel[];
}

NotificationChannelGroupInput

An object represents a notification channel group to be set.

export interface NotificationChannelGroupInput {
  name: string | null;
  description?: string | null;
}

NotificationCategory

export interface NotificationCategory {
  identifier: string;
  actions: NotificationAction[];
  options: {
    // These options are ALL iOS-only
    previewPlaceholder?: string;
    intentIdentifiers?: string[];
    categorySummaryFormat?: string;
    customDismissAction?: boolean;
    allowInCarPlay?: boolean;
    showTitle?: boolean;
    showSubtitle?: boolean;
    allowAnnouncement?: boolean;
  };
}

NotificationAction

export interface NotificationAction {
  identifier: string;
  buttonTitle: string;
  textInput?: {
    submitButtonTitle: string;
    placeholder: string;
  };
  options: {
    isDestructive?: boolean;
    isAuthenticationRequired?: boolean;
    opensAppToForeground?: boolean;
  };
}

NotificationPermissionsStatus

export interface NotificationPermissionsStatus {
  status: 'granted' | 'undetermined' | 'denied'; // on iOS, you should check `ios.status`
  granted: boolean;
  expires: 'never' | number;
  canAskAgain: boolean;
  android?: {
    importance: number;
    interruptionFilter?: number;
  };
  ios?: {
    status: IosAuthorizationStatus;
    allowsDisplayInNotificationCenter: boolean | null;
    allowsDisplayOnLockScreen: boolean | null;
    allowsDisplayInCarPlay: boolean | null;
    allowsAlert: boolean | null;
    allowsBadge: boolean | null;
    allowsSound: boolean | null;
    allowsCriticalAlerts?: boolean | null;
    alertStyle: IosAlertStyle;
    allowsPreviews?: IosAllowsPreviews;
    providesAppNotificationSettings?: boolean;
    allowsAnnouncements?: boolean | null;
  };
}