Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 33 ยท Payments, Shipping and Integrations

Notifications, Email and File Providers

Send order emails and store files in Medusa: the notification module, channels, SendGrid, subscriber-driven emails, the S3 file provider and templates.

A shop talks to customers constantly: "your order is confirmed", "it has shipped", "reset your password". It also handles files: product images, invoices, CSV exports. Medusa treats both as infrastructure modules with swappable providers. You write your code against the Notification Module or the File Module, and a provider decides whether the message goes through SendGrid or the log, and whether the file lands on disk or in an S3 bucket.

This lesson shows how to configure those providers, how an email is triggered from an event, and how templates fit in. The real Medusa code is read-only, because it needs a server and third-party accounts. The runnable parts are Node stand-ins: a notification dispatcher with templates and a file provider interface. For the product-level picture of transactional mail, see Email and Customer Lifecycle Messages.

The Notification Module

The Notification Module has a small vocabulary:

  • A notification is a record of one message: who it goes to (to), which channel (email, sms, feed, ...), which template and the data to fill it with.
  • A provider can send on one or more channels. Each provider declares its channels in the configuration.
  • Medusa stores notifications, so you can see what was sent, and the module can deduplicate by an idempotency key that you supply.

Providers are registered in medusa-config.ts. This is real Medusa configuration (read-only; verify option names for your version):

TypeScript
import { defineConfig } from "@medusajs/framework/utils"

export default defineConfig({
  modules: [
    {
      resolve: "@medusajs/medusa/notification",
      options: {
        providers: [
          {
            resolve: "@medusajs/medusa/notification-sendgrid",
            id: "sendgrid",
            options: {
              channels: ["email"],
              api_key: process.env.SENDGRID_API_KEY,
              from: process.env.SENDGRID_FROM,
            },
          },
        ],
      },
    },
  ],
})

Medusa also includes a local provider that writes to the log (useful in development) and a provider for the admin's "feed" channel. For other services such as Resend or Mailgun, you install a community provider or write your own: a notification provider module service with a send method that receives the notification and calls the vendor's API. Provider packages and their options change over time, so check the provider's own documentation when you pick one.

Because the channels list is explicit, a request for the email channel is routed to the provider that declared it. If no provider handles a channel, the call fails, which is why development setups register the local provider.

Sending from a subscriber

Emails should not be sent inside the request that creates an order: the shopper does not need to wait for a mail server. Instead, the order workflow emits an event and a subscriber reacts to it (events are covered in Events and Subscribers). A read-only sketch:

TypeScript
// src/subscribers/order-placed.ts
import type { SubscriberArgs, SubscriberConfig } from "@medusajs/framework"
import { Modules } from "@medusajs/framework/utils"

export default async function orderPlacedHandler({
  event: { data },
  container,
}: SubscriberArgs<{ id: string }>) {
  const query = container.resolve("query")
  const notifications = container.resolve(Modules.NOTIFICATION)

  const { data: [order] } = await query.graph({
    entity: "order",
    fields: ["id", "display_id", "email", "total", "currency_code", "items.*"],
    filters: { id: data.id },
  })

  await notifications.createNotifications({
    to: order.email,
    channel: "email",
    template: "order-placed",
    data: { orderNumber: order.display_id, total: order.total, items: order.items },
    idempotency_key: `order-placed:${order.id}`,
  })
}

export const config: SubscriberConfig = {
  event: "order.placed",
}

Three habits make this reliable:

  1. Load fresh data inside the handler. Event payloads are small (usually just an id), so fetch what the template needs with Query (Query: Fields, Filters and Pagination).
  2. Use an idempotency key. Events can be delivered more than once, and a duplicate must not mean two emails. The key order-placed:<id> makes the second attempt a no-op.
  3. Treat failure as normal. A mail provider can be down. Let the error surface so the event system can retry (see Events and Subscribers) instead of swallowing it.

You can also send notifications from inside a workflow with a step, which is the better choice when the email is part of a larger business operation and should be rolled back or retried with it.

flowchart LR
    W["Order workflow"] -->|"emits order.placed"| E["Event bus"]
    E --> S["Subscriber"]
    S -->|"query order"| D[("Data")]
    S -->|"createNotifications"| N["Notification module"]
    N -->|"channel: email"| P["SendGrid provider"]
    P --> M["Customer inbox"]

The request that placed the order is long finished by the time the email goes out.

Templates

