Having trouble sending an image through a cloud-message Firebase notification

I have successfully incorporated notifications into my app, but I am facing an issue when trying to include an image in the notification.

Below is my code implementation:

notification(user.fcmToken, {
    notification: {
      title: title,
      body: message,
      imageURL: "https://.../avatar/avatar1.png",
    },
  });

Here is the notification function:

exports.notification = async (registrationToken, message = message_notification, notify_options = options ) => {
   try {
        const response = await admin.messaging().sendToDevice(registrationToken, message, notify_options);
        console.log('Notification response:', JSON.stringify(response));
        if(response.successCount > 0) {
            return {
                statusMessage: 'SUCCESS',
                message: 'Sent Successfully',
                statusCode: 200,
            }
        }
        if(response.failureCount > 0) {
            return {
                statusMessage: 'ERROR',
                message: 'Failure',
                statusCode: 400,
            }
        }
    } catch (error) {
        console.log("Error", error)
       return {
        statusMessage: 'ERROR',
        message: 'SERVER ERROR',
        statusCode: 400,
      }
    }
};

Answer №1

It is important to use the send method or sendAll method instead of sendToDevice. send and sendAll methods only accept one token string per request

     const notificationTokens = ["token1","token2"]
     const params = notificationTokens.map(token => ({
          token: token,
          notification: {
            body: "My TestBody",
            title: "My Title",
            imageUrl: 'http:imageurl.jpg'
          },
          data: {} //optional
        }))
         const response = await admin
        .messaging()
        .sendAll(registrationToken, message, notify_options);

If you only have a single token as a string, you can use send instead of sendAll.

For more information, refer to the documentation: https://firebase.google.com/docs/cloud-messaging/send-message#example-notification-message-image

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What strategy does Node recommend for organizing code into multiple files?

In the midst of my current project, which involves NodeJS and Typescript, I am developing an HTML5 client that communicates with a NodeJS server via web-sockets. With a background in C#, I prefer to organize my code into separate files for different functi ...

I encountered an issue with my promise where the data was undefined, causing me to have trouble properly setting the error. Could this be

Recently, I encountered an issue while trying to sign up my users using a simple form. An error popped up indicating that the data (promise argument) is undefined: Unhandled Runtime Error TypeError: Cannot read property 'message' of undefined (a ...

Problem encountered while performing npm installation on Ubuntu due to ENOENT error with lstat

I've been working on a project that handles blog posts and recently deployed it on a cloud platform without any issues. However, I decided to clean up my node_modules folder by deleting it and reinstalling using npm install. After doing so, I encount ...

Capturing Traffic Prior to CNAME Forwarding

Recently, I encountered a specific scenario that has left me puzzled: When a user connects to the domain: test.com I am interested in redirecting this domain to another site such as google.com To achieve this, I have set up a CNAME record pointing to go ...

How can I incorporate Bootstrap/Semantic UI into an Express project without relying on external CDNs

After downloading the minified version of Bootstrap and placing it in the root directory of my project, I added the following code to a HTML file located in /views/: <link rel="stylesheet" href="/bootstrap.min.css"> Despite this, the page remained ...

Generating a JSON file using JavaScript amidst the presence of unconventional characters in JSON keys

In my Node Red Function Node, I'm currently facing a challenge of generating a JSON file from JavaScript code. The specific format I need for the JSON file is as follows: [ { "H-Nr.":"1", "Pos.-Nr.":"1" }, { "H-Nr.":"1", ...

Can Restify Node return an integer value?

https://i.stack.imgur.com/72ltz.png I recently encountered an issue while trying to validate my URL with Facebook for my bot. It appears to be related to a data type problem since I seem to be sending a string instead of an integer. Below is a snippet of ...

Redis data retrieval is successful on the second attempt

I am utilizing a Redis database along with express routing to create an API. My stack includes node.js and ioredis as well. The process involves connecting to Redis, fetching keys related to a specific date, and then retrieving the data associated with th ...

Automating the execution of `npm run dev` for a React Vite application running within a Docker environment

I currently have a setup where I am running a Vite React app with a Flask API inside Docker using WSL 2 and docker-compose. However, I find myself manually executing certain commands in order to access my React app in the browser: docker exec -it vite_dock ...

Unable to locate a resolution for the error message "Warning: Task "uglify" not found"

Below is the content of my Gruntfile.js: module.exports = function(grunt) { require('load-grunt-tasks')(grunt); grunt.initConfig({ uglify: { start: { files: { 'js/script.min.js': ['js/script.js&a ...

Is there a way to modify the route or file name of the index.html file in a React project?

Every time I use npm build to create a React app (using the typical react-scripts/create-creact-app, etc.), the entry file always ends up in build/index.html. I attempted to move the src folder into a subfolder, but unfortunately, index.js must remain in ...

Removing information from a MongoDB database with the help of AngularJS and Node.js

Having trouble deleting data in MongoDB using AngularJS and Node.js, as I keep encountering the error "Cannot DELETE /api/manage-product" in the console. .html file <tbody> <tr ng-repeat="product in vm.result"> ...

How are objects typically created in Node.js applications?

These code snippets are from Node.js tests, and I am curious about why one method of instantiating an object is favored over another? // 1 var events = require('events'); var emitter = new events.EventEmitter(); emitter.on('test', doSo ...

MongooseError: The query `doctors.find()` exceeded the 10-second timeout for buffering

click here for image encountered this issue in my MERN project. The code seems to work intermittently, with this error popping up at times. I've tried several solutions without success. The MongoDB database connection is fine, although it does take so ...

The error message states: "TypeError: a.map is not a function"

I recently deployed my React JS app on Heroku and encountered some issues with the routing. While everything worked smoothly on my local host, I faced errors after fixing the routing problem that I couldn't resolve. Despite extensive research, I haven ...

Encountered error code 3228369023 while trying to establish a connection to a SQL Server database using Node.js with MSSQL

Currently in the process of setting up an API for a SQL Server Express database, my plan is to utilize mssql in Node.js with express to handle requests and communicate with the database. Despite trying several methods to establish a connection between my n ...

A guide on incorporating user information into http-proxy-middleware

I am currently trying to figure out how to include user data, or any data, in my requests to one of my services. However, despite the code I have written below, the data is not being added to the proxyRequest when it is sent to my service. Can anyone exp ...

The error message received when attempting to install Copay using npm is: unable to execute in working directory %s %s (working directory

While attempting to install copay bitcopay, I ran into an error when executing sudo npm install. $ sudo npm install Password: npm WARN lifecycle <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1e7d716e7f675e2c3029302e">[emai ...

Avoid the issue of having duplicate user ids by implementing a locked thread feature within Next.js

My database setup involves using MongoDB to store user data, with the user id incrementing each time a new user registers (e.g. 1, 2, 3, 4, etc). To generate the user id, I have the following code snippet. The collection where user data is stored is named ...

The node-libxml-xsd library encounters an error stating "file not recognized: File format not recognized" while attempting a node-gyp rebuild, potentially causing issues with the xmljs.node file

Encountering an issue when attempting to create a Docker container for a Meteor app, node-gyp rebuild encounters failure while compiling node-libxml-xsd. The error reads: <command-line>:0:0: note: this is the location of the previous definition SO ...