Product
Socket Now Supports uv.lock Files
Socket now supports uv.lock files to ensure consistent, secure dependency resolution for Python projects and enhance supply chain security.
expo-notifications
Advanced tools
The expo-notifications package is a library for handling notifications in Expo and React Native applications. It provides tools for scheduling, receiving, and managing both local and push notifications.
Scheduling Local Notifications
This feature allows you to schedule local notifications to be triggered at a specific time or after a certain delay.
import * as Notifications from 'expo-notifications';
async function scheduleNotification() {
await Notifications.scheduleNotificationAsync({
content: {
title: "You've got mail! 📬",
body: 'Here is the notification body',
},
trigger: { seconds: 2 },
});
}
Handling Received Notifications
This feature allows you to handle notifications when they are received, enabling you to perform actions or update the UI in response to the notification.
import * as Notifications from 'expo-notifications';
import { useEffect } from 'react';
useEffect(() => {
const subscription = Notifications.addNotificationReceivedListener(notification => {
console.log(notification);
});
return () => subscription.remove();
}, []);
Requesting Permissions
This feature allows you to request the necessary permissions from the user to send notifications.
import * as Notifications from 'expo-notifications';
async function requestPermissions() {
const { status } = await Notifications.requestPermissionsAsync();
if (status !== 'granted') {
alert('Permission not granted!');
}
}
Customizing Notification Behavior
This feature allows you to customize how notifications are handled when they are received, such as whether to show an alert, play a sound, or set a badge.
import * as Notifications from 'expo-notifications';
Notifications.setNotificationHandler({
handleNotification: async () => ({
shouldShowAlert: true,
shouldPlaySound: false,
shouldSetBadge: false,
}),
});
react-native-push-notification is a popular library for handling push notifications in React Native applications. It offers similar functionalities to expo-notifications, such as scheduling local notifications, handling received notifications, and requesting permissions. However, it requires more manual setup and configuration compared to expo-notifications, which is more integrated with the Expo ecosystem.
notifee is a powerful notification library for React Native that provides advanced features like notification channels, grouped notifications, and custom notification sounds. It offers more customization options compared to expo-notifications but also requires more setup and configuration.
react-native-firebase is a comprehensive library that includes support for Firebase Cloud Messaging (FCM) to handle push notifications. It provides robust features for managing notifications, including background message handling and analytics. It is more complex to set up compared to expo-notifications but offers deeper integration with Firebase services.
Provides an API to fetch push notification tokens and to present, schedule, receive and respond to notifications.
This library is not yet usable within managed projects — it is likely to be included in an upcoming Expo SDK release.
For bare React Native projects, you must ensure that you have installed and configured the react-native-unimodules
package before continuing.
expo install expo-notifications
Run npx pod-install
after installing the npm package.
In order to be able to receive push notifications on the device:
ios
folderIn order to be able to receive push notifications on the device ensure that your project is set up for Firebase. For more information on how to do it, see this guide.
The notification icon and the default color can be customized.
To customize the icon:
You can customize two icons: the default and the large one. See the Android documentation for more details. The steps for them are very similar. The only difference is the tag in the second step.
android/app/src/main/AndroidManifest.xml
and add a <meta-data>
tag of android:name="expo.modules.notifications.default_notification_icon"
(or android:name="expo.modules.notifications.large_notification_icon"
if you are changing the large icon) inside the <application>
node referencing the custom icon with @drawable/<notification_icon_name_you_used_in_step_1>
, like here.AndroidManifest.xml
should look more or less like this:<manifest xmlns:android="http://schemas.android.com/apk/res/android" ...>
...
<application ...>
...
<meta-data
android:name="expo.modules.notifications.default_notification_icon"
android:resource="@drawable/ic_stat_notifications" /> <!-- @drawable/<insert_notification_icon_name> -->
...
</application>
</manifest>
To customize the default color of the notification:
android/app/src/main/res/values/colors.xml
(if there is none, create it)<?xml version="1.0" encoding="utf-8"?>
declaration and have a root node of <resources>
)<resources>
node add a <color>
node with an arbitrary name (like notification_icon_color
) containing the color in HEX format inside, like here.colors.xml
should look more or less like this:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="notification_icon_color">#4630EB</color>
</resources>
expo-notifications
to use it when it displays a notification — head over to android/app/src/main/AndroidManifest.xml
and add a <meta-data>
tag of android:name="expo.modules.notifications.default_notification_color"
inside the <application>
node referencing the custom icon with @color/<notification_icon_color_name>
, like here.AndroidManifest.xml
should look more or less like this:<manifest xmlns:android="http://schemas.android.com/apk/res/android" ...>
...
<application ...>
...
<meta-data
android:name="expo.modules.notifications.default_notification_color"
android:resource="@color/notification_icon_color" /> <!-- @color/<insert_notification_icon_color_name> -->
...
</application>
</manifest>
An AndroidManifest.xml
with both color (of name notification_icon_color
) and an icon (of name ic_stat_notifications
) name would look like this:
<manifest xmlns:android="http://schemas.android.com/apk/res/android" ...>
<application ...>
...
<meta-data
android:name="expo.modules.notifications.default_notification_icon"
android:resource="@drawable/ic_stat_notifications" />
<meta-data
android:name="expo.modules.notifications.default_notification_color"
android:resource="@color/notification_icon_color" />
...
</application>
</manifest>
If you would like to send notifications with Expo servers, the servers will need to have a way to authenticate with APNS/FCM that they are authorized to send notifications on your behalf. To do this:
expo credentials:manager
in the root of your application,slug
and ios.bundleIdentifier
fields in app.json
so that the server knows to which experienceId
and bundleIdentifier
the key should be attributed),Contributions are very welcome! Please refer to guidelines described in the contributing guide.
The following methods are exported by the expo-notifications
module:
getExpoPushTokenAsync
-- resolves with an Expo push tokengetDevicePushTokenAsync
-- resolves with a device push tokenaddPushTokenListener
-- adds a listener called when a new push token is issuedremovePushTokenSubscription
-- removes the listener registered with addPushTokenListener
removeAllPushTokenListeners
-- removes all listeners registered with addPushTokenListener
addNotificationReceivedListener
-- adds a listener called whenever a new notification is receivedaddNotificationsDroppedListener
-- adds a listener called whenever some notifications have been droppedaddNotificationResponseReceivedListener
-- adds a listener called whenever user interacts with a notificationremoveNotificationSubscription
-- removes the listener registered with addNotification*Listener()
removeAllNotificationListeners
-- removes all listeners registered with addNotification*Listener()
setNotificationHandler
-- sets the handler function responsible for deciding what to do with a notification that is received when the app is in foregroundgetPermissionsAsync
-- fetches current permission settings related to notificationsrequestPermissionsAsync
-- requests permissions related to notificationsgetBadgeCountAsync
-- fetches the application badge number valuesetBadgeCountAsync
-- sets the application badge number valuegetAllScheduledNotificationsAsync
-- fetches information about all scheduled notificationspresentNotificationAsync
-- schedules a notification for immediate triggerscheduleNotificationAsync
-- schedules a notification to be triggered in the futurecancelScheduledNotificationAsync
-- removes a specific scheduled notificationcancelAllScheduledNotificationsAsync
-- removes all scheduled notificationsgetPresentedNotificationsAsync
-- fetches information about all notifications present in the notification tray (Notification Center)dismissNotificationAsync
-- removes a specific notification from the notification traydismissAllNotificationsAsync
-- removes all notifications from the notification traygetNotificationChannelsAsync
-- fetches information about all known notification channelsgetNotificationChannelAsync
-- fetches information about a specific notification channelsetNotificationChannelAsync
-- saves a notification channel configurationdeleteNotificationChannelAsync
-- deletes a notification channelgetNotificationChannelGroupsAsync
-- fetches information about all known notification channel groupsgetNotificationChannelGroupAsync
-- fetches information about a specific notification channel groupsetNotificationChannelGroupAsync
-- saves a notification channel group configurationdeleteNotificationChannelGroupAsync
-- deletes a notification channel groupsetNotificationCategoryAsync
-- creates a new notification category for interactive notificationsgetNotificationCategoriesAsync
-- fetches information about all active notification categoriesdeleteNotificationCategoryAsync
-- deletes a notification categoryWhen 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;
}
getExpoPushTokenAsync(options: ExpoTokenOptions): ExpoPushToken
Returns an Expo token that can be used to send a push notification to this device using Expo push notifications service. Read more in the Push Notifications guide.
Note: For Expo backend to be able to send notifications to your app, you will need to provide it with push notification keys. This can be done using
expo-cli
(expo credentials:manager
). Read more in the “Upload notifications credentials” guide. TODO
This function accepts an optional object allowing you to pass in configuration, consisting of fields (all are optional, but some may have to be defined if configuration cannot be inferred):
Constants.manifest.id
exposed by expo-constants
. You may need to define it in bare workflow, where expo-constants
doesn't expose the manifest.getDevicePushTokenAsync()
.Application.applicationId
exposed by expo-application
.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 a Promise
that resolves to an object with the following fields:
expo
.import Constants from 'expo-constants';
import * as Notifications from 'expo-notifications';
export async function registerForPushNotificationsAsync(userId: string) {
let experienceId = undefined;
if (!Constants.manifest) {
// Absence of the manifest means we're in bare workflow
experienceId = '@username/example';
}
const expoPushToken = await Notifications.getExpoPushTokenAsync({
experienceId,
});
await fetch('https://example.com/', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
userId,
expoPushToken,
}),
});
}
getDevicePushTokenAsync(): DevicePushToken
Returns a native APNS, FCM token or a PushSubscription
data that can be used with another push notification service.
A Promise
that resolves to an object with the following fields:
ios
, android
or web
.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.
A single and required argument is a function accepting a push token as an argument. It will be called whenever the push token changes.
A Subscription
object representing the subscription of the provided listener.
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 a addPushTokenListener
call.
A single and required argument is a subscription returned by addPushTokenListener
.
removeAllPushTokenListeners(): void
Removes all push token subscriptions that may have been registered with addPushTokenListener
.
addNotificationReceivedListener(listener: (event: Notification) => void): void
Listeners registered by this method will be called whenever a notification is received while the app is running.
A single and required argument is a function accepting a notification (Notification
) as an argument.
A Subscription
object representing the subscription of the provided listener.
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 notifications service on Android. It corresponds to onDeletedMessages()
callback. More information can be found in Firebase docs.
A single and required argument is a function–callback.
A Subscription
object representing 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).
A single and required argument is a function accepting notification response (NotificationResponse
) as an argument.
A Subscription
object representing the subscription of the provided listener.
Registering 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({ navigation }) {
React.useEffect(() => {
const subscription = Notifications.addNotificationResponseReceivedListener(response => {
const url = response.notification.request.content.data.url;
Linking.openUrl(url);
});
return () => subscription.remove();
}, [navigation]);
return (
// Your app content
);
}
removeNotificationSubscription(subscription: Subscription): void
Removes a notification subscription returned by a addNotification*Listener
call.
A single and required argument is a subscription returned by addNotification*Listener
.
removeAllNotificationListeners(): void
Removes all notification subscriptions that may have been registered with addNotification*Listener
.
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.
The function receives a single argument which should be either null
(if you want to clear the handler) or an object of fields:
Promise
resolving to a behavior (NotificationBehavior
) applicable to the notificationImplementing 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,
}),
});
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, etc. There is no user-facing effect of calling this.
It returns a Promise
resolving to an object representing permission settings (NotificationPermissionsStatus
).
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.
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 (a list of iOS options is available here, on Android all available permissions are granted by default and if a user declines any permission an app can't prompt the user to change).
It returns a Promise
resolving to an object representing permission settings (NotificationPermissionsStatus
).
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,
},
});
}
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
.
It returns a Promise
resolving to a number representing 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 to 0
clears the badge.
Note: Not all Android launchers support application badges. If the launcher does not support icon badges, the method will resolve to
false
.
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 format:
{
web?: badgin.Options
}
where the type badgin.Options
is an object described in the badgin
's documentation.
It returns a Promise
resolving to a boolean representing whether setting of the badge succeeded.
getAllScheduledNotificationsAsync(): Promise<Notification[]>
Fetches information about all scheduled notifications.
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 thescheduleNotificationAsync
method. More info may be found at https://expo.fyi/presenting-notifications-deprecated.
The only argument to this function is a NotificationContentInput
.
It returns a Promise
resolving with the notification's identifier once the notification is successfully scheduled for immediate display.
import * as Notifications from 'expo-notifications';
Notifications.presentNotificationAsync({
title: 'Look at that notification',
body: "I'm so proud of myself!",
});
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 triggereed. 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.
The one and only argument to this method is a NotificationRequestInput
describing the notification to be triggered.
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.
import * as Notifications from 'expo-notifications';
Notifications.scheduleNotificationAsync({
content: {
title: "Time's up!",
body: 'Change sides!',
},
trigger: {
seconds: 60,
},
});
import * as Notifications from 'expo-notifications';
Notifications.scheduleNotificationAsync({
content: {
title: 'Remember to drink water!,
},
trigger: {
seconds: 60 * 20,
repeats: true
},
});
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.
The notification identifier with which scheduleNotificationAsync
resolved when the notification has been scheduled.
A Promise
resolving once the scheduled notification is successfully cancelled or if there is no scheduled notification for given identifier.
import * as Notifications from 'expo-notifications';
async function scheduleAndCancel() {
const identifier = await Notifications.scheduleNotificationAsync({
content: {
title: 'Hey!',
},
trigger: { seconds: 5, repeats: true },
});
await Notifications.cancelScheduledNotificationAsync(identifier);
}
cancelAllScheduledNotificationsAsync(): Promise<void>
Cancels all scheduled notifications.
A Promise
resolving once all the scheduled notifications are successfully cancelled or if there are no scheduled notifications.
getPresentedNotificationsAsync(): Promise<Notification[]>
Fetches information about all notifications present in the notification tray (Notification Center).
Note: This method is not supported on Android below 6.0 (API level 23) – on these devices it will resolve to an empty array.
A Promise
resolving 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).
The first and only argument to the function is the notification identifier, obtained either in setNotificationHandler
or in the listener added with addNotificationReceivedListener
.
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).
Resolves once the request to dismiss the notifications is successfully dispatched to the notifications manager.
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.
A Promise
resolving 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.
The only argument to this method is the channel's identifier.
A Promise
resolving 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.
First argument to the method is the channel identifier.
Second argument is the channel's configuration of type NotificationChannelInput
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.
First and only argument to the method is the channel identifier.
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.
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.
The only argument to this method is the channel group's identifier.
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).
First argument to the method is the channel group identifier.
Second argument is the channel group's configuration of type NotificationChannelGroupInput
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.
First and only argument to the method is the channel group identifier.
A Promise
resolving once the channel group is removed (or if there was no channel group for given identifier).
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.
Calling one of the following methods is a no-op on Web.
setNotificationCategoryAsync(identifier: string, actions: NotificationAction[], options: CategoryOptions): Promise<NotificationCategory | null>
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.actions
: An array of NotificationAction
s, 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 (i.e. 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
: 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.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
.allowAnnouncment
: A boolean indicating whether to allow notifications to be automatically read by Siri when the user is using AirPods. Defaults to false
.A Promise
resolving to the category you just created.
getNotificationCategoriesAsync(): Promise<NotificationCategory[]>
Fetches information about all known notification categories.
A Promise
resolving to an array of NotificationCategory
s. 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.
Identifier initially provided to setNotificationCategoryAsync
when creating the category.
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.
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 representing 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 representing 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 representing 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;
} & (
| {
// 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;
categoryIdentifier: string | null;
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 representing 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;
// 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 representing 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 representing a notification delivered by a push notification system.
On Android under remoteMessage
field a JS version of the Firebase RemoteMessage
may be accessed.
export interface PushNotificationTrigger {
type: 'push';
remoteMessage?: FirebaseRemoteMessage;
}
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;
}
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 representing 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
| DateTriggerInput
| TimeIntervalTriggerInput
| DailyTriggerInput
| 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.
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;
}
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 representing user's interaction with the notification.
Note: If the user taps on a notification
actionIdentifier
will be equal toNotifications.DEFAULT_ACTION_IDENTIFIER
.
export interface NotificationResponse {
notification: Notification;
actionIdentifier: string;
userText?: string;
}
NotificationBehavior
An object representing behavior that should be applied to the incoming notification.
export interface NotificationBehavior {
shouldShowAlert: boolean;
shouldPlaySound: boolean;
shouldSetBadge: boolean;
priority?: AndroidNotificationPriority;
}
NotificationChannel
An object representing 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 representing 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 representing 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 representing 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;
};
}
FAQs
Provides an API to fetch push notification tokens and to present, schedule, receive, and respond to notifications.
The npm package expo-notifications receives a total of 123,765 weekly downloads. As such, expo-notifications popularity was classified as popular.
We found that expo-notifications demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 29 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Product
Socket now supports uv.lock files to ensure consistent, secure dependency resolution for Python projects and enhance supply chain security.
Research
Security News
Socket researchers have discovered multiple malicious npm packages targeting Solana private keys, abusing Gmail to exfiltrate the data and drain Solana wallets.
Security News
PEP 770 proposes adding SBOM support to Python packages to improve transparency and catch hidden non-Python dependencies that security tools often miss.