Skip to content

Commit

Permalink
added server side messaging functionality, still need to clean up code.
Browse files Browse the repository at this point in the history
  • Loading branch information
jesslane94 committed Oct 2, 2024
1 parent 8cf6158 commit a8fab72
Show file tree
Hide file tree
Showing 10 changed files with 2,249 additions and 35 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -36,4 +36,5 @@ yarn-error.log*
next-env.d.ts

#keys
config.js
config.mjs
service_key.json
13 changes: 7 additions & 6 deletions app/firebaseConfig.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
import { isSupported, getMessaging } from "firebase/messaging";
import { getFirestore } from "firebase/firestore";
// import { getAnalytics } from "firebase/analytics";
import { getMessaging } from "firebase/messaging";
// https://firebase.google.com/docs/web/setup#available-libraries
import { firebaseConfig, vapidKey } from '../my-app/config';
import { firebaseConfig } from '../config.mjs';

// Initialize Firebase
const app = initializeApp(firebaseConfig);
const messaging = getMessaging(app);
// const analytics = getAnalytics(app);
export const app = initializeApp(firebaseConfig);
export const messaging = async () => await isSupported() && getMessaging(app);
export const db = getFirestore(app);
// const analytics = getAnalytics(app);
17 changes: 17 additions & 0 deletions app/sendNotification/page.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
'use client';
import { saveMessagingDeviceToken } from "@/firebase/messaging";
import { FCM_PUSH } from "./sendMessage"

export default function sendNotification() {
const handleSubmit = async () => {
saveMessagingDeviceToken();
FCM_PUSH();
};

return (
<div>
<button onClick={handleSubmit} className="bg-red-500 text-white py-2 px-4 rounded">Send Notification</button>
</div>
)
}

34 changes: 34 additions & 0 deletions app/sendNotification/sendMessage.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
'use server';
import admin from "firebase-admin";
import { collection, query, where, getDocs } from "firebase/firestore";
import { db } from "../firebaseConfig";

var registrationToken = ""
const q = query(collection(db, "tokens"), where("entry_id", "==", "1"));

const querySnapshot = await getDocs(q);
var doc = (querySnapshot.docs[0].data()['token'])
registrationToken = doc
console.log(querySnapshot.empty)

const message = {
token: registrationToken,
"notification": {
"title": "Here is a Notification!",
"body" : "my message is here."
},
data: {
title: "Here is a notification!",
body: "my message is here.",
link_url: "http://localhost:3000" // When a user clicks on the notification, go here
}
};

export async function FCM_PUSH () {
admin.messaging().send(message).then((response) => {
// Response is a message ID string.
console.log('Successfully sent message:', response);
}).catch((error) => {
console.log('Error sending message:', error);
})
};
4 changes: 0 additions & 4 deletions components/sendNotification.js

This file was deleted.

52 changes: 52 additions & 0 deletions firebase/messaging.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import { collection, addDoc } from 'firebase/firestore';
import { messaging, db } from "../app/firebaseConfig";
import { getToken, onMessage } from 'firebase/messaging';

// export const FCM_TOKEN_KEY = "fcmToken"; // key for storing FCM token in Firestore
const VAPID_KEY = "BDThvrnIE7bAPzbY3cekxtDcKIpLRy2rrOV29YkbtQiEo99QgMQ4m7MoeGMR_YI6bt54tCZDPBoDZiBaRhELTes";

// Requests permissions to show notifications.
async function requestNotificationsPermissions() {
console.log('Requesting notifications permission...');
const permission = await Notification.requestPermission();

if (permission === 'granted') {
console.log('Notification permission granted.');
// Notification permission granted.
await saveMessagingDeviceToken();
} else {
console.log('Unable to get permission to notify.');
}
}

// Saves the messaging device token to Cloud Firestore.
export async function saveMessagingDeviceToken() {
console.log('save msg device token');
try {
const msg = await messaging();
const fcmToken = await getToken(msg, { vapidKey: VAPID_KEY });
if (fcmToken) {
console.log('Got FCM device token:', fcmToken);
// Save device token to
// for now, hardcoded. can use a userID or something else you can query
await addDoc(collection(db, "tokens"),{
entry_id: "1",
token: fcmToken
})
// This will fire when a message is received while the app is in the foreground.
// When the app is in the background, firebase-messaging-sw.js will receive the message instead.
onMessage(msg, (message) => {
console.log(
'New foreground notification from Firebase Messaging!',
message.notification
);
new Notification(message.notification.title, { body: message.notification.body });
});
} else {
// Need to request permissions to show notifications.
requestNotificationsPermissions();
}
} catch (error) {
console.error('Unable to get messaging token.', error);
};
}
11 changes: 10 additions & 1 deletion next.config.mjs
Original file line number Diff line number Diff line change
@@ -1,4 +1,13 @@
/** @type {import('next').NextConfig} */
const nextConfig = {};
const nextConfig = {
webpack: (config, context) => {
// console.log(config)
config.experiments = {
...config.experiments,
asyncWebAssembly: true,
};
return config;
},
};

export default nextConfig;
Loading

0 comments on commit a8fab72

Please sign in to comment.