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.

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 are installing this in an existing React Native app (bare workflow), start by installing expo in your project. Then, follow the additional instructions as mentioned by library's README under "Installation in bare React Native projects" section.

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;
    }
    // Learn more about projectId:
    // https://docs.expo.dev/push-notifications/push-notifications-setup/#configure-projectid
    token = (await Notifications.getExpoPushTokenAsync({ projectId: 'your-project-id' })).data;
    console.log(token);
  } else {
    alert('Must use physical device for Push Notifications');
  }

  return token;
}

Present the notification to the user

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,
});

Handle push notifications with navigation

If you'd like to deep link to a specific screen in your app when you receive a push notification, you can configure either of Expo's navigation systems to do that.

You can use Expo Router's built-in deep linking to handle incoming URLs from push notifications. Simply configure the root layout to listen for incoming and initial notification events.

app/_layout.tsx
import { useEffect } from 'react';
import * as Notifications from 'expo-notifications';
import { router } from 'expo-router';

function useNotificationObserver() {
  useEffect(() => {
    let isMounted = true;

    function redirect(notification: Notifications.Notification) {
      const url = notification.request.content.data?.url;
      if (url) {
        router.push(url);
      }
    }

    Notifications.getLastNotificationResponseAsync()
      .then(response => {
        if (!isMounted || !response?.notification) {
          return;
        }
        redirect(response?.notification);
      });

    const subscription = Notifications.addNotificationResponseReceivedListener(response => {
      redirect(response.notification);
    });

    return () => {
      isMounted = false;
      subscription.remove();
    };
  }, []);
}

export default function Layout() {
  useNotificationObserver();

  return <Slot />;
}

React Navigation's manual linking configuration can be configured to handle incoming redirects from push notifications:

App.tsx
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();

          return response?.notification.request.content.data.url;
        },
        subscribe(listener) {
          const onReceiveURL = ({ url }: { url: string }) => listener(url);

          // Listen to incoming links from deep linking
          const eventListenerSubscription = 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
            eventListenerSubscription.remove();
            subscription.remove();
          };
        },
      }}>
      {/* Your app content */}
    </NavigationContainer>
  );
}

See more details on React Navigation documentation.

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#ffffff
Only 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.

Notification events listeners

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
falseForeground or BackgroundBackgroundNotificationTask
falseKillednone
trueForegroundNotificationReceivedListener & NotificationResponseReceivedListener
trueBackgroundNotificationResponseReceivedListener
trueKilledNotificationResponseReceivedListener

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

Background notifications

Background event listeners are not supported in Expo Go.

A background notification (iOS) or a data-only notification (Android) is a remote notification that does not display an alert, play a sound, or add a badge to your app's icon. The purpose of a background notification is to provide a way to wake up your app to trigger an app data refresh in the background.

To handle notifications while the app is in the background on iOS, add remote-notification as a value to the array under ios.infoPlist.UIBackgroundModes key in your app config, 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.

On Android, data-only notifications are sent using the data key of the push notification request payload.

Additional information

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 and then under the sounds key, provide an array of local paths to sound files that can be used as custom notification sounds. These local paths are local to your project.

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',
  importance: Notifications.AndroidImportance.HIGH,
  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: {
    // ...
  },
});

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;
}

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 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.

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.

Notification categories are not supported on the web and all related methods will result in noop.

Platform specific guides

Handling notification channels 
Android 8+

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, as Android developer docs states.

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 (Android below version 8.0 (26), iOS and web).

Custom notification icon and colors 
Android

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.

API

import * as Notifications from 'expo-notifications';

Fetch tokens for push notifications

addPushTokenListener(listener)

NameTypeDescription
listenerPushTokenListener

A function accepting a push token as an argument, it will be called whenever the push token changes.


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.

Returns:

Subscription

Example

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
  );
}

getDevicePushTokenAsync()

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

Returns:

Promise<DevicePushToken>

getExpoPushTokenAsync(options)

NameTypeDescription
options
(optional)
ExpoPushTokenOptions

Object allowing you to pass in push notification configuration.

Default: {}

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.

Returns:

Promise<ExpoPushToken>

Returns a Promise that resolves to an object representing acquired push token.

Example

import * as Notifications from 'expo-notifications';

export async function registerForPushNotificationsAsync(userId: string) {
  const expoPushToken = await Notifications.getExpoPushTokenAsync({
   projectId: 'your-project-id',
  });

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

removePushTokenSubscription(subscription)

NameTypeDescription
subscriptionSubscription

A subscription returned by addPushTokenListener method.


Removes a push token subscription returned by an addPushTokenListener call.

Returns:

void

Listen to notification events

addNotificationReceivedListener(listener)

NameTypeDescription
listener(event: Notification) => void

A function accepting a notification (Notification) as an argument.


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

Returns:

Subscription

A Subscription object represents the subscription of the provided listener.

Example

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
  );
}