Medusa's notification record carries a template name (a string) and a data object. What that name means is up to the provider. The SendGrid provider, for example, treats it as the ID of a template stored in SendGrid, and the data fills that template's placeholders on SendGrid's side. If you prefer to keep templates in your repository, a custom provider (or a local email-rendering helper called from the subscriber) can render HTML itself, for instance with React Email, and pass the final HTML to a generic mail API.

Choose where templates live deliberately:

Approach Good for Cost
Templates in the vendor Non-developers edit copy Versioning and tests live outside your repo
Templates in code Reviewed, tested, versioned with the app Developers change every wording edit

Whichever you pick, escape all customer-provided values (names, addresses, notes) before they reach HTML.

Stand-in 1: a notification dispatcher with templates

The first stand-in is not Medusa code. It reproduces the pipeline: channel routing, template rendering with escaping, and idempotency keys.

Node.js A notification dispatcher with channels, templates and idempotency

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Look at the output: the name Dana <script> is escaped in the email body, the second identical order email is skipped, a channel with no provider fails loudly, and a missing template value (tracking) is an error rather than a silently broken email. Those are the same properties you want from a real setup.

The File Module

The File Module stores uploaded files: product images from the Admin, imports and exports, and anything your own routes upload. Like notifications, it has providers:

  • The local provider writes into a folder on the server (the static directory). It is the default and fine for development, but a poor fit for production, because files vanish when a container is replaced and cannot be shared by several servers.
  • The S3 provider stores files in an S3-compatible bucket (AWS S3, Cloudflare R2, MinIO and others).

Configuration for S3 (read-only; confirm the option names in your version's documentation):

TypeScript
{
  resolve: "@medusajs/medusa/file",
  options: {
    providers: [
      {
        resolve: "@medusajs/medusa/file-s3",
        id: "s3",
        options: {
          file_url: process.env.S3_FILE_URL,
          access_key_id: process.env.S3_ACCESS_KEY_ID,
          secret_access_key: process.env.S3_SECRET_ACCESS_KEY,
          region: process.env.S3_REGION,
          bucket: process.env.S3_BUCKET,
          endpoint: process.env.S3_ENDPOINT,
        },
      },
    ],
  },
}

file_url is the public base URL that returned file URLs start with, which is often a CDN domain in front of the bucket. Product images are public, but exports and invoices usually are not; the file module can issue presigned URLs for private objects, so a link works for a short time without making the bucket public. Use separate buckets or prefixes for public and private files, and give the access key only the permissions it needs.

Stand-in 2: a file provider interface

This stand-in shows why the module and provider split pays off: the code that uses files does not know whether bytes land in memory, on disk or in S3. It also shows a presigned-style URL signed with HMAC and an expiry (the scheme is invented for teaching; real S3 presigning is done by the SDK).

Node.js Swapping file providers behind one interface

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Both providers run the same saveInvoice function. That is the point of the module boundary: switching from local disk to S3 is a configuration change, not a rewrite of every route that handles uploads.

Common mistakes

  • Sending email inside the request. A slow mail API makes checkout slow. Use a subscriber or a workflow step.
  • No idempotency key. Redelivered events then send duplicate emails.
  • Local file provider in production. Files disappear on redeploy and differ per server.
  • Public buckets for private files. Serve invoices and exports through presigned URLs.
  • Unescaped customer data in HTML mail. Escape every value, as the stand-in does.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What decides which provider sends a notification?

    Each provider lists its channels in the configuration. A notification for the email channel is routed to the provider that declared email.
  2. 2. Why send order emails from a subscriber rather than inside the checkout request?

    The request finishes without waiting for the mail API, and the event system can retry a failed handler without redoing the order.
  3. 3. What is the purpose of an idempotency key on a notification?

    Events can be delivered more than once. A stable key such as order-placed:<id> lets the module recognize the duplicate.
  4. 4. Why is the local file provider a poor choice for production?

    Containers are replaced and several servers need the same files. A shared store such as an S3-compatible bucket solves both problems.

Summary

  • The Notification Module routes a message by channel to the provider that declared it; SendGrid is an included email provider, and others can be added.
  • Trigger emails from subscribers or workflow steps, load fresh data in the handler and set an idempotency key.
  • Template names are interpreted by the provider; keep templates either in the vendor or in code on purpose, and escape customer data.
  • The File Module hides storage behind providers: local for development, S3-compatible buckets for production, presigned URLs for private files.

Next, change the Admin itself in Admin Dashboard Extensions.