Send Notification with the Notification Module
In this guide, you'll learn about the different ways to send notifications using the Notification Module.
Using the Create Method#
In your resource, such as a subscriber, resolve the Notification Module's main service and use its create method:
import { INotificationModuleService } from "@medusajs/framework/types"
export default async function productCreateHandler({
event: { data },
container,
}: SubscriberArgs<{ id: string }>) {
const notificationModuleService: INotificationModuleService =
container.resolve(Modules.NOTIFICATION)
await notificationModuleService.createNotifications({
to: "user@gmail.com",
channel: "email",
template: "product-created",
data,
})
}
export const config: SubscriberConfig = {
event: "product.created",
}
The create method accepts an object or an array of objects having the following properties:
Loading...
For a full list of properties accepted, refer to this guide.
Using the sendNotificationsStep#
If you want to send a notification as part of a workflow, You can use the sendNotificationsStep in your workflow.
For example:
import {
createWorkflow,
transform,
} from "@medusajs/framework/workflows-sdk"
import {
sendNotificationsStep,
useQueryGraphStep,
} from "@medusajs/medusa/core-flows"
type WorkflowInput = {
id: string
}
export const sendEmailWorkflow = createWorkflow(
"send-email-workflow",
({ id }: WorkflowInput) => {
const { data: products } = useQueryGraphStep({
entity: "product",
fields: [
"*",
"variants.*",
],
filters: {
id,
},
})
const notificationData = transform(
{ products },
({ products }) => ({
product_title: products[0].title,
product_image: products[0].images[0]?.url,
})
)
sendNotificationsStep({
to: "user@gmail.com",
channel: "email",
template: "product-created",
data: notificationData,
})
}
)
For a full list of input properties accepted, refer to the sendNotificationsStep reference.
You can then execute this workflow in a subscriber, API route, or scheduled job.
For example, you can execute it when a product is created:
import type {
SubscriberArgs,
SubscriberConfig,
} from "@medusajs/framework"
import { sendEmailWorkflow } from "../workflows/send-email"
export default async function productCreateHandler({
event: { data },
container,
}: SubscriberArgs<{ id: string }>) {
await sendEmailWorkflow(container).run({
input: {
id: data.id,
},
})
}
export const config: SubscriberConfig = {
event: "product.created",
}
Was this page helpful?