SendGrid Notification Module Provider
The SendGrid Notification Module Provider integrates SendGrid to send emails to users and customers.
Register the SendGrid Notification Module#
Add the module into the providers
array of the Notification Module:
1import { Modules } from "@medusajs/framework/utils"2 3// ...4 5module.exports = defineConfig({6 // ...7 modules: [8 {9 resolve: "@medusajs/medusa/notification",10 options: {11 providers: [12 // ...13 {14 resolve: "@medusajs/medusa/notification-sendgrid",15 id: "sendgrid",16 options: {17 channels: ["email"],18 api_key: process.env.SENDGRID_API_KEY,19 from: process.env.SENDGRID_FROM,20 },21 },22 ],23 },24 },25 ],26})
Environment Variables#
Make sure to add the following environment variables:
SendGrid Notification Module Options#
Option | Description |
---|---|
channels | The channels this notification module is used to send notifications for. Only one provider can be defined for a channel. |
api_key | The SendGrid API key. |
from | The SendGrid from email. |
SendGrid Templates#
When you send a notification, you must specify the ID of the template to use in SendGrid.
Refer to this SendGrid documentation guide on how to create templates for your different email types.
Test out the Module#
To test the module out, create a simple subscriber at src/subscribers/product-created.ts
with the following content:
6 7export default async function productCreateHandler({8 event: { data },9 container,10}: SubscriberArgs<{ id: string }>) {11 const notificationModuleService = container.resolve(Modules.NOTIFICATION)12 const productModuleService = container.resolve(Modules.PRODUCT)13 14 const product = await productModuleService.retrieveProduct(data.id)15 16 await notificationModuleService.createNotifications({17 to: "test@gmail.com",18 channel: "email",19 template: "product-created",20 data: {21 product_title: product.title,22 product_image: product.images[0]?.url,23 },24 })25}26 27export const config: SubscriberConfig = {28 event: "product.created",29}
In this subscriber, you:
- Resolve the Notification and Product Modules' main services from the Medusa container.
- Retrieve the product's details to pass them to the template in SendGrid.
- Use the
createNotifications
method of the Notification Module's main service to create a notification to be sent to the specified email. By specifying theemail
channel, the SendGrid Notification Module Provider is used to send the notification. - The
template
property of thecreateNotifications
method's parameter specifies the ID of the template defined in SendGrid. - The
data
property allows you to pass data to the template in SendGrid. For example, the product's title and image.
Then, start the Medusa application:
And create a product either using the API route or the Medusa Admin. This runs the subscriber and sends an email using SendGrid.