Strapi for Push Notification?

Hello Community,

I am working at a fairly large company. We are in the process of launching our first mobile app. We will have hundreds of thousands of daily users.

My company is already using Strapi (Web). I was wondering if Strapi could be a solution for my mobile app notification project.

Thank you
Eric

We integrated Firebase cloud messaging for push notifications and it is awesome.

1 Like

Hi,
Can you give me a short guide on how did you achieve it?
code snippet would be helpful.
Do I need to register user to firebase as well ?

Greetings @m90khan. Here is a brief starter for using Firebase Cloud messaging with Strapi.

  1. Install the firebase-admin server into your nodejs project. See here
  2. Yes, you will need to have a Firebase Cloud messaging account to set up a Cloud Messaging project. See here
  3. I created a new Strapi service called notifications. with code like this:
'use strict';

const admin = require('firebase-admin');
const serviceAccount = require("./push-your-project-info.json");

/**
 * `notifications` service.
 * Currently we are using the Google Fiebase Cloud Messaging service
 * to broadcast push notifications to iOS and Android clients`
 */

module.exports = {
	  
  initNotifications() {
  	admin.initializeApp({
  		credential: admin.credential.cert(serviceAccount)
  	});
  	strapi.log.info('Notifications initialized...');
  },
   
  // a topic is automatically created when there is at least 1 subscriber(token) assigned to it
  // a topic is automatically deleted when there are no more subscribers assigned to it
  // so to delete a topic, just remove all of the subscribers for the topic  
  async subscribeToTopic(topic, tokens) {
  	try {
  		let response = await admin.messaging().subscribeToTopic(tokens, topic);
  		return prepareTopicResponse(response, tokens, 'subscribeToTopic', topic);
  	} catch(err) {
  		strapi.log.error('Notifications/subscribeToTopic', err.errorInfo);
			//throw new Error(err);
		}
  },
   
  async unsubscribeFromTopic(topic, tokens) {
  	try {
  		let response = await admin.messaging().unsubscribeFromTopic(tokens, topic);
  		return prepareTopicResponse(response, tokens, 'unsubscribeFromTopic', topic);
  	} catch(err) {
  		strapi.log.error('Notifications/unsubscribeFromTopic', err.errorInfo);
			//throw new Error(err);
		}	
  },
  
  async sendMessageToTopic(topic, title, description, data) {
		const message = {
		  notification: {
		    title: title,
		    body: description
		  },			
		  data: data,
		  topic: topic
		};
		
		let respObj = {
			method: 'sendMessageToTopic',
			topic: topic,
			message: message,
			response: ''
		};
  	
  	try {
  		respObj.response = await admin.messaging().send(message);
  		return respObj;
  	} catch(err)  {
  		strapi.log.error('Notifications/sendMessageToTopic', err.errorInfo);
			// throw new Error(err);
		}
  },
  
	async sendMessageToDevices(tokens, title, description, data) {
		const message = {
		  notification: {
		    title: title,
		    body: description
		  },			
		  data: data,
		  tokens: tokens
		};
		
		try {
			const response = await admin.messaging().sendMulticast(message);
			console.log(prepareTopicResponse(response, tokens, 'sendMessageToDevices', ''));
			return prepareTopicResponse(response, tokens, 'sendMessageToDevices', '');
		} catch(err) {
			strapi.log.error('Notifications/sendMessageToDevices', err.errorInfo);
			//throw new Error(err);
		}
	},   
  1. Call init on the service from your Strapi bootstrap function
module.exports = () => {
	// Initialize the Firebase Cloud Messaging Service
	strapi.services.notifications.initNotifications();
}
  1. Call the notifications methods where needed
  	try {
  		let resp1 = await strapi.services.notifications.subscribeToTopic(topic, tokens);
  		let resp2 = await strapi.services.notifications.sendMessageToDevices(tokens, title, description, data);
  	} catch(err) {
  		strapi.log.error('Notifications/subscribeToTopicAndSendMessageToDevices', err);
  	}
2 Likes

Yeah, I did this and it is working, not like a native, just, for now, it is ok.

Hey !

I tried this code, but, I don’t have any sign that it worked, no log in the terminal, nothing.

And I don’t know why…

I checked the code from this post, and the one from the Strapi website, and modified it for my project : Learn How to Integrate Push Notifications Into Your Applications Using Strapi v4 and Firebase Cloud Messaging [CTRL-F /src/api/like/controllers/like.js]

My code look like this :

// src/api/news/controllers/news.js
'use strict';
/**
 *  news controller
 */
const { createCoreController } = require('@strapi/strapi').factories;
module.exports = createCoreController('api::news.news', ({ strapi }) => ({
    async create() {
        try {
            await strapi.services.notifications.sendMessageToDevices(tokens, title, description, data);
        } catch(err) {
            strapi.log.error('Notifications/sendMessageToDevices', err);
        }
    }
}));

I would like to recieve notifications, if any “News” is created.

If anyone have a solution, it would be great, thanks !

EDIT : New code

'use strict';
/**
 *  news controller
 */
const { createCoreController } = require('@strapi/strapi').factories;
module.exports = createCoreController('api::news.news', ({ strapi }) => ({
    async create() {
        await strapi.service('api::news.news').createNew({
            ...ctx.request.body.data,
        });
        strapi.log.debug('A new News was added');
        try {
            await strapi.services.notifications.sendMessageToDevices(tokens, title, description, data);
        } catch(err) {
            strapi.log.error('Notifications/sendMessageToDevices', err);
        }
    }
}));

Did it work for you?