Remote notifications
- React Native course
- Advanced
- Lesson 4/83
- 5 min
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.
Practice 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.
Starter code
export async function sendPush(token) {
// send a notification to the Expo push service
}Sample 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;Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 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 Correct answer
Explanation: The Expo push service is called with an HTTP POST.
2 Match each part to its role
| Term | Meaning |
|---|---|
to |
Push token |
title |
Notification title |
body |
Notification text |
Content-Type |
Body format |
3 Write the header value
headers: { 'Content-Type': '____' },
headers: { 'Content-Type': 'application/json' },
Explanation: The body is sent as an object; Content-Type must be application/json.