The useNotification() function facilitates real-time notification handling in web applications, similar to a notification centre. It operates within the MagicJS framework, integrating backend and frontend components seamlessly.

Here's an example:


To fetch and interact with the notification:

import { useNotification } from '';

const { notifications, unreadCount, markAsRead } = useNotification();

return (
        <p>{`Notification counter: ${unreadCount}`}</p>
       => (
                    <div key={n._id}>
                        <button onClick={() => markAsRead([n._id])}>
                            Mark as read
        <button onClick={async () => {
            markAsRead( => n._id))
            Mark all as read
  • It renders the notifications and a button to mark all notifications as read.

  • It fetches the unread notification count using the unreadCount variable.

  • For each notification, it renders a <div> with a unique key (n._id), a title (n.payload.title), and a "Mark as read" button if the notification has not been read yet (n.hasRead === false).

  • The "Mark as read" button calls the markAsRead function with the notification's ID when clicked.

  • There's a button labeled "Mark all as read", which marks all notifications as read by calling markAsRead with an array of all notification IDs.

  • Clicking on the 'Create Notification' button invokes the notifyServer and sends a notification.


To send a notification:

import { createBackendFunction, utils, useFunctionContext } from "";

export default createBackendFunction(async function () {
    const ctx = useFunctionContext(this);

    await utils.sendNotification(
            title: 'Test at ' + (new Date()),
            message: 'Hello world'
  • It uses utils.sendNotification function to send a notification.

  • To send the notification to the current user, it accesses ctx.currentUser._id, add multiple recepients separated by a comma.

  • The second argument is an object containing the notification details, including the title and message. The title is dynamic, including the current date/time concatenated with the string 'Test at '. with a static message 'Hello world'.

Click here to refer GitHub.

Last updated