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:

Note: Only one provider can be defined for a channel.
medusa-config.ts
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:

Terminal
SENDGRID_API_KEY=<YOUR_SENDGRID_API_KEY>SENDGRID_FROM=<YOUR_SENDGRID_FROM>

SendGrid Notification Module Options#

OptionDescription
channels

The channels this notification module is used to send notifications for. Only one provider can be defined for a channel.

api_keyThe SendGrid API key.
fromThe 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, you'll listen to the product.created event and send an email when a product is created.

Create a subscriber at src/subscribers/product-created.ts with the following content:

src/subscribers/product-created.ts
6
7export default async function productCreateHandler({8  event: { data },9  container,10}: SubscriberArgs<{ id: string }>) {11  const notificationModuleService = container.resolve(Modules.NOTIFICATION)12  const query = container.resolve("query")13
14  const { data: [product] } = await query.graph({15    entity: "product",16    fields: ["*"],17    filters: {18      id: data.id,19    },20  })21
22  await notificationModuleService.createNotifications({23    to: "test@gmail.com",24    channel: "email",25    template: "product-created",26    data: {27      product_title: product.title,28      product_image: product.images[0]?.url,29    },30  })31}32
33export const config: SubscriberConfig = {34  event: "product.created",35}

In this subscriber, you:

  • Resolve the Notification Module's main service and Query from the Medusa container.
  • Retrieve the product's details using Query 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 the email channel, the SendGrid Notification Module Provider is used to send the notification.
  • The template property of the createNotifications 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.

Other Events to Handle#

Medusa emits other events that you can handle to send notifications using the SendGrid Notification Module Provider, such as order.placed when an order is placed.

Refer to the Events Reference for a complete list of events emitted by Medusa.

Sending Emails with SendGrid in Workflows#

You can also send an email using SendGrid in any workflow. This allows you to send emails within your custom flows.

You can use the sendNotifcationStep in your workflow to send an email using SendGrid.

For example:

src/workflows/send-email.ts
1import { createWorkflow } from "@medusajs/framework/workflows-sdk"2import { 3  sendNotificationsStep, 4  useQueryGraphStep,5} from "@medusajs/medusa/core-flows"6
7type WorkflowInput = {8  id: string9}10
11export const sendEmailWorkflow = createWorkflow(12  "send-email-workflow",13  ({ id }: WorkflowInput) => {14    const { data: products } = useQueryGraphStep({15      entity: "product",16      fields: [17        "*",18        "variants.*",19      ],20      filters: {21        id,22      },23    })24
25    sendNotificationsStep({26      to: "test@gmail.com",27      channel: "email",28      template: "product-created",29      data: {30        product_title: product[0].title,31        product_image: product[0].images[0]?.url,32      },33    })34  }35)

This workflow works similarly to the subscriber. It retrieves the product's details using Query and sends an email using SendGrid (by specifying the email channel) to the test@gmail.com email.

You can also execute this workflow in a subscriber. For example, you can execute it when a product is created:

src/subscribers/product-created.ts
1import type {2  SubscriberArgs,3  SubscriberConfig,4} from "@medusajs/framework"5import { Modules } from "@medusajs/framework/utils"6import { sendEmailWorkflow } from "../workflows/send-email"7
8export default async function productCreateHandler({9  event: { data },10  container,11}: SubscriberArgs<{ id: string }>) {12  await sendEmailWorkflow(container).run({13    input: {14      id: data.id,15    },16  })17}18
19export const config: SubscriberConfig = {20  event: "product.created",21}

This subscriber will run every time a product is created, and it will execute the sendEmailWorkflow to send an email using SendGrid.

Was this page helpful?
Ask Anything
FAQ
What is Medusa?
How can I create a module?
How can I create a data model?
How do I create a workflow?
How can I extend a data model in the Product Module?
Recipes
How do I build a marketplace with Medusa?
How do I build digital products with Medusa?
How do I build subscription-based purchases with Medusa?
What other recipes are available in the Medusa documentation?
Chat is cleared on refresh
Line break