react-native-firebase:用户登出时如何删除设备令牌?
Hey there! I’ve dealt with this exact scenario before, so let me break down the steps you need to take to properly cut off notifications once a user logs out.
Key Actions to Take
The missing piece here is leveraging the deleteToken() method from @react-native-firebase/messaging—but you also need to handle server-side cleanup to fully stop notifications from being sent.
Step 1: Revoke the local FCM token
React Native Firebase’s Messaging module has a built-indeleteToken()function that invalidates the device’s current FCM token. Call this as part of your logout flow to ensure the device won’t receive new notifications tied to this token.Step 2: Clean up token records on your backend
Even if you delete the token locally, your server might still have it stored and linked to the user. You must call an API endpoint to remove that token from your database—otherwise, your backend could still attempt to send notifications to the invalid token (though the device won’t receive them, cleanup is still good practice).Step 3: Re-register the token on future logins
When the user logs back in, remember to fetch a new token withmessaging().getToken()and send it to your server to re-associate it with their account.
Example Logout Function Implementation
Here’s how you can integrate this into your app’s logout logic:
import messaging from '@react-native-firebase/messaging'; import { clearAuthStorage, navigation } from '../your-app-helpers'; // Adjust imports to match your app const handleLogout = async () => { try { // Delete the device's FCM token await messaging().deleteToken(); console.log('FCM token revoked successfully'); // Call your backend to remove the token from the user's record const currentUserId = getCurrentUserId(); // Replace with your method to get the user ID await fetch('/api/users/logout/cleanup', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${getAuthToken()}`, // Include auth if required }, body: JSON.stringify({ userId: currentUserId }), }); // Complete standard logout tasks clearAuthStorage(); navigation.reset({ index: 0, routes: [{ name: 'Login' }] }); } catch (error) { console.error('Error during logout:', error); // Optional: Show an error message to the user } };
Additional Tips
- If you need to target a specific Firebase sender ID, pass it to
deleteToken()like this:await messaging().deleteToken('YOUR_SENDER_ID');—the default (no parameter) works for most cases. - Double-check that your backend is set up to accept the cleanup request and remove the token associated with the user. This prevents unnecessary notification attempts to invalid tokens.
内容的提问来源于stack exchange,提问作者Edoardo Foco

