Raw
1 ---
2 products:
3 - order
4 ---
5
6 import { Card, Prerequisites, Details } from "docs-ui"
7 import { Github } from "@medusajs/icons"
8
9 export const ogImage = "https://res.cloudinary.com/dza7lstvk/image/upload/v1732704590/Medusa%20Resources/Integrations_Resend_pam0nf.jpg"
10
11 export const metadata = {
12 title: `Integrate Medusa with Resend (Email Notifications)`,
13 openGraph: {
14 images: [
15 {
16 url: ogImage,
17 width: 1600,
18 height: 900,
19 type: "image/jpeg"
20 }
21 ],
22 },
23 twitter: {
24 images: [
25 {
26 url: ogImage,
27 width: 1600,
28 height: 900,
29 type: "image/jpeg"
30 }
31 ]
32 }
33 }
34
35 # {metadata.title}
36
37 In this guide, you'll learn how to integrate Medusa with Resend.
38
39 When you install a Medusa application, you get a fully-fledged commerce platform with a Framework for customization. Medusa's architecture supports integrating third-party services, such as an email service, that allow you to build your unique requirements around core commerce flows.
40
41 [Resend](https://resend.com/docs/introduction) is an email service with an intuitive developer experience to send emails from any application type, including Node.js servers. By integrating Resend with Medusa, you can build flows to send an email when a commerce operation is performed, such as when an order is placed.
42
43 This guide will teach you how to:
44
45 - Install and set up Medusa.
46 - Integrate Resend into Medusa for sending emails.
47 - Build a flow to send an email with Resend when a customer places an order.
48
49 You can follow this guide whether you're new to Medusa or an advanced Medusa developer.
50
51 <Card
52 title="Example Repository"
53 text="Find the full code of the guide in this repository."
54 href="https://github.com/medusajs/examples/tree/main/resend-integration"
55 icon={Github}
56 />
57
58 ---
59
60 ## Step 1: Install a Medusa Application
61
62 <Prerequisites items={[
63 {
64 text: "Node.js v20.19.0+ or v22.12.0+",
65 link: "https://nodejs.org/en/download"
66 },
67 {
68 text: "Git CLI tool",
69 link: "https://git-scm.com/downloads"
70 },
71 {
72 text: "PostgreSQL",
73 link: "https://www.postgresql.org/download/"
74 }
75 ]} />
76
77 Start by installing the Medusa application on your machine with the following command:
78
79 ```bash
80 npx create-medusa-app@latest
81 ```
82
83 You'll first be asked for the project's name. Then, when you're asked whether you want to install the Next.js Starter Storefront, choose `Y` for yes.
84
85 Afterwards, the installation process will start, which will install the Medusa application as a monorepository in a directory with your project's name. The backend is installed in the `apps/backend` directory, and the Next.js Starter Storefront is installed in the `apps/storefront` directory.
86
87 Once the installation finishes successfully, the Medusa Admin dashboard will open with a form to create a new user. Enter the user's credential and submit the form. Afterwards, you can login with the new user and explore the dashboard.
88
89 The Next.js Starter Storefront is also running at `http://localhost:8000`.
90
91 <Note title="Ran into Errors?">
92
93 Check out the [troubleshooting guides](../../../troubleshooting/create-medusa-app-errors/page.mdx) for help.
94
95 </Note>
96
97 <Note>
98
99 In this guide, all file paths of backend customizations are relative to the `apps/backend` directory of your Medusa project.
100
101 </Note>
102
103 ---
104
105 ## Step 2: Prepare Resend Account
106
107 If you don't have a Resend Account, create one on [their website](https://resend.com/emails).
108
109 In addition, Resend allows you to send emails from the address `onboarding@resend.dev` only to your account's email, which is useful for development purposes. If you have a custom domain to send emails from, add it to your Resend account's domains:
110
111 1. Go to Domains from the sidebar.
112 2. Click on Add Domain.
113
114 ![Resend dashboard interface showing the Domains section in the left sidebar navigation and the prominent "Add Domain" button in the main content area, which initiates the process of configuring a custom domain for email sending through the Resend service](https://res.cloudinary.com/dza7lstvk/image/upload/v1732523238/Medusa%20Resources/Screenshot_2024-11-25_at_10.18.11_AM_pmqgtv.png)
115
116 3\. In the form that opens, enter your domain name and select a region close to your users, then click Add.
117
118 ![Domain configuration modal in Resend showing form fields for entering the custom domain name and selecting the appropriate geographical region for optimal email delivery performance, with an "Add" button to confirm the domain setup](https://res.cloudinary.com/dza7lstvk/image/upload/v1732523280/Medusa%20Resources/Screenshot_2024-11-25_at_10.18.52_AM_sw2pr4.png)
119
120 4\. In the domain's details page that opens, you'll find DNS records to add to your DNS provider. After you add them, click on Verify DNS Records. You can start sending emails from your custom domain once it's verified.
121
122 <Note title="Tip">
123
124 The steps to add DNS records are different for each provider, so refer to your provider's documentation or knowledge base for more details.
125
126 </Note>
127
128 ![The DNS records to add are in a table under the DNS Records section. Once added, click the Verify DNS Records button at the top right.](https://res.cloudinary.com/dza7lstvk/image/upload/v1732523394/Medusa%20Resources/Screenshot_2024-11-25_at_10.20.56_AM_ktvbse.png)
129
130 You also need an API key to connect to your Resend account from Medusa, but you'll create that one in a later section.
131
132 ---
133
134 ## Step 3: Install Resend Dependencies
135
136 In this step, you'll install two packages useful for your Resend integration:
137
138 1. `resend`, which is the Resend SDK:
139
140 ```bash npm2yarn
141 npm install resend
142 ```
143
144 2\. [react-email](https://github.com/resend/react-email), which is a package created by Resend to create email templates with React:
145
146 ```bash npm2yarn
147 npm install @react-email/components -E
148 ```
149
150 You'll use these packages in the next steps.
151
152 ---
153
154 ## Step 4: Create Resend Module Provider
155
156 To integrate third-party services into Medusa, you create a custom module. A module is a re-usable package with functionalities related to a single feature or domain. Medusa integrates the module into your application without implications or side effects on your setup.
157
158 Medusa's Notification Module delegates sending notifications to other modules, called module providers. In this step, you'll create a Resend Module Provider that implements sending notifications through the email channel. In later steps, you'll send email notifications with Resend when an order is placed through this provider.
159
160 <Note>
161
162 Learn more about modules in [this documentation](!docs!/learn/fundamentals/modules).
163
164 </Note>
165
166 ### Create Module Directory
167
168 A module is created under the `src/modules` directory of your Medusa application. So, create the directory `src/modules/resend`.
169
170 ### Create Service
171
172 You define a module's functionalities in a service. A service is a TypeScript or JavaScript class that the module exports. In the service's methods, you can connect to the database, which is useful if your module defines tables in the database, or connect to a third-party service.
173
174 In this section, you'll create the Resend Module Provider's service and the methods necessary to send an email with Resend.
175
176 Start by creating the file `src/modules/resend/service.ts` with the following content:
177
178 export const serviceHighlights1 = [
179 ["12", "api_key", "The Resend API key."],
180 ["13", "from", "The email address to send the emails from."],
181 ["14", "html_templates", "Option to override or provide custom templates."],
182 ["21", "identifier", "Unique identifier that Medusa will use when registering the provider in the database."],
183 ["22", "resendClient", "Client to send emails with Resend."],
184 ["23", "options", "Options passed to the module provider."],
185 ["24", "logger", "Logger utility to log messages in the terminal."]
186 ]
187
188 ```ts title="src/modules/resend/service.ts" highlights={serviceHighlights1}
189 import {
190 AbstractNotificationProviderService,
191 } from "@medusajs/framework/utils"
192 import {
193 Logger,
194 } from "@medusajs/framework/types"
195 import {
196 Resend,
197 } from "resend"
198
199 type ResendOptions = {
200 api_key: string
201 from: string
202 html_templates?: Record<string, {
203 subject?: string
204 content: string
205 }>
206 }
207
208 class ResendNotificationProviderService extends AbstractNotificationProviderService {
209 static identifier = "notification-resend"
210 private resendClient: Resend
211 private options: ResendOptions
212 private logger: Logger
213
214 // ...
215 }
216
217 export default ResendNotificationProviderService
218 ```
219
220 A Notification Module Provider's service must extend the `AbstractNotificationProviderService`. It has a `send` method that you'll implement soon. The service must also have an `identifier` static property, which is a unique identifier that the Medusa application will use to register the provider in the database.
221
222 The `ResendNotificationProviderService` class also has the following properties:
223
224 - `resendClient` of type `Resend` (from the Resend SDK you installed in the previous step) to send emails through Resend.
225 - `options` of type `ResendOptions`. Modules accept options through Medusa's configurations. This ensures that the module is reusable across applications and you don't use sensitive variables like API keys directly in your code. The options that the Resend Module Provider accepts are:
226 - `api_key`: The Resend API key.
227 - `from`: The email address to send the emails from.
228 - `html_templates`: An optional object to replace the default subject and template that the Resend Module uses. This is also useful to support custom emails in different Medusa application setups.
229 - `logger` property, which is an instance of Medusa's [Logger](!docs!/learn/debugging-and-testing/logging), to log messages.
230
231 To send requests using the `resendClient`, you need to initialize it in the class's constructor. So, add the following constructor to `ResendNotificationProviderService`:
232
233 ```ts title="src/modules/resend/service.ts"
234 // ...
235
236 type InjectedDependencies = {
237 logger: Logger
238 }
239
240 class ResendNotificationProviderService extends AbstractNotificationProviderService {
241 // ...
242 constructor(
243 { logger }: InjectedDependencies,
244 options: ResendOptions
245 ) {
246 super()
247 this.resendClient = new Resend(options.api_key)
248 this.options = options
249 this.logger = logger
250 }
251 }
252 ```
253
254 A module's service accepts two parameters:
255
256 1. Dependencies resolved from the [Module's container](!docs!/learn/fundamentals/modules/container), which is the module's local registry that the Medusa application adds Framework tools to. In this service, you resolve the [Logger utility](!docs!/learn/debugging-and-testing/logging) from the module's container.
257 2. The module's options that are passed to the module in Medusa's configuration as you'll see in a later section.
258
259 Using the API key passed in the module's options, you initialize the Resend client. You also set the `options` and `logger` properties.
260
261 #### Validate Options Method
262
263 A Notification Module Provider's service can implement a static `validateOptions` method that ensures the options passed to the module through Medusa's configurations are valid.
264
265 So, add to the `ResendNotificationProviderService` the `validateOptions` method:
266
267 ```ts title="src/modules/resend/service.ts"
268 // other imports...
269 import {
270 // other imports...
271 MedusaError,
272 } from "@medusajs/framework/utils"
273
274 // ...
275
276 class ResendNotificationProviderService extends AbstractNotificationProviderService {
277 // ...
278 static validateOptions(options: Record<any, any>) {
279 if (!options.api_key) {
280 throw new MedusaError(
281 MedusaError.Types.INVALID_DATA,
282 "Option `api_key` is required in the provider's options."
283 )
284 }
285 if (!options.from) {
286 throw new MedusaError(
287 MedusaError.Types.INVALID_DATA,
288 "Option `from` is required in the provider's options."
289 )
290 }
291 }
292 }
293 ```
294
295 In the `validateOptions` method, you throw an error if the `api_key` or `from` options aren't passed to the module. To throw errors, you use `MedusaError` from the Modules SDK. This ensures errors follow Medusa's conventions and are displayed similar to Medusa's errors.
296
297 #### Implement Template Methods
298
299 Each email type has a different template and content. For example, order confirmation emails show the order's details, whereas customer confirmation emails show a greeting message to the customer.
300
301 So, add two methods to the `ResendNotificationProviderService` class that retrieve the email template and subject of a specified template type:
302
303 export const serviceHighlights2 = [
304 ["3", "Templates", "Names of supported template types."],
305 ["7", "templates", "A map of templates for each template type."],
306 ["13", "getTemplate", "Retrieve the template of a template type."],
307 ["26", "getTemplateSubject", "Retrieve the subject line of a template type."]
308 ]
309
310 ```ts title="src/modules/resend/service.ts" highlights={serviceHighlights2}
311 // imports and types...
312
313 enum Templates {
314 ORDER_PLACED = "order-placed",
315 }
316
317 const templates: {[key in Templates]?: (props: unknown) => React.ReactNode} = {
318 // TODO add templates
319 }
320
321 class ResendNotificationProviderService extends AbstractNotificationProviderService {
322 // ...
323 getTemplate(template: Templates) {
324 if (this.options.html_templates?.[template]) {
325 return this.options.html_templates[template].content
326 }
327 const allowedTemplates = Object.keys(templates)
328
329 if (!allowedTemplates.includes(template)) {
330 return null
331 }
332
333 return templates[template]
334 }
335
336 getTemplateSubject(template: Templates) {
337 if (this.options.html_templates?.[template]?.subject) {
338 return this.options.html_templates[template].subject
339 }
340 switch(template) {
341 case Templates.ORDER_PLACED:
342 return "Order Confirmation"
343 default:
344 return "New Email"
345 }
346 }
347 }
348 ```
349
350 You first define a `Templates` enum, which holds the names of supported template types. You can add more template types to this enum later. You also define a `templates` variable that specifies the React template for each template type. You'll add templates to this variable later.
351
352 In the `ResendNotificationProviderService` you add two methods:
353
354 - `getTemplate`: Retrieve the template of a template type. If the `html_templates` option is set for the specified template type, you return its `content`'s value. Otherwise, you retrieve the template from the `templates` variable.
355 - `getTemplateSubject`: Retrieve the subject of a template type. If a `subject` is passed for the template type in the `html_templates`, you return its value. Otherwise, you return a subject based on the template type.
356
357 You'll use these methods in the `send` method next.
358
359 #### Implement Send Method
360
361 In this section, you'll implement the `send` method of `ResendNotificationProviderService`. When you send a notification through the email channel later using the Notification Module, the Notification Module's service will use this `send` method under the hood to send the email with Resend.
362
363 In the `send` method, you'll retrieve the template and subject of the email template, then send the email using the Resend client.
364
365 Add the `send` method to the `ResendNotificationProviderService` class:
366
367 export const serviceHighlights3 = [
368 ["17", "getTemplate", "Get the template of the specified type."],
369 ["25", "from", "The email address to send the email from."],
370 ["26", "to", "The email address to send the email to"],
371 ["27", "getTemplateSubject", "Get the email subject for the template type."],
372 ["34", "html", "Set the template as an HTML template if its type is `string`."],
373 ["39", "react", "Set the template as a React template."],
374 ["43", "send", "Send the email using the Resend client."]
375 ]
376
377 ```ts title="src/modules/resend/service.ts" highlights={serviceHighlights3}
378 // other imports...
379 import {
380 // ...
381 ProviderSendNotificationDTO,
382 ProviderSendNotificationResultsDTO,
383 } from "@medusajs/framework/types"
384 import {
385 // ...
386 CreateEmailOptions,
387 } from "resend"
388
389 class ResendNotificationProviderService extends AbstractNotificationProviderService {
390 // ...
391 async send(
392 notification: ProviderSendNotificationDTO
393 ): Promise<ProviderSendNotificationResultsDTO> {
394 const template = this.getTemplate(notification.template as Templates)
395
396 if (!template) {
397 this.logger.error(`Couldn't find an email template for ${notification.template}. The valid options are ${Object.values(Templates)}`)
398 return {}
399 }
400
401 const commonOptions = {
402 from: this.options.from,
403 to: [notification.to],
404 subject: this.getTemplateSubject(notification.template as Templates),
405 }
406
407 let emailOptions: CreateEmailOptions
408 if (typeof template === "string") {
409 emailOptions = {
410 ...commonOptions,
411 html: template,
412 }
413 } else {
414 emailOptions = {
415 ...commonOptions,
416 react: template(notification.data),
417 }
418 }
419
420 const { data, error } = await this.resendClient.emails.send(emailOptions)
421
422 if (error || !data) {
423 if (error) {
424 this.logger.error("Failed to send email", error)
425 } else {
426 this.logger.error("Failed to send email: unknown error")
427 }
428 return {}
429 }
430
431 return { id: data.id }
432 }
433 }
434 ```
435
436 The `send` method receives the notification details object as a parameter. Some of its properties include:
437
438 - `to`: The address to send the notification to.
439 - `template`: The template type of the notification.
440 - `data`: The data useful for the email type. For example, when sending an order-confirmation email, `data` would hold the order's details.
441
442 In the method, you retrieve the template and subject of the email using the methods you defined earlier. Then, you put together the data to pass to Resend, such as the email address to send the notification to and the email address to send from.
443
444 Also, if the email's template is a string, it's passed as an HTML template. Otherwise, it's passed as a React template.
445
446 Finally, you use the `emails.send` method of the Resend client to send the email. If an error occurs you log it in the terminal. Otherwise, you return the ID of the send email as received from Resend. Medusa uses this ID when creating the notification in its database.
447
448 ### Export Module Definition
449
450 The `ResendNotificationProviderService` class now has the methods necessary to start sending emails.
451
452 Next, you must export the module provider's definition, which lets Medusa know what module this provider belongs to and its service.
453
454 Create the file `src/modules/resend/index.ts` with the following content:
455
456 ```ts title="src/modules/resend/index.ts"
457 import {
458 ModuleProvider,
459 Modules,
460 } from "@medusajs/framework/utils"
461 import ResendNotificationProviderService from "./service"
462
463 export default ModuleProvider(Modules.NOTIFICATION, {
464 services: [ResendNotificationProviderService],
465 })
466 ```
467
468 You export the module provider's definition using `ModuleProvider` from the Modules SDK. It accepts as a first parameter the name of the module that this provider belongs to, which is the Notification Module. It also accepts as a second parameter an object having a `service` property indicating the provider's service.
469
470 ### Add Module to Configurations
471
472 Finally, to register modules and module providers in Medusa, you must add them to Medusa's configurations.
473
474 Medusa's configurations are set in the `medusa-config.ts` file, which is at the root directory of your Medusa application. The configuration object accepts a `modules` array, whose value is an array of modules to add to the application.
475
476 Add the `modules` property to the exported configurations in `medusa-config.ts`:
477
478 ```ts title="medusa-config.ts"
479 module.exports = defineConfig({
480 // ...
481 modules: [
482 {
483 resolve: "@medusajs/medusa/notification",
484 options: {
485 providers: [
486 {
487 resolve: "./src/modules/resend",
488 id: "resend",
489 options: {
490 channels: ["email"],
491 api_key: process.env.RESEND_API_KEY,
492 from: process.env.RESEND_FROM_EMAIL,
493 },
494 },
495 ],
496 },
497 },
498 ],
499 })
500 ```
501
502 In the `modules` array, you pass a module object having the following properties:
503
504 - `resolve`: The NPM package of the Notification Module. Since the Resend Module is a Notification Module Provider, it'll be passed in the options of the Notification Module.
505 - `options`: An object of options to pass to the module. It has a `providers` property which is an array of module providers to register. Each module provider object has the following properties:
506 - `resolve`: The path to the module provider to register in the application. It can also be the name of an NPM package.
507 - `id`: A unique ID, which Medusa will use along with the `identifier` static property that you set earlier in the class to identify this module provider.
508 - `options`: An object of options to pass to the module provider. These are the options you expect and use in the module provider's service. You must also specify the `channels` option, which indicates the channels that this provider sends notifications through.
509
510 Some of the module's options, such as the Resend API key, are set in environment variables. So, add the following environment variables to `.env`:
511
512 ```shell
513 RESEND_FROM_EMAIL=onboarding@resend.dev
514 RESEND_API_KEY=
515 ```
516
517 Where:
518
519 - `RESEND_FROM_EMAIL`: The email to send emails from. If you've configured the custom domain as explained in [Step 2](#step-2-prepare-resend-account), change this email to an email from your custom domain. Otherwise, you can use `onboarding@resend.dev` for development purposes.
520 - `RESEND_API_KEY` is the API key of your Resend account. To retrieve it:
521 - Go to API Keys in the sidebar.
522 - Click on the Create API Key button.
523
524 ![Click on the API keys in the sidebar, then click on the Create API Key button at the top right](https://res.cloudinary.com/dza7lstvk/image/upload/v1732535399/Medusa%20Resources/Screenshot_2024-11-25_at_10.22.25_AM_v4d09s.png)
525
526 - In the form that opens, enter a name for the API key (for example, Medusa). You can keep its permissions to Full Access or change it to Sending Access. Once you're done, click Add.
527
528 ![The form to create an API key with fields for the API key's name, permissions, and domain](https://res.cloudinary.com/dza7lstvk/image/upload/v1732535464/Medusa%20Resources/Screenshot_2024-11-25_at_10.23.26_AM_g7gcuc.png)
529
530 - A new pop-up will show with your API key hidden. Copy it before closing the pop-up, since you can't access the key again afterwards. Use its value for the `RESEND_API_KEY` environment variable.
531
532 ![Click the copy icon to copy the API key](https://res.cloudinary.com/dza7lstvk/image/upload/v1732535791/Medusa%20Resources/Screenshot_2024-11-25_at_10.23.43_AM_divins.png)
533
534 Your Resend Module Provider is all set up. You'll test it out in a later section.
535
536 ---
537
538 ## Step 5: Add Order Confirmation Template
539
540 In this step, you'll add a React template for order confirmation emails. You'll create it using the [react-email](https://github.com/resend/react-email) package you installed earlier. You can follow the same steps for other email templates, such as for customer confirmation.
541
542 Create the directory `src/modules/resend/emails` that will hold the email templates. Then, to add the template for order confirmation, create the file `src/modules/resend/emails/order-placed.tsx` with the following content:
543
544 export const templateHighlights = [
545 ["29", "OrderPlacedEmailComponent", "The template React component for order confirmation emails."],
546 ["193", "orderPlacedEmail", "A function that returns the JSX `OrderPlacedEmailComponent`."]
547 ]
548
549 ```tsx title="src/modules/resend/emails/order-placed.tsx" highlights={templateHighlights} collapsibleLines="1-17" expandMoreLabel="Show Imports"
550 import {
551 Text,
552 Column,
553 Container,
554 Heading,
555 Html,
556 Img,
557 Row,
558 Section,
559 Tailwind,
560 Head,
561 Preview,
562 Body,
563 Link,
564 } from "@react-email/components"
565 import { BigNumberValue, CustomerDTO, OrderDTO } from "@medusajs/framework/types"
566
567 type OrderPlacedEmailProps = {
568 order: OrderDTO & {
569 customer: CustomerDTO
570 }
571 email_banner?: {
572 body: string
573 title: string
574 url: string
575 }
576 }
577
578 function OrderPlacedEmailComponent({ order, email_banner }: OrderPlacedEmailProps) {
579 const shouldDisplayBanner = email_banner && "title" in email_banner
580
581 const formatter = new Intl.NumberFormat([], {
582 style: "currency",
583 currencyDisplay: "narrowSymbol",
584 currency: order.currency_code,
585 })
586
587 const formatPrice = (price: BigNumberValue) => {
588 if (typeof price === "number") {
589 return formatter.format(price)
590 }
591
592 if (typeof price === "string") {
593 return formatter.format(parseFloat(price))
594 }
595
596 return price?.toString() || ""
597 }
598
599 return (
600 <Tailwind>
601 <Html className="font-sans bg-gray-100">
602 <Head />
603 <Preview>Thank you for your order from Medusa</Preview>
604 <Body className="bg-white my-10 mx-auto w-full max-w-2xl">
605 {/* Header */}
606 <Section className="bg-[#27272a] text-white px-6 py-4">
607 <svg width="15" height="15" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M16.2447 3.92183L12.1688 1.57686C10.8352 0.807712 9.20112 0.807712 7.86753 1.57686L3.77285 3.92183C2.45804 4.69098 1.63159 6.11673 1.63159 7.63627V12.345C1.63159 13.8833 2.45804 15.2903 3.77285 16.0594L7.84875 18.4231C9.18234 19.1923 10.8165 19.1923 12.15 18.4231L16.2259 16.0594C17.5595 15.2903 18.3672 13.8833 18.3672 12.345V7.63627C18.4048 6.11673 17.5783 4.69098 16.2447 3.92183ZM10.0088 14.1834C7.69849 14.1834 5.82019 12.3075 5.82019 10C5.82019 7.69255 7.69849 5.81657 10.0088 5.81657C12.3191 5.81657 14.2162 7.69255 14.2162 10C14.2162 12.3075 12.3379 14.1834 10.0088 14.1834Z" fill="currentColor"></path></svg>
608 </Section>
609
610 {/* Thank You Message */}
611 <Container className="p-6">
612 <Heading className="text-2xl font-bold text-center text-gray-800">
613 Thank you for your order, {order.customer?.first_name || order.shipping_address?.first_name}
614 </Heading>
615 <Text className="text-center text-gray-600 mt-2">
616 We're processing your order and will notify you when it ships.
617 </Text>
618 </Container>
619
620 {/* Promotional Banner */}
621 {shouldDisplayBanner && (
622 <Container
623 className="mb-4 rounded-lg p-7"
624 style={{
625 background: "linear-gradient(to right, #3b82f6, #4f46e5)",
626 }}
627 >
628 <Section>
629 <Row>
630 <Column align="left">
631 <Heading className="text-white text-xl font-semibold">
632 {email_banner.title}
633 </Heading>
634 <Text className="text-white mt-2">{email_banner.body}</Text>
635 </Column>
636 <Column align="right">
637 <Link href={email_banner.url} className="font-semibold px-2 text-white underline">
638 Shop Now
639 </Link>
640 </Column>
641 </Row>
642 </Section>
643 </Container>
644 )}
645
646 {/* Order Items */}
647 <Container className="px-6">
648 <Heading className="text-xl font-semibold text-gray-800 mb-4">
649 Your Items
650 </Heading>
651 <Row>
652 <Column>
653 <Text className="text-sm m-0 my-2 text-gray-500">Order ID: #{order.display_id}</Text>
654 </Column>
655 </Row>
656 {order.items?.map((item) => (
657 <Section key={item.id} className="border-b border-gray-200 py-4">
658 <Row>
659 <Column className="w-1/3">
660 <Img
661 src={item.thumbnail ?? ""}
662 alt={item.product_title ?? ""}
663 className="rounded-lg"
664 width="100%"
665 />
666 </Column>
667 <Column className="w-2/3 pl-4">
668 <Text className="text-lg font-semibold text-gray-800">
669 {item.product_title}
670 </Text>
671 <Text className="text-gray-600">{item.variant_title}</Text>
672 <Text className="text-gray-800 mt-2 font-bold">
673 {formatPrice(item.total)}
674 </Text>
675 </Column>
676 </Row>
677 </Section>
678 ))}
679
680 {/* Order Summary */}
681 <Section className="mt-8">
682 <Heading className="text-xl font-semibold text-gray-800 mb-4">
683 Order Summary
684 </Heading>
685 <Row className="text-gray-600">
686 <Column className="w-1/2">
687 <Text className="m-0">Subtotal</Text>
688 </Column>
689 <Column className="w-1/2 text-right">
690 <Text className="m-0">
691 {formatPrice(order.item_total)}
692 </Text>
693 </Column>
694 </Row>
695 {order.shipping_methods?.map((method) => (
696 <Row className="text-gray-600" key={method.id}>
697 <Column className="w-1/2">
698 <Text className="m-0">{method.name}</Text>
699 </Column>
700 <Column className="w-1/2 text-right">
701 <Text className="m-0">{formatPrice(method.total)}</Text>
702 </Column>
703 </Row>
704 ))}
705 <Row className="text-gray-600">
706 <Column className="w-1/2">
707 <Text className="m-0">Tax</Text>
708 </Column>
709 <Column className="w-1/2 text-right">
710 <Text className="m-0">{formatPrice(order.tax_total || 0)}</Text>
711 </Column>
712 </Row>
713 <Row className="border-t border-gray-200 mt-4 text-gray-800 font-bold">
714 <Column className="w-1/2">
715 <Text>Total</Text>
716 </Column>
717 <Column className="w-1/2 text-right">
718 <Text>{formatPrice(order.total)}</Text>
719 </Column>
720 </Row>
721 </Section>
722 </Container>
723
724 {/* Footer */}
725 <Section className="bg-gray-50 p-6 mt-10">
726 <Text className="text-center text-gray-500 text-sm">
727 If you have any questions, reply to this email or contact our support team at support@medusajs.com.
728 </Text>
729 <Text className="text-center text-gray-500 text-sm">
730 Order Token: {order.id}
731 </Text>
732 <Text className="text-center text-gray-400 text-xs mt-4">
733 © {new Date().getFullYear()} Medusajs, Inc. All rights reserved.
734 </Text>
735 </Section>
736 </Body>
737 </Html>
738 </Tailwind >
739 )
740 }
741
742 export const orderPlacedEmail = (props: OrderPlacedEmailProps) => (
743 <OrderPlacedEmailComponent {...props} />
744 )
745 ```
746
747 You define the `OrderPlacedEmailComponent` which is a React email template that shows the order's details, such as items and their totals. The component accepts an `order` object as a prop.
748
749 You also export an `orderPlacedEmail` function, which accepts props as an input and returns the `OrderPlacedEmailComponent` passing it the props. Because you can't use JSX syntax in `src/modules/resend/service.ts`, you'll import this function instead.
750
751 Next, update the `templates` variable in `src/modules/resend/service.ts` to assign this template to the `order-placed` template type:
752
753 ```ts title="src/modules/resend/service.ts"
754 // other imports...
755 import { orderPlacedEmail } from "./emails/order-placed"
756
757 const templates: {[key in Templates]?: (props: unknown) => React.ReactNode} = {
758 [Templates.ORDER_PLACED]: orderPlacedEmail,
759 }
760 ```
761
762 The `ResendNotificationProviderService` will now use the `OrderPlacedEmailComponent` as the template of order confirmation emails.
763
764 ### Test Email Out
765
766 You'll later test out sending the email when an order is placed. However, you can also test out how the email looks like using [React Email's CLI tool](https://react.email/docs/cli).
767
768 First, install the CLI tool in your Medusa application:
769
770 ```bash npm2yarn
771 npm install -D react-email
772 ```
773
774 Then, in `src/modules/resend/emails/order-placed.tsx`, add the following at the end of the file:
775
776 ```tsx title="src/modules/resend/emails/order-placed.tsx"
777 const mockOrder = {
778 "order": {
779 "id": "order_01JSNXDH9BPJWWKVW03B9E9KW8",
780 "display_id": 1,
781 "email": "afsaf@gmail.com",
782 "currency_code": "eur",
783 "total": 20,
784 "subtotal": 20,
785 "discount_total": 0,
786 "shipping_total": 10,
787 "tax_total": 0,
788 "item_subtotal": 10,
789 "item_total": 10,
790 "item_tax_total": 0,
791 "customer_id": "cus_01JSNXD6VQC1YH56E4TGC81NWX",
792 "items": [
793 {
794 "id": "ordli_01JSNXDH9C47KZ43WQ3TBFXZA9",
795 "title": "L",
796 "subtitle": "Medusa Sweatshirt",
797 "thumbnail": "https://medusa-public-images.s3.eu-west-1.amazonaws.com/sweatshirt-vintage-front.png",
798 "variant_id": "variant_01JSNXAQCZ5X81A3NRSVFJ3ZHQ",
799 "product_id": "prod_01JSNXAQBQ6MFV5VHKN420NXQW",
800 "product_title": "Medusa Sweatshirt",
801 "product_description": "Reimagine the feeling of a classic sweatshirt. With our cotton sweatshirt, everyday essentials no longer have to be ordinary.",
802 "product_subtitle": null,
803 "product_type": null,
804 "product_type_id": null,
805 "product_collection": null,
806 "product_handle": "sweatshirt",
807 "variant_sku": "SWEATSHIRT-L",
808 "variant_barcode": null,
809 "variant_title": "L",
810 "variant_option_values": null,
811 "requires_shipping": true,
812 "is_giftcard": false,
813 "is_discountable": true,
814 "is_tax_inclusive": false,
815 "is_custom_price": false,
816 "metadata": {},
817 "raw_compare_at_unit_price": null,
818 "raw_unit_price": {
819 "value": "10",
820 "precision": 20,
821 },
822 "created_at": new Date(),
823 "updated_at": new Date(),
824 "deleted_at": null,
825 "tax_lines": [],
826 "adjustments": [],
827 "compare_at_unit_price": null,
828 "unit_price": 10,
829 "quantity": 1,
830 "raw_quantity": {
831 "value": "1",
832 "precision": 20,
833 },
834 "detail": {
835 "id": "orditem_01JSNXDH9DK1XMESEZPADYFWKY",
836 "version": 1,
837 "metadata": null,
838 "order_id": "order_01JSNXDH9BPJWWKVW03B9E9KW8",
839 "raw_unit_price": null,
840 "raw_compare_at_unit_price": null,
841 "raw_quantity": {
842 "value": "1",
843 "precision": 20,
844 },
845 "raw_fulfilled_quantity": {
846 "value": "0",
847 "precision": 20,
848 },
849 "raw_delivered_quantity": {
850 "value": "0",
851 "precision": 20,
852 },
853 "raw_shipped_quantity": {
854 "value": "0",
855 "precision": 20,
856 },
857 "raw_return_requested_quantity": {
858 "value": "0",
859 "precision": 20,
860 },
861 "raw_return_received_quantity": {
862 "value": "0",
863 "precision": 20,
864 },
865 "raw_return_dismissed_quantity": {
866 "value": "0",
867 "precision": 20,
868 },
869 "raw_written_off_quantity": {
870 "value": "0",
871 "precision": 20,
872 },
873 "created_at": new Date(),
874 "updated_at": new Date(),
875 "deleted_at": null,
876 "item_id": "ordli_01JSNXDH9C47KZ43WQ3TBFXZA9",
877 "unit_price": null,
878 "compare_at_unit_price": null,
879 "quantity": 1,
880 "fulfilled_quantity": 0,
881 "delivered_quantity": 0,
882 "shipped_quantity": 0,
883 "return_requested_quantity": 0,
884 "return_received_quantity": 0,
885 "return_dismissed_quantity": 0,
886 "written_off_quantity": 0,
887 },
888 "subtotal": 10,
889 "total": 10,
890 "original_total": 10,
891 "discount_total": 0,
892 "discount_subtotal": 0,
893 "discount_tax_total": 0,
894 "tax_total": 0,
895 "original_tax_total": 0,
896 "refundable_total_per_unit": 10,
897 "refundable_total": 10,
898 "fulfilled_total": 0,
899 "shipped_total": 0,
900 "return_requested_total": 0,
901 "return_received_total": 0,
902 "return_dismissed_total": 0,
903 "write_off_total": 0,
904 "raw_subtotal": {
905 "value": "10",
906 "precision": 20,
907 },
908 "raw_total": {
909 "value": "10",
910 "precision": 20,
911 },
912 "raw_original_total": {
913 "value": "10",
914 "precision": 20,
915 },
916 "raw_discount_total": {
917 "value": "0",
918 "precision": 20,
919 },
920 "raw_discount_subtotal": {
921 "value": "0",
922 "precision": 20,
923 },
924 "raw_discount_tax_total": {
925 "value": "0",
926 "precision": 20,
927 },
928 "raw_tax_total": {
929 "value": "0",
930 "precision": 20,
931 },
932 "raw_original_tax_total": {
933 "value": "0",
934 "precision": 20,
935 },
936 "raw_refundable_total_per_unit": {
937 "value": "10",
938 "precision": 20,
939 },
940 "raw_refundable_total": {
941 "value": "10",
942 "precision": 20,
943 },
944 "raw_fulfilled_total": {
945 "value": "0",
946 "precision": 20,
947 },
948 "raw_shipped_total": {
949 "value": "0",
950 "precision": 20,
951 },
952 "raw_return_requested_total": {
953 "value": "0",
954 "precision": 20,
955 },
956 "raw_return_received_total": {
957 "value": "0",
958 "precision": 20,
959 },
960 "raw_return_dismissed_total": {
961 "value": "0",
962 "precision": 20,
963 },
964 "raw_write_off_total": {
965 "value": "0",
966 "precision": 20,
967 },
968 },
969 ],
970 "shipping_address": {
971 "id": "caaddr_01JSNXD6W0TGPH2JQD18K97B25",
972 "customer_id": null,
973 "company": "",
974 "first_name": "safasf",
975 "last_name": "asfaf",
976 "address_1": "asfasf",
977 "address_2": "",
978 "city": "asfasf",
979 "country_code": "dk",
980 "province": "",
981 "postal_code": "asfasf",
982 "phone": "",
983 "metadata": null,
984 "created_at": "2025-04-25T07:25:48.801Z",
985 "updated_at": "2025-04-25T07:25:48.801Z",
986 "deleted_at": null,
987 },
988 "billing_address": {
989 "id": "caaddr_01JSNXD6W0V7RNZH63CPG26K5W",
990 "customer_id": null,
991 "company": "",
992 "first_name": "safasf",
993 "last_name": "asfaf",
994 "address_1": "asfasf",
995 "address_2": "",
996 "city": "asfasf",
997 "country_code": "dk",
998 "province": "",
999 "postal_code": "asfasf",
1000 "phone": "",
1001 "metadata": null,
1002 "created_at": "2025-04-25T07:25:48.801Z",
1003 "updated_at": "2025-04-25T07:25:48.801Z",
1004 "deleted_at": null,
1005 },
1006 "shipping_methods": [
1007 {
1008 "id": "ordsm_01JSNXDH9B9DDRQXJT5J5AE5V1",
1009 "name": "Standard Shipping",
1010 "description": null,
1011 "is_tax_inclusive": false,
1012 "is_custom_amount": false,
1013 "shipping_option_id": "so_01JSNXAQA64APG6BNHGCMCTN6V",
1014 "data": {},
1015 "metadata": null,
1016 "raw_amount": {
1017 "value": "10",
1018 "precision": 20,
1019 },
1020 "created_at": new Date(),
1021 "updated_at": new Date(),
1022 "deleted_at": null,
1023 "tax_lines": [],
1024 "adjustments": [],
1025 "amount": 10,
1026 "order_id": "order_01JSNXDH9BPJWWKVW03B9E9KW8",
1027 "detail": {
1028 "id": "ordspmv_01JSNXDH9B5RAF4FH3M1HH3TEA",
1029 "version": 1,
1030 "order_id": "order_01JSNXDH9BPJWWKVW03B9E9KW8",
1031 "return_id": null,
1032 "exchange_id": null,
1033 "claim_id": null,
1034 "created_at": new Date(),
1035 "updated_at": new Date(),
1036 "deleted_at": null,
1037 "shipping_method_id": "ordsm_01JSNXDH9B9DDRQXJT5J5AE5V1",
1038 },
1039 "subtotal": 10,
1040 "total": 10,
1041 "original_total": 10,
1042 "discount_total": 0,
1043 "discount_subtotal": 0,
1044 "discount_tax_total": 0,
1045 "tax_total": 0,
1046 "original_tax_total": 0,
1047 "raw_subtotal": {
1048 "value": "10",
1049 "precision": 20,
1050 },
1051 "raw_total": {
1052 "value": "10",
1053 "precision": 20,
1054 },
1055 "raw_original_total": {
1056 "value": "10",
1057 "precision": 20,
1058 },
1059 "raw_discount_total": {
1060 "value": "0",
1061 "precision": 20,
1062 },
1063 "raw_discount_subtotal": {
1064 "value": "0",
1065 "precision": 20,
1066 },
1067 "raw_discount_tax_total": {
1068 "value": "0",
1069 "precision": 20,
1070 },
1071 "raw_tax_total": {
1072 "value": "0",
1073 "precision": 20,
1074 },
1075 "raw_original_tax_total": {
1076 "value": "0",
1077 "precision": 20,
1078 },
1079 },
1080 ],
1081 "customer": {
1082 "id": "cus_01JSNXD6VQC1YH56E4TGC81NWX",
1083 "company_name": null,
1084 "first_name": null,
1085 "last_name": null,
1086 "email": "afsaf@gmail.com",
1087 "phone": null,
1088 "has_account": false,
1089 "metadata": null,
1090 "created_by": null,
1091 "created_at": "2025-04-25T07:25:48.791Z",
1092 "updated_at": "2025-04-25T07:25:48.791Z",
1093 "deleted_at": null,
1094 },
1095 },
1096 }
1097 // @ts-ignore
1098 export default () => <OrderPlacedEmailComponent {...mockOrder} />
1099 ```
1100
1101 You create a mock order object that contains the order's details. Then, you export a default function that returns the `OrderPlacedEmailComponent` passing it the mock order.
1102
1103 The React Email CLI tool will use the function to render the email template.
1104
1105 Finally, add the following script to `package.json`:
1106
1107 ```json
1108 {
1109 "scripts": {
1110 "dev:email": "email dev --dir ./src/modules/resend/emails"
1111 }
1112 }
1113 ```
1114
1115 This script will run the React Email CLI tool, passing it the directory where the email templates are located.
1116
1117 You can now test out the email template by running the following command:
1118
1119 ```bash npm2yarn
1120 npm run dev:email
1121 ```
1122
1123 This will start a development server at `http://localhost:3000`. If you open this URL, you can view your email templates in the browser.
1124
1125 You can make changes to the email template, and the server will automatically reload the changes.
1126
1127 ![The email template rendered in the browser](https://res.cloudinary.com/dza7lstvk/image/upload/v1745568201/Medusa%20Resources/Screenshot_2025-04-25_at_10.41.26_AM_u86abc.png)
1128
1129 ---
1130
1131 ## Step 6: Send Email when Order is Placed
1132
1133 Medusa has an event system that emits an event when a commerce operation is performed. You can then listen and handle that event in an asynchronous function called a subscriber.
1134
1135 So, to send a confirmation email when a customer places an order, which is a commerce operation that Medusa already implements, you don't need to extend or hack your way into Medusa's implementation as you would do with other commerce platforms.
1136
1137 Instead, you'll create a subscriber that listens to the `order.placed` event and sends an email when the event is emitted.
1138
1139 <Note>
1140
1141 Learn more about Medusa's event system in [this documentation](!docs!/learn/fundamentals/events-and-subscribers).
1142
1143 </Note>
1144
1145 ### Send Order Confirmation Email Workflow
1146
1147 To send the order confirmation email, you need to retrieve the order's details first, then use the Notification Module's service to send the email. To implement this flow, you'll create a workflow.
1148
1149 A workflow is a series of queries and actions, called steps, that complete a task. You construct a workflow like you construct a function, but it's a special function that allows you to track its executions' progress, define roll-back logic, and configure other advanced features. Then, you execute the workflow from other customizations, such as in a subscriber.
1150
1151 <Note>
1152
1153 Learn more about workflows in [this documentation](!docs!/learn/fundamentals/workflows)
1154
1155 </Note>
1156
1157 #### Send Notification Step
1158
1159 You'll start by implementing the step of the workflow that sends the notification. To do that, create the file `src/workflows/steps/send-notification.ts` with the following content:
1160
1161 ```ts title="src/workflows/steps/send-notification.ts"
1162 import { Modules } from "@medusajs/framework/utils"
1163 import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"
1164 import { CreateNotificationDTO } from "@medusajs/framework/types"
1165
1166 export const sendNotificationStep = createStep(
1167 "send-notification",
1168 async (data: CreateNotificationDTO[], { container }) => {
1169 const notificationModuleService = container.resolve(
1170 Modules.NOTIFICATION
1171 )
1172 const notification = await notificationModuleService.createNotifications(data)
1173 return new StepResponse(notification)
1174 }
1175 )
1176 ```
1177
1178 You define the `sendNotificationStep` using the `createStep` function that accepts two parameters:
1179
1180 - A string indicating the step's unique name.
1181 - The step's function definition as a second parameter. It accepts the step's input as a first parameter, and an object of options as a second.
1182
1183 The `container` property in the second parameter is an instance of the [Medusa container](!docs!/learn/fundamentals/medusa-container), which is a registry of Framework and commerce tools, such as a module's service, that you can resolve to utilize their functionalities.
1184
1185 <Note title="Tip">
1186
1187 The Medusa container is accessible by all customizations, such as workflows and subscribers, except for modules. Each module has its own container with Framework tools like the Logger utility.
1188
1189 </Note>
1190
1191 In the step function, you resolve the Notification Module's service, and use its `createNotifications` method, passing it the notification's data that the step receives as an input.
1192
1193 The step returns an instance of `StepResponse`, which must be returned by any step. It accepts as a parameter the data to return to the workflow that executed this step.
1194
1195 #### Workflow Implementation
1196
1197 You'll now create the workflow that uses the `sendNotificationStep` to send the order confirmation email.
1198
1199 Create the file `src/workflows/send-order-confirmation.ts` with the following content:
1200
1201 export const workflowHighlights = [
1202 ["13", "sendOrderConfirmationWorkflow", "Create the workflow that sends an order confirmation email."],
1203 ["16", "useQueryGraphStep", "Retrieve the order's details."],
1204 ["48", "sendNotificationStep", "Send the order confirmation email."]
1205 ]
1206
1207 ```ts title="src/workflows/send-order-confirmation.ts" highlights={workflowHighlights}
1208 import {
1209 createWorkflow,
1210 when,
1211 WorkflowResponse,
1212 } from "@medusajs/framework/workflows-sdk"
1213 import { useQueryGraphStep } from "@medusajs/medusa/core-flows"
1214 import { sendNotificationStep } from "./steps/send-notification"
1215
1216 type WorkflowInput = {
1217 id: string
1218 }
1219
1220 export const sendOrderConfirmationWorkflow = createWorkflow(
1221 "send-order-confirmation",
1222 ({ id }: WorkflowInput) => {
1223 const { data: orders } = useQueryGraphStep({
1224 entity: "order",
1225 fields: [
1226 "id",
1227 "display_id",
1228 "email",
1229 "currency_code",
1230 "total",
1231 "items.*",
1232 "shipping_address.*",
1233 "billing_address.*",
1234 "shipping_methods.*",
1235 "customer.*",
1236 "total",
1237 "subtotal",
1238 "discount_total",
1239 "shipping_total",
1240 "tax_total",
1241 "item_subtotal",
1242 "item_total",
1243 "item_tax_total",
1244 ],
1245 filters: {
1246 id,
1247 },
1248 options: {
1249 throwIfKeyNotFound: true,
1250 },
1251 })
1252
1253 const notification = when({ orders }, (data) => !!data.orders[0].email)
1254 .then(() => {
1255 return sendNotificationStep([{
1256 to: orders[0].email!,
1257 channel: "email",
1258 template: "order-placed",
1259 data: {
1260 order: orders[0],
1261 },
1262 }])
1263 })
1264
1265 return new WorkflowResponse({
1266 notification,
1267 })
1268 }
1269 )
1270 ```
1271
1272 You create a workflow using `createWorkflow` from the Workflows SDK. It accepts the workflow's unique name as a first parameter.
1273
1274 It accepts as a second parameter a constructor function, which is the workflow's implementation. The workflow has the following steps:
1275
1276 1. `useQueryGraphStep`, which is a step implemented by Medusa that uses [Query](!docs!/learn/fundamentals/query), a tool that allows you to retrieve data across modules. You use it to retrieve the order's details.
1277 2. Ensure that the order has an email address by using `when-then`. If so, you send the notification using the `sendNotificationStep` you implemented earlier. You pass it an object with the following properties:
1278 - `to`: The address to send the email to. You pass the customer's email that is stored in the order.
1279 - `channel`: The channel to send the notification through, which is `email`. Since you specified `email` in the Resend Module Provider's `channel` option, the Notification Module will delegate the sending to the Resend Module Provider's service.
1280 - `template`: The email's template type. You retrieve the template content in the `ResendNotificationProviderService`'s `send` method based on the template specified here.
1281 - `data`: The data to pass to the email template, which is the order's details.
1282
1283 <Note title="Tip">
1284
1285 `when` allows you to perform steps based on a condition during execution. Learn more in the [Conditions in Workflows](!docs!/learn/fundamentals/workflows/conditions) documentation.
1286
1287 </Note>
1288
1289 You'll execute the workflow when you create the subscriber next.
1290
1291 #### Add the Order Placed Subscriber
1292
1293 Now that you have the workflow to send an order-confirmation email, you'll execute it in a subscriber that's executed whenever an order is placed.
1294
1295 You create a subscriber in a TypeScript or JavaScript file under the `src/subscribers` directory. So, create the file `src/subscribers/order-placed.ts` with the following content:
1296
1297 export const subscriberHighlights = [
1298 ["7", "orderPlacedHandler", "The subscriber function"],
1299 ["8", "data", "The event's data payload, which has the order's ID."],
1300 ["9", "container", "The Medusa container."],
1301 ["11", "sendOrderConfirmationWorkflow", "Execute the workflow to send an email."],
1302 ["13", "input", "The input to pass to the workflow."],
1303 ["14", "id", "The ID of the order."],
1304 ["19", "config", "The subscriber's configurations."],
1305 ["20", "event", "The event that the subscriber is listening to."]
1306 ]
1307
1308 ```ts title="src/subscribers/order-placed.ts" highlights={subscriberHighlights}
1309 import type {
1310 SubscriberArgs,
1311 SubscriberConfig,
1312 } from "@medusajs/framework"
1313 import { sendOrderConfirmationWorkflow } from "../workflows/send-order-confirmation"
1314
1315 export default async function orderPlacedHandler({
1316 event: { data },
1317 container,
1318 }: SubscriberArgs<{ id: string }>) {
1319 await sendOrderConfirmationWorkflow(container)
1320 .run({
1321 input: {
1322 id: data.id,
1323 },
1324 })
1325 }
1326
1327 export const config: SubscriberConfig = {
1328 event: "order.placed",
1329 }
1330 ```
1331
1332 A subscriber file exports:
1333
1334 - An asynchronous function that's executed whenever the associated event is emitted, which is the `order.placed` event.
1335 - A configuration object with an `event` property indicating the event the subscriber is listening to.
1336
1337 The subscriber function accepts the event's details as a first parameter which has a `data` property that holds the data payload of the event. For example, Medusa emits the `order.placed` event with the order's ID in the data payload. The function also accepts as a second parameter the [Medusa container](!docs!/learn/fundamentals/medusa-container).
1338
1339 In the function, you execute the `sendOrderConfirmationWorkflow` by invoking it, passing it the `container`, then using its `run` method. The `run` method accepts an object having an `input` property, which is the input to pass to the workflow. You pass the ID of the placed order as received in the event's data payload.
1340
1341 This subscriber now runs whenever an order is placed. You'll see this in action in the next section.
1342
1343 ---
1344
1345 ## Test it Out: Place an Order
1346
1347 To test out the Resend integration, you'll place an order using the [Next.js Starter Storefront](../../../nextjs-starter/page.mdx) that you installed as part of installing Medusa.
1348
1349 Start your Medusa application first:
1350
1351 ```bash npm2yarn
1352 npm run dev
1353 ```
1354
1355 Then, in the Next.js Starter Storefront's directory (`apps/storefront`), run the following command to start the storefront:
1356
1357 ```bash npm2yarn
1358 npm run dev
1359 ```
1360
1361 Then, open the storefront in your browser at `http://localhost:8000` and:
1362
1363 1. Go to Menu -> Store.
1364
1365 ![Choose Store from Menu](https://res.cloudinary.com/dza7lstvk/image/upload/v1732539139/Medusa%20Resources/Screenshot_2024-11-25_at_2.51.59_PM_fubiwj.png)
1366
1367 2\. Click on a product, select its options, and add it to the cart.
1368
1369 ![Choose an option, such as size, then click on the Add to cart button](https://res.cloudinary.com/dza7lstvk/image/upload/v1732539227/Medusa%20Resources/Screenshot_2024-11-25_at_2.53.11_PM_iswcjy.png)
1370
1371 3\. Click on Cart at the top right, then click Go to Cart.
1372
1373 ![Cart is at the top right. It opens a dropdown with a Go to Cart button](https://res.cloudinary.com/dza7lstvk/image/upload/v1732539354/Medusa%20Resources/Screenshot_2024-11-25_at_2.54.44_PM_b1pnlu.png)
1374
1375 4\. On the cart's page, click on the "Go to checkout" button.
1376
1377 ![The Go to checkout button is at the right side of the page](https://res.cloudinary.com/dza7lstvk/image/upload/v1732539443/Medusa%20Resources/Screenshot_2024-11-25_at_2.56.27_PM_cvqshj.png)
1378
1379 5\. On the checkout page, when entering the shipping address, make sure to set the email to your Resend account's email if you didn't set up a custom domain.
1380
1381 ![Enter your Resend account email if you didn't set up a custom domain](https://res.cloudinary.com/dza7lstvk/image/upload/v1732539536/Medusa%20Resources/Screenshot_2024-11-25_at_2.58.31_PM_wmlh60.png)
1382
1383 6\. After entering the shipping address, choose a delivery and payment methods, then click the Place Order button.
1384
1385 Once the order is placed, you'll find the following message logged in the Medusa application's terminal:
1386
1387 ```bash
1388 info: Processing order.placed which has 1 subscribers
1389 ```
1390
1391 This indicates that the `order.placed` event was emitted and its subscriber, which you added in the previous step, is executed.
1392
1393 If you check the inbox of the email address you specified in the shipping address, you'll find a new email with the order's details.
1394
1395 ![Example of order-confirmation email](https://res.cloudinary.com/dza7lstvk/image/upload/v1732551372/Medusa%20Resources/Screenshot_2024-11-25_at_6.15.59_PM_efyuoj.png)
1396
1397 ---
1398
1399 ## Next Steps
1400
1401 You've now integrated Medusa with Resend. You can add more templates for other emails, such as customer registration confirmation, user invites, and more. Check out the [Events Reference](/references/events) for a list of all events that the Medusa application emits.
1402
1403 ### More Resend Email Templates
1404
1405 Find more email templates to use with the Resend Module Provider in the following guides:
1406
1407 - [Send Invite User Email](../../../commerce-modules/user/invite-user-subscriber/page.mdx).
1408 - [Send Reset Password Email](../../../commerce-modules/auth/reset-password/page.mdx).
1409
1410 ### Learn More About Medusa
1411
1412 If you're new to Medusa, check out the [main documentation](!docs!/learn), where you'll get a more in-depth learning of all the concepts you've used in this guide and more.
1413
1414 To learn more about the commerce features that Medusa provides, check out Medusa's [Commerce Modules](../../../commerce-modules/page.mdx).