使用Firebase Functions调用FCM发送消息时遇Requested entity was not found错误
Hey there, let's tackle this FCM error you're seeing with admin.messaging().send()—it's a common issue, and we can sort it out quickly!
First, let's clarify what this error means: "Requested entity was not found" almost always points to an invalid or expired FCM registration token. FCM can't find the target device associated with that token, so the send request fails. Here's how to fix it and prevent it from happening again:
1. Clean Up Invalid Tokens Immediately
When you catch this error, the token is no longer valid—you need to remove it from your database right away to avoid wasting future API calls. Here's how to handle it in your function:
try { await admin.messaging().send(messagePayload); } catch (error) { // Check for the specific token-not-registered error if (error.code === 'messaging/registration-token-not-registered') { // Replace this with your actual database logic to delete the token await yourFirestoreCollection.doc(invalidTokenId).delete(); console.log(`Removed invalid token: ${invalidTokenId}`); } else { // Handle other FCM errors here console.error('FCM send error:', error); } }
Tokens become invalid for a few common reasons:
- The user uninstalled your app
- The app's data was cleared on the device
- The device was factory reset
- The token expired (FCM tokens can rotate over time)
2. Validate Tokens Proactively (Optional)
If you want to catch invalid tokens before sending messages, you can use admin.messaging().validateToken() to check individual tokens. Just note that this API has usage limits, so don't overuse it—reserve it for batch checks when you suspect a batch of tokens might be stale:
const validationResult = await admin.messaging().validateToken(suspectToken); if (!validationResult.valid) { // Delete the invalid token from your database }
3. Update Your Firebase Admin SDK
Outdated SDK versions can sometimes cause compatibility issues with FCM's backend. Let's make sure you're running the latest stable version:
npm install firebase-admin@latest --save
Firebase does roll out updates to FCM regularly, but this error isn't usually caused by a platform-wide change—it's almost always token-related. That said, updating the SDK ensures you're using the latest token-handling logic and bug fixes.
4. Double-Check Client-Side Token Logic
Make sure your mobile app is correctly managing FCM tokens:
- When the app is first installed, it should fetch a token and send it to your backend immediately.
- Use the token refresh callback (like
onTokenRefresh()on Android ordidReceiveRegistrationTokenon iOS) to send updated tokens to your backend whenever FCM issues a new one. - Avoid hardcoding tokens or storing them in places that don't sync with your backend properly.
5. Verify Message Payload Format
While less likely, a malformed message payload could cause unexpected errors. Double-check that your message object has the correct token field (no typos), and that the payload adheres to FCM's requirements for Android/iOS (e.g., correct notification vs. data payload structure).
内容的提问来源于stack exchange,提问作者enfix

