Notifications

SveltePak includes support for sending notifications.

Server Side

To get started you just need to call the sendNotification function from the notifications package.

import { sendNotification } from "$modules/notifications";

await sendNotification(userId, {
  title: "Hello",
  body: "Hello world",
  icon: "πŸ‘‹",
  link: "https://sveltepak.com"
});

This can be used in any tRPC or API endpoint.

Ideally you want to use this inside a tRPC method and use the context to get the user id. This way you can send notifications to the user that is currently logged in.

Of course, you can also use this in a tRPC method to send notifications to other users.

import { t } from "$trpc/t";
import { sendNotification } from "$modules/notifications";
import { exampleSchema } from "./schema";

export const example = t.router({
  completion: t.procedure.input(exampleSchema).query(async ({ input, ctx }) => {
    await sendNotification(ctx.user.id, {
      title: "Hello",
      body: "Hello world",
      icon: "πŸ‘‹",
      link: "https://sveltepak.com"
    });
    return input;
  })
});

Client Side

While you can’t send notifications from the client, you can use a Store to manage the notifications.

Basic example includes the ability to read and mark as read notifications.

import { notifications, unread, count, markAsRead } from "$stores/notifications";

// Read all notifications
const allNotifications = $notifications;

// Read all unread notifications
const unreadNotifications = $unread;

// Read the count of unread notifications
const unreadNotificationsCount = $count;

// Mark a notification as read
markAsRead("notification-id");