Token retrieval
- React Native course
- Advanced
- Lesson 2/83
- 5 min
Learn to get push tokens.
What is a push token?
A push token is a string that uniquely identifies your device. Your server sends notifications to this string and the Apple or Google service routes it to the real device. Without a token you cannot send remote notifications.
The expo-notifications package returns an Expo token through getExpoPushTokenAsync. The token has the form ExponentPushToken[xxxxxxxxxxxxxxx]. You register the token with your server; when the server wants to send a notification it uses this token.
Android channel
On Android 8 and later, notifications must be tied to a channel. The channel sets the notification's sound, importance and behavior. iOS has no channel concept; so channel settings apply only to Android.
To create a channel you call Notifications.setNotificationChannelAsync. Example: Notifications.setNotificationChannelAsync('default', {{ name: 'Default', importance: Notifications.AndroidImportance.HIGH }}). This call is made once when the app starts; you then give the same channel name to notifications.
Practice Get the token and log it
Complete the registerForPushNotifications function. First get the permission status with Notifications.getPermissionsAsync(); if not granted, call Notifications.requestPermissionsAsync(). Then get the token with const token = await Notifications.getExpoPushTokenAsync({{ projectId: 'abc123' }}) and log it with console.log(token.data).
Starter code
import * as Notifications from 'expo-notifications';
export async function registerForPushNotifications() {
// check permissions, request if needed
// get the token and log it
}Sample solution
async function registerForPushNotifications() {
const current = await Notifications.getPermissionsAsync();
let final = current;
if (!final.granted) {
final = await Notifications.requestPermissionsAsync();
}
if (!final.granted) return null;
const token = await Notifications.getExpoPushTokenAsync({ projectId: 'abc123' });
console.log(token.data);
return token.data;
}Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Write the token function
const token = await Notifications.____({ projectId: 'your-project-id' });
const token = await Notifications.getExpoPushTokenAsync({ projectId: 'your-project-id' });
Explanation: getExpoPushTokenAsync returns an Expo token.
2 What is a push token used for?
- Only to schedule local notifications
- To send a notification from the server to the device Correct answer
- To store the user password
- To change the app icon
Explanation: The server sends a notification to the token; the service routes it to the device.
3 Match each part to its role
| Term | Meaning |
|---|---|
getExpoPushTokenAsync |
Returns Expo token |
getPermissionsAsync |
Gives permission status |
requestPermissionsAsync |
Requests permission |
token.data |
Holds the token string |