addNotificationResponseReceivedListener(listener)

NameTypeDescription
listener(event: NotificationResponse) => void

A function accepting notification response (NotificationResponse) as an argument.


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

Returns:

Subscription

A Subscription object represents the subscription of the provided listener.

Example

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
  );
}

addNotificationsDroppedListener(listener)

NameTypeDescription
listener() => void

A callback function.


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.

Returns:

Subscription

A Subscription object represents the subscription of the provided listener.

getLastNotificationResponseAsync()

Returns:

Promise<NotificationResponse | null>

removeNotificationSubscription(subscription)

NameTypeDescription
subscriptionSubscription

A subscription returned by addNotificationListener method.


Removes a notification subscription returned by an addNotificationListener call.

Returns:

void

useLastNotificationResponse()

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:

undefined | null | NotificationResponse

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.

Example

(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 content
  );
}

Handle incoming notifications when the app is in the foreground

setNotificationHandler(handler)

NameTypeDescription
handlernull | NotificationHandler

A single parameter which should be either null (if you want to clear the handler) or a NotificationHandler object.


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.

Returns:

void

Example

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

registerTaskAsync(taskName)

NameTypeDescription
taskNamestring

The string you passed to TaskManager.defineTask as the taskName parameter.


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 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 PushNotificationTrigger 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.
Returns:

Promise<null>

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)

NameTypeDescription
taskNamestring

The string you passed to registerTaskAsync as the taskName parameter.


Used to unregister tasks registered with registerTaskAsync method.

Returns:

Promise<null>

Fetch information about notifications-related permissions

getPermissionsAsync()

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, etc. There is no user-facing effect of calling this.

Returns:

Promise<NotificationPermissionsStatus>

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

Example

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(permissions)

NameTypeDescription
permissions
(optional)
NotificationPermissionsRequest

An object representing configuration for the request scope.


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.

Returns:

Promise<NotificationPermissionsStatus>

Example

import * as Notifications from 'expo-notifications';

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

Manage application badge icon

getBadgeCountAsync()

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:

Promise<number>

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

setBadgeCountAsync(badgeCount, options)

NameTypeDescription
badgeCountnumber

The count which should appear on the badge. A value of 0 will clear the badge.

options
(optional)
SetBadgeCountOptions

An object of options configuring behavior applied in Web environment.


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.

Returns:

Promise<boolean>

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

Schedule notifications

cancelAllScheduledNotificationsAsync()

Cancels all scheduled notifications.

Returns:

Promise<void>

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

cancelScheduledNotificationAsync(identifier)

NameTypeDescription
identifierstring

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


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

Returns:

Promise<void>

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

Example

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);
}

getAllScheduledNotificationsAsync()

Fetches information about all scheduled notifications.

Returns:

Promise<NotificationRequest[]>

getNextTriggerDateAsync(trigger)

NameTypeDescription
triggerSchedulableNotificationTriggerInput

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


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

Returns:

Promise<number | null>

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.

