Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

128
Vistas
Firebase Cloud Messaging Web - onMessage not firing

I am trying to integrate FCM into my Next.js app. I have a hook to handle the messaging, but it isn't receiving my test messages. The code produces no errors either client side or server side, and logging shows that the onMessage callback is set, but after calling the API to send a test message, the client does not execute the callback.

_app.tsx

export default function MyApp({ Component, pageProps }: AppProps) {
    initializeFirebase();
    useMessaging();

    return <Component {...pageProps} />;
}

hooks.ts

export function useMessaging() {
    const [user] = useAuthState(getAuth());
    const [token, setToken] = useState<string | null>(null);

    useEffect(() => {
        // VAPID_KEY is imported from another file
        getToken(getMessaging(), { vapidKey: VAPID_KEY })
            .then((token) => {
                setToken(token);
                onMessage(getMessaging(), (message) => {
                    // For testing, log that the message was received
                    console.log({ message });
                });
            })
    }, []);

    useEffect(() => {
        if (user && token) {
            // For testing, log the token
            console.log({ token });
        }
    }, [user, token]);
}

/api/test.ts

export default async function handler(
    req: NextApiRequest,
    res: NextApiResponse
) {
    const serviceAccount = JSON.parse(
        decodeURI((process.env as MoodGraphEnv).FIREBASE_SERVICE_ACCOUNT)
    ) as ServiceAccount;

    if (getApps().length === 0) {
        initializeApp({
            credential: cert(serviceAccount),
            databaseURL: 'https://my-app-123456-default-rtdb.firebaseio.com',
        });
    }

    const message: Message = {
        notification: {
            title: 'Hello world!',
            body: 'The notification worked!',
        },
        token:
            // During testing I replace this with the token logged to the browser console
            'token_goes_here',
    };

    getMessaging()
        .send(message)
        .then((messagingResponse) => {
            console.log('Successfully sent message:', messagingResponse);
        })
        .catch((error) => {
            console.log('Error sending message:', error);
        });

    res.status(200).json({});
}

I am not sure why the callback is not executed, so any help would be appreciated.

about 4 years ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda