React Native
Remote notifications
Learn to receive notifications from a remote server.
Remote notification
A remote notification is sent from your server to the device. The server sends a notification payload to a registered push token; Apple's APNs service or Google's FCM service routes the payload to the device. It is used for news, messages and event notifications.
Expo offers its own notification service: https://exp.host/--/api/v2/push/send. Your server sends an HTTP POST request; the body carries the token, title and message. The Expo service forwards the payload to APNs or FCM. This is the easiest way to send remote notifications without managing your own certificates.
Request body
The body of an Expo push request is an object. The to field carries the push token. title and body are the notification text. data is free data attached to the notification. Your server uses fetch to turn this object into a string and put it in the POST body.
Example body: { to: 'ExponentPushToken[xxx]', title: 'New message', body: 'Hello!' }. The request header must include Content-Type: application/json; this tells the server to read the body as an object. The Expo service returns the response as an object.
Exercise Send a notification from the server
Complete the sendPush function. Call fetch('https://exp.host/--/api/v2/push/send', {{ method: 'POST', headers: {{ 'Content-Type': 'application/json' }}, body: JSON.stringify({ to: token, title: 'New message', body: 'Hello!' }) }}) with await and return the response.
Show example solution
const response = await fetch('https://exp.host/--/api/v2/push/send', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ to: token, title: 'New message', body: 'Hello!' }),
});
return response;
Test yourself
-
How is the Expo push service called?
- Only an iOS API from inside the app
- Only by writing a file
- A GET request from the browser
- An HTTP POST request
Show answer
An HTTP POST request — The Expo push service is called with an HTTP POST.
-
Match each part to its role
- to
- Push token
- title
- Notification title
- body
- Notification text
- Content-Type
- Body format
-
Write the header value
headers: { 'Content-Type': '____' },
Show answer
headers: { 'Content-Type': 'application/json' },
Next lesson: Notification events