Supabase边缘函数通过Firebase推送通知遇TypeError求助
问题排查与解决方案
错误原因
这个TypeError: Right-hand side of 'instanceof' is not an object错误,源于Firebase Admin SDK依赖的jsonwebtoken库在Deno环境(Supabase边缘函数基于Deno)中缺少适配,导致内部类型检查逻辑失效。
修复步骤
导入适配Deno的Firebase Admin包
修改Firebase Admin的导入链接,添加?target=deno参数,让esm.sh提供针对Deno环境编译的版本:import { initializeApp, cert } from "https://esm.sh/firebase-admin@11.11.0?target=deno" import { getMessaging } from "https://esm.sh/firebase-admin@11.11.0/messaging?target=deno"确保私钥格式合法
从Firebase下载的服务账号私钥包含换行符,直接写入代码时需保证格式正确,推荐用模板字符串保留换行:privateKey: `-----BEGIN PRIVATE KEY----- your-private-key-full-content-here -----END PRIVATE KEY-----`,等待异步操作完成
原代码中sendToDevice是异步操作,但函数直接返回Response,会导致推送逻辑可能未执行完毕就终止。需用await等待异步操作完成:
修改后的完整代码
import { serve } from "https://deno.land/std@0.168.0/http/server.ts" import { initializeApp, cert } from "https://esm.sh/firebase-admin@11.11.0?target=deno" import { getMessaging } from "https://esm.sh/firebase-admin@11.11.0/messaging?target=deno" const serviceAccount = cert({ projectId: "your-project-id", privateKey: `-----BEGIN PRIVATE KEY----- your-private-key-content -----END PRIVATE KEY-----`, clientEmail: "your-service-account-email", }) const app = initializeApp({ credential: serviceAccount }); const TEST_FCM_TOKEN = "your-test-fcm-token" export interface momentNotification { data: { title: string, message: string, } } serve(async (req) => { const { name } = await req.json() const data = { message: `Hello ${name}!`, } const defaultMessaging = getMessaging(app); try { const response = await defaultMessaging.sendToDevice(TEST_FCM_TOKEN, { notification: { title: 'title', body: 'description' }, }) console.log("Successfully sent message:", response); } catch (error) { console.log("Error sending message:", error); } return new Response( JSON.stringify(data), { headers: { "Content-Type": "application/json" } }, ) })
验证方式
重新执行npx supabase functions serve启动本地服务,调用函数后查看日志,确认推送通知是否正常发送。
内容的提问来源于stack exchange,提问作者Adam O'Neill
相关产品推荐
相关产品推荐