Example

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}`);
  }
}

Deprecated This method has been deprecated in favor of using an explicit NotificationHandler and the scheduleNotificationAsync method. More information can be found in our FYI document.

presentNotificationAsync(content, identifier)

NameTypeDescription
contentNotificationContentInput

An object representing the notification content.

identifier
(optional)
string-

Schedules a notification for immediate trigger.

Returns:

Promise<string>

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

scheduleNotificationAsync(request)

NameTypeDescription
requestNotificationRequestInput

An object describing the notification to be triggered.


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.

Returns:

Promise<string>

Returns a Promise resolving to a string which is a notification identifier you can later use to cancel the notification or to identify an incoming notification.

Example

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,
});

Dismiss notifications

dismissAllNotificationsAsync()

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

Returns:

Promise<void>

A Promise which resolves once the request to dismiss the notifications is successfully dispatched to the notifications manager.

dismissNotificationAsync(notificationIdentifier)

NameTypeDescription
notificationIdentifierstring

The notification identifier, obtained either via setNotificationHandler method or in the listener added with addNotificationReceivedListener.


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

Returns:

Promise<void>

A Promise which resolves once the request to dismiss the notification is successfully dispatched to the notifications manager.

getPresentedNotificationsAsync()

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:

Promise<Notification[]>

Manage notification channels (Android-specific)

Only for:
Android

deleteNotificationChannelAsync(channelId)

NameTypeDescription
channelIdstring

The channel identifier.


Removes the notification channel.

Returns:

Promise<void>

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

Only for:
Android

deleteNotificationChannelGroupAsync(groupId)

NameTypeDescription
groupIdstring

The channel group identifier.


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

Returns:

Promise<void>

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

Only for:
Android

getNotificationChannelAsync(channelId)

NameTypeDescription
channelIdstring

The channel's identifier.


Fetches information about a single notification channel.

Returns:

Promise<NotificationChannel | null>

Only for:
Android

getNotificationChannelGroupAsync(groupId)

NameTypeDescription
groupIdstring

The channel group's identifier.


Fetches information about a single notification channel group.

Returns:

Promise<NotificationChannelGroup | null>

Only for:
Android

getNotificationChannelGroupsAsync()

Fetches information about all known notification channel groups.

Returns:

Promise<NotificationChannelGroup[]>

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

Only for:
Android

getNotificationChannelsAsync()

Fetches information about all known notification channels.

Returns:

Promise<NotificationChannel[]>

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

Only for:
Android

setNotificationChannelAsync(channelId, channel)

NameTypeDescription
channelIdstring

The channel identifier.

channelNotificationChannelInput

Object representing the channel's configuration.


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 its 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 Set custom notification sounds on Android.

Returns:

Promise<NotificationChannel | null>

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

Only for:
Android

setNotificationChannelGroupAsync(groupId, group)

NameTypeDescription
groupIdstring

The channel group's identifier.

groupNotificationChannelGroupInput

Object representing the channel group configuration.


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

Returns:

Promise<NotificationChannelGroup | null>

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.

Manage notification categories (interactive notifications)

Only for:
Android
iOS

deleteNotificationCategoryAsync(identifier)

NameTypeDescription
identifierstring

Identifier initially provided to setNotificationCategoryAsync when creating the category.


Deletes the category associated with the provided identifier.

Returns:

Promise<boolean>

A Promise which resolves 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.

Only for:
Android
iOS

getNotificationCategoriesAsync()

Fetches information about all known notification categories.

Returns:

Promise<NotificationCategory[]>

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

Only for:
Android
iOS

setNotificationCategoryAsync(identifier, actions, options)

NameTypeDescription
identifierstring

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.

actionsNotificationAction[]

An array of NotificationActions, which describe the actions associated with this category.

options
(optional)
NotificationCategoryOptions

An optional object of additional configuration options for your category.


Sets the new notification category.

Returns:

Promise<NotificationCategory>

A Promise which resolves to the category you just have created.

Constants

Notifications.DEFAULT_ACTION_IDENTIFIER

Type: 'expo.modules.notifications.actions.DEFAULT'

Methods

Notifications.setAutoServerRegistrationEnabledAsync(enabled)

NameType
enabledboolean

Sets the registration information so that the device push token gets pushed to the given registration endpoint

Returns:

Promise<void>

Notifications.unregisterForNotificationsAsync()

Returns:

Promise<void>

Interfaces

AudioAttributes

AudioAttributes Properties

NameTypeDescription
contentTypeAndroidAudioContentType-
flags{ enforceAudibility: boolean, requestHardwareAudioVideoSynchronization: boolean }-
usageAndroidAudioUsage-

Only for:
iOS

BeaconRegion

Extends: Region

A region used to detect the presence of iBeacon devices. Based on Core Location CLBeaconRegion class.

BeaconRegion Properties

NameTypeDescription
beaconIdentityConstraint
(optional)
{ major: null | number, minor: null | number, uuid: string }

The beacon identity constraint that defines the beacon region.

majornull | number

The major value from the beacon identity constraint that defines the beacon region.

minornull | number

The minor value from the beacon identity constraint that defines the beacon region.

notifyEntryStateOnDisplayboolean

A Boolean value that indicates whether Core Location sends beacon notifications when the device’s display is on.

type'beacon'-
uuid
(optional)
string

The UUID value from the beacon identity constraint that defines the beacon region.


Only for:
iOS

CalendarNotificationTrigger

A trigger related to a UNCalendarNotificationTrigger.

CalendarNotificationTrigger Properties

NameTypeDescription
dateComponents{ calendar: string, day: number, era: number, hour: number, isLeapMonth: boolean, minute: number, month: number, nanosecond: number, quarter: number, second: number, timeZone: string, weekOfMonth: number, weekOfYear: number, weekday: number, weekdayOrdinal: number, year: number, yearForWeekOfYear: number }-
repeatsboolean-
type'calendar'-

Only for:
iOS

CircularRegion

Extends: Region

A circular geographic region, specified as a center point and radius. Based on Core Location CLCircularRegion class.

CircularRegion Properties

NameTypeDescription
center{ latitude: number, longitude: number }

The center point of the geographic area.

radiusnumber

The radius (measured in meters) that defines the geographic area’s outer boundary.

type'circular'-

Only for:
Android

DailyNotificationTrigger

A trigger related to a daily notification.

The same functionality will be achieved on iOS with a CalendarNotificationTrigger.

DailyNotificationTrigger Properties

NameTypeDescription
hournumber-
minutenumber-
type'daily'-

DailyTriggerInput

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

DailyTriggerInput Properties

NameTypeDescription
channelId
(optional)
string-
hournumber-
minutenumber-
repeatstrue-

ExpoPushToken

Borrowing structure from DevicePushToken a little. You can use the data value to send notifications via Expo Notifications service.

ExpoPushToken Properties

NameTypeDescription
datastring

The acquired push token.

type'expo'

Always set to "expo".


ExpoPushTokenOptions

ExpoPushTokenOptions Properties

NameTypeDescription
applicationId
(optional)
string

The ID of the application to which the token should be attributed. Defaults to Application.applicationId exposed by expo-application.

baseUrl
(optional)
string

Endpoint URL override.

development
(optional)
boolean
Only for:
iOS

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.

deviceId
(optional)
string-
devicePushToken
(optional)
DevicePushToken

The device push token with which to register at the backend. Defaults to a token fetched with getDevicePushTokenAsync().

projectId
(optional)
string

The ID of the project to which the token should be attributed. Defaults to Constants.expoConfig.extra.eas.projectId exposed by expo-constants.

When using EAS Build, this value is automatically set. However, it is recommended to set it manually. Once you have EAS Build configured, you can find the value in app.json under extra.eas.projectId. You can copy and paste it into your code. If you are not using EAS Build, it will fallback to Constants.expoConfig?.extra?.eas?.projectId.

type
(optional)
string

Request body override.

url
(optional)
string

Request URL override.


FirebaseRemoteMessage

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

FirebaseRemoteMessage Properties

NameTypeDescription
collapseKeynull | string-
dataRecord<string, string>-
fromnull | string-
messageIdnull | string-
messageTypenull | string-
notificationnull | FirebaseRemoteMessageNotification-
originalPrioritynumber-
prioritynumber-
sentTimenumber-
tonull | string-
ttlnumber-

FirebaseRemoteMessageNotification

FirebaseRemoteMessageNotification Properties

NameTypeDescription
bodynull | string-
bodyLocalizationArgsnull | string[]-
bodyLocalizationKeynull | string-
channelIdnull | string-
clickActionnull | string-
colornull | string-
eventTimenull | number-
iconnull | string-
imageUrlnull | string-
lightSettingsnull | number[]-
linknull | string-
localOnlyboolean-
notificationCountnull | number-
notificationPrioritynull | number-
soundnull | string-
stickyboolean-
tagnull | string-
tickernull | string-
titlenull | string-
titleLocalizationArgsnull | string[]-
titleLocalizationKeynull | string-
usesDefaultLightSettingsboolean-
usesDefaultSoundboolean-
usesDefaultVibrateSettingsboolean-
vibrateTimingsnull | number[]-
visibilitynull | number-

IosNotificationPermissionsRequest

Available configuration for permission request on iOS platform. See Apple documentation for UNAuthorizationOptions to learn more.

IosNotificationPermissionsRequest Properties

NameTypeDescription
allowAlert
(optional)
boolean

The ability to display alerts.

allowAnnouncements
(optional)
boolean
Deprecated

The ability for Siri to automatically read out messages over AirPods.

allowBadge
(optional)
boolean

The ability to update the app’s badge.

allowCriticalAlerts
(optional)
boolean

The ability to play sounds for critical alerts.

allowDisplayInCarPlay
(optional)
boolean

The ability to display notifications in a CarPlay environment.

allowProvisional
(optional)
boolean

The ability to post noninterrupting notifications provisionally to the Notification Center.

allowSound
(optional)
boolean

The ability to play sounds.

provideAppNotificationSettings
(optional)
boolean

An option indicating the system should display a button for in-app notification settings.


Only for:
iOS

LocationNotificationTrigger

A trigger related to a UNLocationNotificationTrigger.

LocationNotificationTrigger Properties

NameTypeDescription
regionCircularRegion | BeaconRegion-
repeatsboolean-
type'location'-

NativeDevicePushToken

NativeDevicePushToken Properties

NameTypeDescription
datastring-
type'ios' | 'android'-

Notification

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

Notification Properties

NameTypeDescription
datenumber-
requestNotificationRequest-

NotificationAction

NotificationAction Properties

NameTypeDescription
buttonTitlestring

The title of the button triggering this action.

identifierstring

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.

options
(optional)
{ isAuthenticationRequired: boolean, isDestructive: boolean, opensAppToForeground: boolean }