Raw
1 ---
2 sidebar_label: "Integrate Mailchimp"
3 tags:
4 - server
5 - tutorial
6 - notification
7 products:
8 - product
9 ---
10
11 import { Card, Prerequisites, Details, WorkflowDiagram } from "docs-ui"
12 import { Github, PlaySolid } from "@medusajs/icons"
13
14 export const metadata = {
15 title: `Add Newsletter Subscriptions with Mailchimp in Medusa`,
16 }
17
18 # {metadata.title}
19
20 In this tutorial, you'll learn how to integrate Mailchimp with Medusa to manage newsletter subscribers and automate newsletters.
21
22 When you install a Medusa application, you get a fully-fledged commerce platform with a Framework for customization. Medusa's architecture facilitates integrating third-party services to customize Medusa's infrastructure for your business needs.
23
24 Medusa's [Notification Module](../../../infrastructure-modules/notification/page.mdx) allows you to customize Medusa's infrastructure to send notifications using the third-party provider that fits your business needs, such as [Mailchimp](https://mailchimp.com/).
25
26 In this tutorial, you'll integrate Mailchimp with Medusa to allow customers to subscribe to your newsletter and automate sending newsletters.
27
28 ## Summary
29
30 By following this tutorial, you'll learn how to:
31
32 - Install and set up Medusa.
33 - Integrate Mailchimp with Medusa.
34 - Allow customers to subscribe to your store's newsletter.
35 - Automate sending newsletters about new products to subscribed customers.
36
37 You can follow this tutorial whether you're new to Medusa or an advanced Medusa developer.
38
39 ![Diagram showcasing the flow of the Mailchimp integration with Medusa](https://res.cloudinary.com/dza7lstvk/image/upload/v1750679344/Medusa%20Resources/mailchimp-overview_itmiul.jpg)
40
41 <Card
42 title="Example Repository"
43 text="Find the full code of the guide in this repository."
44 href="https://github.com/medusajs/examples/tree/main/mailchimp-integration"
45 icon={Github}
46 />
47
48 ---
49
50 ## Step 1: Install a Medusa Application
51
52 <Prerequisites items={[
53 {
54 text: "Node.js v20.19.0+ or v22.12.0+",
55 link: "https://nodejs.org/en/download"
56 },
57 {
58 text: "Git CLI tool",
59 link: "https://git-scm.com/downloads"
60 },
61 {
62 text: "PostgreSQL",
63 link: "https://www.postgresql.org/download/"
64 }
65 ]} />
66
67 Start by installing the Medusa application on your machine with the following command:
68
69 ```bash
70 npx create-medusa-app@latest
71 ```
72
73 First, you'll be asked for the project's name. Then, when prompted about installing the [Next.js Starter Storefront](../../../nextjs-starter/page.mdx), choose "Yes."
74
75 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.
76
77 Once the installation finishes successfully, the Medusa Admin dashboard will open with a form to create a new user. Enter the user's credentials and submit the form. Afterwards, you can log in with the new user and explore the dashboard.
78
79 <Note title="Ran into Errors?">
80
81 Check out the [troubleshooting guides](../../../troubleshooting/create-medusa-app-errors/page.mdx) for help.
82
83 </Note>
84
85 <Note>
86
87 In this guide, all file paths of backend customizations are relative to the `apps/backend` directory of your Medusa project.
88
89 </Note>
90
91 ---
92
93 ## Step 2: Create Mailchimp Module Provider
94
95 To integrate third-party services into Medusa, you create a custom [module](!docs!/learn/fundamentals/modules). A module is a reusable package with functionalities related to a single feature or domain.
96
97 Medusa's [Notification Module](../../../infrastructure-modules/notification/page.mdx) provides an interface to send notifications in your Medusa application. It delegates the actual sending of notifications to the underlying provider, such as Mailchimp.
98
99 In this step, you'll integrate Mailchimp as a Notification Module Provider. Later, you'll use it to handle newsletter subscriptions and send newsletters.
100
101 <Note>
102
103 Refer to the [Modules](!docs!/learn/fundamentals/modules) documentation to learn more about modules in Medusa.
104
105 </Note>
106
107 ### a. Install Mailchimp Marketing API SDK
108
109 To interact with Mailchimp's APIs, you'll use their official Node.js SDK.
110
111 Run the following command to install the SDK with its types package in your Medusa application:
112
113 ```bash npm2yarn
114 npm install @mailchimp/mailchimp_marketing
115 npm install @types/mailchimp__mailchimp_marketing --save-dev
116 ```
117
118 ### b. Create Module Directory
119
120 A module is created under the `src/modules` directory of your Medusa application. So, create the directory `src/modules/mailchimp`.
121
122 ### c. Create Mailchimp Module's Service
123
124 A module has a service that contains its logic. For Notification Module Providers, the service implements the logic to send notifications with a third-party service.
125
126 To create the service of the Mailchimp Notification Module Provider, create the file `src/modules/mailchimp/service.ts` with the following content:
127
128 export const serviceHighlights = [
129 ["6", "Options", "The options required for Mailchimp integration."],
130 ["22", "identifier", "The unique identifier for the module provider."],
131 ]
132
133 ```ts title="src/modules/mailchimp/service.ts" highlights={serviceHighlights}
134 import {
135 AbstractNotificationProviderService,
136 } from "@medusajs/framework/utils"
137 import mailchimpMarketingApi from "@mailchimp/mailchimp_marketing"
138
139 type Options = {
140 apiKey: string
141 server: string
142 listId: string
143 templates?: {
144 new_products?: {
145 subject_line?: string
146 storefront_url?: string
147 }
148 }
149 }
150
151 type InjectedDependencies = {
152 }
153
154 class MailchimpNotificationProviderService extends AbstractNotificationProviderService {
155 static identifier = "mailchimp"
156 protected options: Options
157 protected mailchimp: typeof mailchimpMarketingApi
158
159 constructor(container: InjectedDependencies, options: Options) {
160 super()
161 this.options = options
162 this.mailchimp = mailchimpMarketingApi
163 this.mailchimp.setConfig({
164 apiKey: options.apiKey,
165 server: options.server,
166 })
167 }
168 }
169
170 export default MailchimpNotificationProviderService
171 ```
172
173 A Notification Module Provider's service must extend the `AbstractNotificationProviderService` class. You'll implement its methods in the next sections.
174
175 The service must also have an `identifier` static property, which is a unique identifier for the module. This identifier is used when registering the module in the Medusa application.
176
177 The service's constructor receives two parameters:
178
179 - `container`: The [module's container](!docs!/learn/fundamentals/modules/container) that contains Framework resources available to the module. You don't need to use it for this tutorial.
180 - `options`: Options that are passed to the module provider when it's registered in Medusa's configurations. You define the following options:
181 - `apiKey`: The Mailchimp API key.
182 - `server`: The Mailchimp server prefix. For example, `us10`.
183 - `listId`: The ID of the Mailchimp audience list where subscribed customers will be added.
184 - `templates`: Optional template configurations for newsletters.
185
186 <Note title="Tip">
187
188 You'll learn how to set these options in the [Add Module Provider to Medusa's Configurations](#g-add-module-provider-to-medusas-configurations) section.
189
190 </Note>
191
192 In the constructor, you set the `options` property and initialize the Mailchimp SDK with your API key and server.
193
194 In the next sections, you'll implement the methods of the `MailchimpNotificationProviderService` class.
195
196 ### d. Implement validateOptions Method
197
198 The `validateOptions` method is used to validate the options passed to the module provider. If the method throws an error, the Medusa application won't start.
199
200 Add the `validateOptions` method to the `MailchimpNotificationProviderService` class:
201
202 ```ts title="src/modules/mailchimp/service.ts"
203 // other imports...
204 import {
205 MedusaError,
206 } from "@medusajs/framework/utils"
207
208 class MailchimpNotificationProviderService extends AbstractNotificationProviderService {
209 // ...
210 static validateOptions(options: Record<any, any>): void | never {
211 if (!options.apiKey) {
212 throw new MedusaError(
213 MedusaError.Types.INVALID_ARGUMENT,
214 "API key is required"
215 )
216 }
217 if (!options.server) {
218 throw new MedusaError(
219 MedusaError.Types.INVALID_ARGUMENT,
220 "Server is required"
221 )
222 }
223 if (!options.listId) {
224 throw new MedusaError(
225 MedusaError.Types.INVALID_ARGUMENT,
226 "List ID is required"
227 )
228 }
229 }
230 }
231 ```
232
233 The `validateOptions` method receives the options passed to the module provider as a parameter.
234
235 In the method, you throw an error if the required options are not set.
236
237 ### e. Implement send Method
238
239 When the Medusa application needs to send a notification through a channel (such as `email`), it calls the `send` method of the channel's module provider.
240
241 The `send` method can be used to send different types of notifications based on the template specified. So, you'll implement the helper methods that handle the different notification templates, then use them in the `send` method.
242
243 #### sendNewsletterSignup Method
244
245 The `sendNewsletterSignup` method adds an email to the Mailchimp audience list. You'll use this method when a customer subscribes to the newsletter.
246
247 Add the `sendNewsletterSignup` method to the `MailchimpNotificationProviderService` class:
248
249 ```ts title="src/modules/mailchimp/service.ts"
250 // other imports...
251 import {
252 ProviderSendNotificationResultsDTO,
253 ProviderSendNotificationDTO,
254 } from "@medusajs/framework/types"
255
256 class MailchimpNotificationProviderService extends AbstractNotificationProviderService {
257 // ...
258 async sendNewsletterSignup(
259 notification: ProviderSendNotificationDTO
260 ): Promise<ProviderSendNotificationResultsDTO> {
261 const { to, data } = notification
262
263 try {
264 const response = await this.mailchimp.lists.addListMember(
265 this.options.listId, {
266 email_address: to,
267 status: "subscribed",
268 merge_fields: {
269 FNAME: data?.first_name,
270 LNAME: data?.last_name,
271 },
272 }
273 )
274
275 return {
276 id: "id" in response ? response.id : "",
277 }
278 } catch (error) {
279 throw new MedusaError(
280 MedusaError.Types.UNEXPECTED_STATE,
281 `Failed to send newsletter signup: ${error.response.text}`
282 )
283 }
284 }
285 }
286 ```
287
288 This method receives the same parameter as the `send` method, which is an object containing the notification details including:
289
290 - `to`: The email address to add to the Mailchimp audience list.
291 - `data`: An object containing additional data, such as the user's first and last name.
292
293 <Note>
294
295 Learn about other properties in the object in the [Create Notification Module Provider](/references/notification-provider-module#send) guide.
296
297 </Note>
298
299 In the method, you use the `mailchimp.lists.addListMember` method to subscribe an email address to the Mailchimp audience list. You pass the `listId` from the module's options and the email address along with optional first and last names.
300
301 If the subscription is successful, the method returns an object with the `id` of the subscribed email. If it fails, it throws a `MedusaError` with the error message from Mailchimp.
302
303 You don't do any email sending in this method because later, in the [Send Welcome Emails from Mailchimp](#optional-step-send-welcome-emails-from-mailchimp) section, you'll create an automation flow in Mailchimp that automatically sends a welcome email to new subscribers.
304
305 #### getNewProductsHtmlContent Method
306
307 The `getNewProductsHtmlContent` method will generate the HTML content for the "New Products" newsletter. You'll then use this method when sending the new products newsletter.
308
309 Add the `getNewProductsHtmlContent` method to the `MailchimpNotificationProviderService` class:
310
311 ```ts title="src/modules/mailchimp/service.ts"
312 class MailchimpNotificationProviderService extends AbstractNotificationProviderService {
313 // ...
314 private async getNewProductsHtmlContent(data: any): Promise<string> {
315 return `
316 <!DOCTYPE html>
317 <html xmlns:mc="http://schemas.mailchimp.com/2006/hcm">
318 <head>
319 <meta charset="UTF-8">
320 <title>${this.options.templates?.new_products?.subject_line}</title>
321 <style>
322 body {
323 font-family: Arial, sans-serif;
324 background-color: #f4f4f4;
325 margin: 0;
326 padding: 0;
327 }
328 .container {
329 max-width: 600px;
330 background: #ffffff;
331 margin: 0 auto;
332 padding: 20px;
333 }
334 .product {
335 border-bottom: 1px solid #ddd;
336 padding: 20px 0;
337 display: flex;
338 }
339 .product img {
340 max-width: 120px;
341 margin-right: 20px;
342 }
343 .product-info {
344 flex: 1;
345 }
346 .product-info h4 {
347 margin: 0 0 10px;
348 font-size: 18px;
349 }
350 .product-info p {
351 margin: 0 0 5px;
352 color: #555;
353 }
354 .cta-button {
355 display: inline-block;
356 margin-top: 10px;
357 background-color: #007BFF;
358 color: #ffffff;
359 text-decoration: none;
360 padding: 10px 15px;
361 border-radius: 4px;
362 font-size: 14px;
363 }
364 </style>
365 </head>
366 <body>
367 <div class="container">
368 <h2 style="text-align:center;">Check out our latest products</h2>
369
370 <!-- Repeatable product block -->
371 <table role="presentation" width="100%" cellspacing="0" cellpadding="0" border="0" mc:repeatable="product_block" mc:variant="Product Item">
372 <tbody>
373 ${data.products.map((product: any) => `
374 <tr>
375 <td class="product">
376 <img mc:edit="product_image" src="${product.thumbnail}" alt="Product Image">
377 <div class="product-info">
378 <h4 mc:edit="product_title">${product.title}</h4>
379 <p mc:edit="product_description">${product.description}</p>
380 <a mc:edit="product_link" href="${this.options.templates?.new_products?.storefront_url}/products/${product.handle}" class="cta-button">View Product</a>
381 </div>
382 </td>
383 </tr>
384 `).join("")}
385 </tbody>
386 </table>
387
388 </div>
389 </body>
390 </html>
391 `
392 }
393 }
394 ```
395
396 This method receives the product data as a parameter and returns a string containing the HTML content for the newsletter. You show the products in a responsive layout with images, titles, descriptions, and a button to view the product.
397
398 Notice that the HTML template uses the `template.new_products.storefront_url` module option to generate the product links. This allows you to customize the storefront URL in the module's options.
399
400 <Note title="Tip">
401
402 Feel free to modify the HTML template to match your design preferences or add more product details. You can also define a template in Mailchimp and use its ID in the next method instead of generating the HTML content dynamically.
403
404 </Note>
405
406 #### sendNewProducts Method
407
408 The last helper method you'll add is `sendNewProducts`. This method will create and send a campaign in Mailchimp that showcases new products.
409
410 Add the `sendNewProducts` method to the `MailchimpNotificationProviderService` class:
411
412 export const sendNewProductsHighlights = [
413 ["9", "list", "Retrieve the list settings."],
414 ["19", "campaign", "Create a new campaign with the list ID and settings."],
415 ["33", "setContent", "Set the campaign content using the `getNewProductsHtmlContent` method."],
416 ["38", "send", "Send the campaign to the subscribers."],
417 ]
418
419 ```ts title="src/modules/mailchimp/service.ts" highlights={sendNewProductsHighlights}
420 class MailchimpNotificationProviderService extends AbstractNotificationProviderService {
421 // ...
422 async sendNewProducts(
423 notification: ProviderSendNotificationDTO
424 ): Promise<ProviderSendNotificationResultsDTO> {
425 const { data } = notification
426
427 try {
428 const list = await fetch(
429 `https://${this.options.server}.api.mailchimp.com/3.0/lists/${this.options.listId}`,
430 {
431 headers: {
432 Authorization: `Bearer ${this.options.apiKey}`,
433 },
434 }
435 ).then((res) => res.json()) as mailchimpMarketingApi.lists.List
436
437 // create a campaign
438 const campaign = await this.mailchimp.campaigns.create({
439 type: "regular",
440 recipients: {
441 list_id: this.options.listId,
442 },
443 settings: {
444 subject_line:
445 this.options.templates?.new_products?.subject_line || "New Products",
446 from_name: list.campaign_defaults?.from_name,
447 reply_to: list.campaign_defaults?.from_email,
448 },
449 }) as mailchimpMarketingApi.campaigns.Campaigns
450
451 // set content
452 await this.mailchimp.campaigns.setContent(campaign.id, {
453 html: await this.getNewProductsHtmlContent(data),
454 })
455
456 // send campaign
457 await this.mailchimp.campaigns.send(campaign.id)
458
459 return {
460 id: campaign.id,
461 }
462 } catch (error) {
463 throw new MedusaError(
464 MedusaError.Types.UNEXPECTED_STATE,
465 `Failed to send new products newsletter: ${
466 error.response?.text || error
467 }`
468 )
469 }
470 }
471 }
472 ```
473
474 This method receives the same parameter as the `send` method, which is an object containing the notification details.
475
476 <Note>
477
478 Learn about the object's properties in the [Create Notification Module Provider](/references/notification-provider-module#send) guide.
479
480 </Note>
481
482 In the method, you:
483
484 1. Fetch the Mailchimp list details to get default sender information. You use the `fetch` API because the Mailchimp SDK does not provide a method to fetch list details.
485 2. Create a new campaign in Mailchimp using the `mailchimp.campaigns.create` method. You specify the list ID to ensure the subscribers of that list receive the campaign. You also set the subject line and sender information using the list's default settings.
486 3. Set the campaign content using the HTML returned by the `getNewProductsHtmlContent` method.
487 4. Send the campaign using the `mailchimp.campaigns.send` method.
488 5. Return the campaign ID if successful.
489
490 You also throw a `MedusaError` if the method fails at any point, providing the error message from Mailchimp.
491
492 #### Implement send Method
493
494 You can now implement the required `send` method of the `MailchimpNotificationProviderService` class that sends a notification based on the template provided.
495
496 Add the `send` method to the `MailchimpNotificationProviderService` class:
497
498 ```ts title="src/modules/mailchimp/service.ts"
499 class MailchimpNotificationProviderService extends AbstractNotificationProviderService {
500 // ...
501 async send(
502 notification: ProviderSendNotificationDTO
503 ): Promise<ProviderSendNotificationResultsDTO> {
504 const { template } = notification
505
506 switch (template) {
507 case "newsletter-signup":
508 return this.sendNewsletterSignup(notification)
509 case "new-products":
510 return this.sendNewProducts(notification)
511 default:
512 throw new MedusaError(
513 MedusaError.Types.INVALID_ARGUMENT,
514 "Invalid template"
515 )
516 }
517 }
518 }
519 ```
520
521 This method receives an object of notification details, including the `template` property that specifies which template to use for sending the notification.
522
523 <Note>
524
525 Learn about other properties in the object in the [Create Notification Module Provider](/references/notification-provider-module#send) guide.
526
527 </Note>
528
529 In the method, you perform an action based on the `template` value:
530
531 - If the template is `newsletter-signup`, you call the `sendNewsletterSignup` method to add a new subscriber to the Mailchimp audience list.
532 - If the template is `new-products`, you call the `sendNewProducts` method to create and send a campaign showcasing new products.
533 - If the template is not recognized, you throw a `MedusaError` indicating that the template is invalid.
534
535 ### f. Export Module Definition
536
537 You've now finished implementing the necessary methods for the Mailchimp Notification Module Provider.
538
539 The final piece to a module is its definition, which you export in an `index.ts` file at the module's root directory. This definition tells Medusa the module's details, including its service.
540
541 To create the module's definition, create the file `src/modules/mailchimp/index.ts` with the following content:
542
543 ```ts title="src/modules/mailchimp/index.ts"
544 import MailchimpNotificationProviderService from "./service"
545 import {
546 ModuleProvider,
547 Modules,
548 } from "@medusajs/framework/utils"
549
550 export default ModuleProvider(Modules.NOTIFICATION, {
551 services: [MailchimpNotificationProviderService],
552 })
553 ```
554
555 You use `ModuleProvider` from the Modules SDK to create the module provider's definition. It accepts two parameters:
556
557 1. The name of the module that this provider belongs to, which is `Modules.NOTIFICATION` in this case.
558 2. An object with a required property `services` indicating the Module Provider's services.
559
560 ### g. Add Module Provider to Medusa's Configurations
561
562 Once you finish building the module, add it to Medusa's configurations to start using it.
563
564 In `medusa-config.ts`, add a `modules` property to the configurations:
565
566 export const configurationsHighlight = [
567 ["13", "apiKey", "Mailchimp API key."],
568 ["14", "server", "Mailchimp server prefix."],
569 ["15", "listId", "Mailchimp audience list ID."],
570 ["16", "templates", "Optional template settings for newsletters."],
571 ]
572
573 ```ts title="medusa-config.ts" highlights={configurationsHighlight}
574 module.exports = defineConfig({
575 // ...
576 modules: [
577 {
578 resolve: "@medusajs/medusa/notification",
579 options: {
580 providers: [
581 {
582 resolve: "./src/modules/mailchimp",
583 id: "mailchimp",
584 options: {
585 channels: ["email"],
586 apiKey: process.env.MAILCHIMP_API_KEY!,
587 server: process.env.MAILCHIMP_SERVER!,
588 listId: process.env.MAILCHIMP_LIST_ID!,
589 templates: {
590 new_products: {
591 subject_line: process.env.MAILCHIMP_NEW_PRODUCTS_SUBJECT_LINE!,
592 storefront_url: process.env.MAILCHIMP_NEW_PRODUCTS_STOREFRONT_URL!,
593 },
594 },
595 },
596 },
597 ],
598 },
599 },
600 ],
601 })
602 ```
603
604 To pass a Module Provider to the Notification Module, you add the `modules` property to the Medusa configuration and pass the Notification Module in its value.
605
606 The Notification Module accepts a `providers` option, which is an array of Notification Module Providers to register.
607
608 To register the Mailchimp Notification Module Provider, you add an object to the `providers` array with the following properties:
609
610 - `resolve`: The NPM package or path to the module provider. In this case, it's the path to the `src/modules/mailchimp` directory.
611 - `id`: The ID of the module provider. The Notification Module Provider is then registered with the ID `np_{identifier}_{id}`, where:
612 - `{identifier}`: The identifier static property defined in the Module Provider's service, which is `mailchimp` in this case.
613 - `{id}`: The ID set in this configuration, which is also `mailchimp` in this case.
614 - `options`: The options to pass to the module provider. These are the options you defined in the `Options` type of the module provider's service.
615 - You must also set a `channels` option that indicates the channels this provider is used to send notifications.
616
617 ### h. Set Environment Variables
618
619 Next, you'll set the options you passed to the Mailchimp Notification Module Provider as environment variables.
620
621 #### Retrieve Mailchimp API Key
622
623 To retrieve your Mailchimp API key:
624
625 1. On the Mailchimp dashboard, click on your profile icon at the top right.
626 2. Choose "Account & billing" from the dropdown.
627
628 ![Mailchimp dashboard with the profile menu opened](https://res.cloudinary.com/dza7lstvk/image/upload/v1750682692/Medusa%20Resources/CleanShot_2025-06-23_at_11.46.07_2x_xo5a5l.png)
629
630 3. Click on the "Extras" tab and select "API keys" from the dropdown.
631
632 ![Mailchimp account page with the Extras dropdown opened](https://res.cloudinary.com/dza7lstvk/image/upload/v1750682741/Medusa%20Resources/CleanShot_2025-06-23_at_11.48.12_2x_l86ein.png)
633
634 4. Scroll down to the "Your API keys" section and click on the "Create A Key" button.
635
636 ![Mailchimp API keys page with the Create A Key button highlighted](https://res.cloudinary.com/dza7lstvk/image/upload/v1750682771/Medusa%20Resources/CleanShot_2025-06-23_at_11.48.53_2x_vf3ftl.png)
637
638 5. In the API key form, enter a name for the API key.
639 6. Click the "Generate Key" button to create the API key.
640
641 ![Mailchimp API key creation form with a name field](https://res.cloudinary.com/dza7lstvk/image/upload/v1750682817/Medusa%20Resources/CleanShot_2025-06-23_at_11.49.12_2x_xwwmi6.png)
642
643 Copy the generated API key and add it to the `.env` file in your Medusa application:
644
645 ```shell
646 MAILCHIMP_API_KEY=123...
647 ```
648
649 #### Retrieve Mailchimp Server Prefix
650
651 You can retrieve your Mailchimp server prefix from the URL of your Mailchimp dashboard. It should be in the format `https://<server-prefix>.admin.mailchimp.com/`. So, the server prefix will be something like `us5`, for example.
652
653 Then, add the server prefix to the `.env` file in your Medusa application:
654
655 ```shell
656 MAILCHIMP_SERVER=us5
657 ```
658
659 #### Create Mailchimp Audience List
660
661 Next, you'll create a Mailchimp audience list to store your subscribers:
662
663 1. On the Mailchimp dashboard, click on "Audience" in the left sidebar.
664 2. Click on the dropdown next to the "Contacts" header and choose "Manage Audiences".
665
666 ![Mailchimp audience management page with the Manage Audiences option highlighted](https://res.cloudinary.com/dza7lstvk/image/upload/v1750683058/Medusa%20Resources/CleanShot_2025-06-23_at_11.50.54_2x_ayyyuq.png)
667
668 3. Click on the "Create Audience" button at the top right.
669
670 ![Mailchimp audience creation page with the Create Audience button highlighted](https://res.cloudinary.com/dza7lstvk/image/upload/v1750683095/Medusa%20Resources/CleanShot_2025-06-23_at_11.51.51_2x_d0nxvc.png)
671
672 4. Enter the audience details, such as the audience name, default from email address, and default from name. These defaults are used in the created campaigns.
673
674 ![Mailchimp audience creation form with fields for audience name, default from email address, and default from name](https://res.cloudinary.com/dza7lstvk/image/upload/v1750683517/Medusa%20Resources/CleanShot_2025-06-23_at_11.54.25_2x_ihgiyt.png)
675
676 5. Once you're done, click the "Save" button to create the audience. This will open the Audience's contacts page.
677 6. Click on the "More options" button and select "Audience settings" from the dropdown.
678
679 ![Mailchimp audience contacts page with the More options button highlighted](https://res.cloudinary.com/dza7lstvk/image/upload/v1750683642/Medusa%20Resources/CleanShot_2025-06-23_at_16.00.19_2x_zjetg6.png)
680
681 7. In the Audience settings page, copy the value of "Audience ID" from the first section.
682
683 ![Mailchimp audience settings page with the Audience ID highlighted](https://res.cloudinary.com/dza7lstvk/image/upload/v1750683763/Medusa%20Resources/CleanShot_2025-06-23_at_16.01.51_2x_a8grlw.png)
684
685 Add the copied ID to the `.env` file in your Medusa application as the list ID:
686
687 ```shell
688 MAILCHIMP_LIST_ID=123...
689 ```
690
691 #### Set Mailchimp Templates Options
692
693 Finally, you can optionally set the Mailchimp templates options in the `.env` file. These options are used when sending newsletters about new products.
694
695 ```shell
696 MAILCHIMP_NEW_PRODUCTS_SUBJECT_LINE="Check out our new products!"
697 MAILCHIMP_NEW_PRODUCTS_STOREFRONT_URL=https://localhost:8000
698 ```
699
700 Where:
701
702 - `MAILCHIMP_NEW_PRODUCTS_SUBJECT_LINE`: The subject line for the new products newsletter.
703 - `MAILCHIMP_NEW_PRODUCTS_STOREFRONT_URL`: The URL of your storefront where users can view the new products. In development, the Next.js Starter Storefront runs on `http://localhost:8000`, so you can set it to that URL.
704
705 The Mailchimp integration is now ready. You'll test it out as you implement the subscription features in the next steps.
706
707 ---
708
709 ## Optional Step: Send Welcome Emails from Mailchimp
710
711 In the Mailchimp Notification Module Provider, you handle the `newsletter-signup` notification template by subscribing an email address to the Mailchimp audience list. However, you typically should also send a welcome email to the subscribed customer.
712
713 To do that, you can create an automation flow in Mailchimp that automatically sends emails whenever a new subscriber is added to the audience list.
714
715 To do that:
716
717 1. On the Mailchimp dashboard, click on "Automations" in the sidebar.
718 2. Click on the "Build from scratch" button to create a new automation flow.
719
720 ![Mailchimp automations page with the Build from scratch button highlighted](https://res.cloudinary.com/dza7lstvk/image/upload/v1750684308/Medusa%20Resources/CleanShot_2025-06-23_at_12.18.15_2x_ymj8ar.png)
721
722 3. In the flow creation form, enter a name for the automation flow and choose the Audience you created earlier.
723 4. Click the "Choose a starting point" button to select a template for the automation flow.
724
725 ![Mailchimp automation flow creation form with fields for flow name and audience selection](https://res.cloudinary.com/dza7lstvk/image/upload/v1750684445/Medusa%20Resources/CleanShot_2025-06-23_at_12.19.17_2x_yso5wu.png)
726
727 5. A pop-up will open in the flow editor to choose a template to start from. Choose the "Signs up for Email" template.
728
729 ![Mailchimp automation flow editor with the Signs up for Email template highlighted](https://res.cloudinary.com/dza7lstvk/image/upload/v1750685997/Medusa%20Resources/CleanShot_2025-06-23_at_12.19.32_2x_x14tcv.png)
730
731 6. In the flow editor, drag the "Send Email" action to the flow canvas. This will open a pop-up to configure the email.
732 7. In the email configuration pop-up, you can enter the email subject, from name, and from email address.
733
734 ![Mailchimp automation flow editor with the Send Email action highlighted](https://res.cloudinary.com/dza7lstvk/image/upload/v1750686062/Medusa%20Resources/CleanShot_2025-06-23_at_12.20.56_2x_iksdox.png)
735
736 8. To set the email content, click the "Select a template" link in the email configuration pop-up. You can then choose an existing template or paste your own HTML content.
737
738 <Details summaryContent="Example HTML Content" className="mb-1">
739
740 ```html
741 <!DOCTYPE html>
742 <html xmlns:mc="http://schemas.mailchimp.com/2006/hcm">
743 <head>
744 <meta charset="UTF-8">
745 <title>Thanks for signing up!</title>
746 <style type="text/css">
747 body {
748 background-color: #f5f5f5;
749 font-family: Arial, sans-serif;
750 margin: 0;
751 padding: 0;
752 }
753 .email-container {
754 max-width: 600px;
755 margin: 40px auto;
756 background-color: #ffffff;
757 padding: 30px;
758 border-radius: 8px;
759 box-shadow: 0 0 5px rgba(0,0,0,0.1);
760 }
761 h1 {
762 color: #333;
763 font-size: 24px;
764 margin-bottom: 20px;
765 }
766 p {
767 color: #555;
768 line-height: 1.6;
769 }
770 .cta-button {
771 display: inline-block;
772 margin-top: 20px;
773 padding: 12px 24px;
774 background-color: #007BFF;
775 color: #ffffff;
776 text-decoration: none;
777 border-radius: 5px;
778 font-weight: bold;
779 }
780 .footer {
781 text-align: center;
782 font-size: 12px;
783 color: #999;
784 margin-top: 30px;
785 }
786 </style>
787 </head>
788 <body>
789 <div class="email-container">
790 <h1 mc:edit="welcome_heading">Thank you for signing up to the Medusa newsletter 🎉</h1>
791 <p mc:edit="welcome_text">
792 Hi there,<br><br>
793 Thanks for signing up! Get ready for exciting product updates and special offers sent right to your inbox.
794 </p>
795
796 <a href="http://localhost:8000" class="cta-button" mc:edit="cta_button">Start Exploring</a>
797
798 <div class="footer" mc:edit="footer_text">
799 You’re receiving this email because you signed up for updates from Medusa.<br>
800 Want to unsubscribe? <a href="*|UNSUB|*">Click here</a>.
801 </div>
802 </div>
803 </body>
804 </html>
805 ```
806
807 </Details>
808
809 9. Once you're done, close the email configuration pop-up. The changes will be saved automatically.
810 10. In the flow editor, click the "Continue" button at the top right.
811
812 ![Mailchimp automation flow editor with the Continue button highlighted](https://res.cloudinary.com/dza7lstvk/image/upload/v1750686278/Medusa%20Resources/CleanShot_2025-06-23_at_12.24.15_2x_v1mcas.png)
813
814 11. In the review pop-up, click the "Turn flow on" button to activate the automation flow.
815
816 ![Mailchimp automation flow review pop-up with the Turn flow on button highlighted](https://res.cloudinary.com/dza7lstvk/image/upload/v1750686313/Medusa%20Resources/CleanShot_2025-06-23_at_12.24.36_2x_wji8xx.png)
817
818 Whenever a customer subscribes to the newsletter, Mailchimp will automatically send them a welcome email using the automation flow you created.
819
820 ---
821
822 ## Step 3: Create Newsletter Subscription API Route
823
824 Now that you've integrated Mailchimp with Medusa, you need to allow customers to subscribe to the newsletter.
825
826 In this step, you will:
827
828 - Create an [API route](!docs!/learn/fundamentals/api-routes) to subscribe customers. An API Route is an endpoint that exposes commerce features to external applications and clients, such as storefronts.
829 - In the API route, you'll emit an event indicating that the customer is signing up for the newsletter.
830 - Create a [subscriber](!docs!/learn/fundamentals/events-and-subscribers) that listens to the event emitted by the API route. The subscriber will use Mailchimp to subscribe the customer to the newsletter audience list.
831
832 ### a. Create the API Route
833
834 An API route is created in a `route.ts` file under a sub-directory of the `src/api` directory. The path of the API route is the file's path relative to `src/api`.
835
836 So, to create an API route at the path `/store/newsletter`, create the file `src/api/store/newsletter/route.ts` with the following content:
837
838 export const apiRouteHighlights = [
839 ["5", "newsletterSignupSchema", "Zod schema to validate the request body."],
840 ["11", "POST", "POST route handler function for the API route."],
841 ["15", "eventModuleService", "Resolve the Event Module service from the Medusa container."],
842 ["19", "emit", "Emit the newsletter.signup event with the request body data."],
843 ]
844
845 <Note>
846
847 As of [Medusa v2.13.0](https://github.com/medusajs/medusa/releases/tag/v2.13.0), Zod should be imported from `@medusajs/framework/zod`.
848
849 </Note>
850
851 ```ts title="src/api/store/newsletter/route.ts" highlights={apiRouteHighlights}
852 import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http"
853 import { z } from "@medusajs/framework/zod"
854 import { Modules } from "@medusajs/framework/utils"
855
856 export const newsletterSignupSchema = z.object({
857 email: z.email(),
858 first_name: z.string().optional(),
859 last_name: z.string().optional(),
860 })
861
862 export async function POST(
863 req: MedusaRequest<z.infer<typeof newsletterSignupSchema>>,
864 res: MedusaResponse
865 ) {
866 const eventModuleService = req.scope.resolve(
867 Modules.EVENT_BUS
868 )
869
870 await eventModuleService.emit({
871 name: "newsletter.signup",
872 data: {
873 email: req.validatedBody.email,
874 first_name: req.validatedBody.first_name,
875 last_name: req.validatedBody.last_name,
876 },
877 })
878
879 res.json({
880 success: true,
881 })
882 }
883 ```
884
885 You first export a [Zod](https://zod.dev/) schema object that you'll use to validate incoming request bodies. You expect the request body to have an `email` field, and optionally allow passing `first_name` and `last_name` fields.
886
887 Then, you export a `POST` route handler function. This will expose a `POST` API route at `/store/newsletter`. The route handler function accepts two parameters:
888
889 1. A request object with details and context on the request, such as body parameters.
890 2. A response object to manipulate and send the response.
891
892 In the route handler, you use the [Medusa container](!docs!/learn/fundamentals/medusa-container) to resolve the [Event Module](../../../infrastructure-modules/event/page.mdx)'s service.
893
894 Then, you emit the `newsletter.signup` event, passing as the event payload the email, first name, and last name from the request body.
895
896 Finally, you send a JSON response indicating that the request was successful.
897
898 ### b. Add Validation Middleware
899
900 To validate that requests sent to the `/store/newsletter` API route have the required body parameters, you'll add a validation [middleware](!docs!/learn/fundamentals/api-routes/middlewares). A middleware is a function that is executed before an API route's handler when a request is made to the route.
901
902 To apply the validation middleware on the `/store/newsletter` API route, create the file `src/api/middlewares.ts` with the following content:
903
904 ```ts title="src/api/middlewares.ts"
905 import {
906 defineMiddlewares,
907 validateAndTransformBody,
908 } from "@medusajs/framework/http"
909 import { newsletterSignupSchema } from "./store/newsletter/route"
910
911 export default defineMiddlewares({
912 routes: [
913 {
914 matcher: "/store/newsletter",
915 methods: ["POST"],
916 middlewares: [
917 validateAndTransformBody(newsletterSignupSchema),
918 ],
919 },
920 ],
921 })
922 ```
923
924 You define middlewares using the `defineMiddlewares` function from the Medusa Framework. It accepts an object having a `routes` property, whose value is an array of middleware route objects. Each middleware route object has the following properties:
925
926 - `matcher`: The path of the route the middleware applies to.
927 - `methods`: The HTTP methods the middleware applies to, which is in this case `POST`.
928 - `middlewares`: An array of middleware functions to apply to the route. You apply the `validateAndTransformBody` middleware which ensures that a request's body has the parameters required by a route. You pass it the schema you defined earlier in the API route's file.
929
930 ### c. Create Subscriber
931
932 Finally, you'll create a subscriber that listens to the `newsletter.signup` event emitted by the API route. The subscriber will create a notification with the `newsletter-signup` template. Under the hoode, the Mailchimp Notification Module Provider will handle the notification and subscribe the customer to the newsletter audience list.
933
934 Create the file `src/subscribers/newsletter-signup.ts` with the following content:
935
936 ```ts title="src/subscribers/newsletter-signup.ts"
937 import { SubscriberArgs, type SubscriberConfig } from "@medusajs/framework"
938 import { Modules } from "@medusajs/framework/utils"
939
940 export default async function orderPlacedHandler({
941 event: { data },
942 container,
943 }: SubscriberArgs<{ email: string, first_name: string, last_name: string }>) {
944 const notificationModuleService = container.resolve(
945 Modules.NOTIFICATION
946 )
947
948 await notificationModuleService.createNotifications({
949 channel: "email",
950 to: data.email,
951 template: "newsletter-signup",
952 data: {
953 first_name: data.first_name,
954 last_name: data.last_name,
955 },
956 })
957 }
958
959 export const config: SubscriberConfig = {
960 event: `newsletter.signup`,
961 }
962 ```
963
964 A subscriber file must export:
965
966 1. An asynchronous function, which is the subscriber that is executed when the event is emitted.
967 2. A configuration object that holds the name of the event the subscriber listens to, which is `newsletter.signup` in this case.
968
969 The subscriber function receives an object as a parameter that has a `container` property, which is the Medusa container. The Medusa container holds Framework and commerce tools that you can resolve and use in your customizations.
970
971 In the subscriber function, you resolve the [Notification Module](../../../infrastructure-modules/notification/page.mdx)'s service from the Medusa container. Then, you call the `createNotifications` method to create a notification with the following properties:
972
973 - `channel`: The channel to send the notification through, which is `email` in this case. Since the [Mailchimp Notification Module Provider is registered with the email channel](#g-add-module-provider-to-medusas-configurations), it will process the notification.
974 - `to`: The email address to subscribe to the newsletter.
975 - `template`: The template to use for the notification, which is `newsletter-signup`.
976 - `data`: An object containing additional data to pass to the notification, such as the user's first and last names.
977
978 Now you have an API route that allows customers to subscribe to the newsletter. You'll test it when you customize the storefront in the next step.
979
980 ---
981
982 ## Step 4: Add Newsletter Subscription Form in the Storefront
983
984 In this step, you'll customize the [Next.js Starter Storefront](../../../nextjs-starter/page.mdx) that you installed as part of the first step. You'll add a newsletter subscription form in the storefront's footer that allows customers to subscribe to the newsletter.
985
986 <Note title="Reminder" forceMultiline>
987
988 The Next.js Starter Storefront is available in the `apps/storefront` directory of your project:
989
990 ```bash
991 cd apps/storefront
992 ```
993
994 </Note>
995
996 ### a. Add Subscribe to Newsletter Function
997
998 You'll start by adding a server function that sends a request to the `/store/newsletter` API route you created in the previous step to subscribe a customer to the newsletter.
999
1000 Create the file `src/lib/data/newsletter.ts` with the following content:
1001
1002 ```ts title="src/lib/data/newsletter.ts" badgeLabel="Storefront" badgeColor="blue"
1003 "use server"
1004
1005 import { sdk } from "@lib/config"
1006
1007 export const subscribeToNewsletter = async (email: string) => {
1008 const response = await sdk.client.fetch(`/store/newsletter`, {
1009 method: "POST",
1010 body: {
1011 email,
1012 },
1013 })
1014
1015 return response
1016 }
1017 ```
1018
1019 You use the [JS SDK](../../../js-sdk/page.mdx), which is already configured in the Next.js Starter Storefront, to send a `POST` request to the `/store/newsletter` API route. You pass the email address in the request body.
1020
1021 ### b. Create Newsletter Subscription Form
1022
1023 Next, you'll create a newsletter subscription form component that allows customers to enter their email address and subscribe to the newsletter.
1024
1025 Create the file `src/modules/layout/components/newsletter-form/index.tsx` with the following content:
1026
1027 ```tsx title="src/modules/layout/components/newsletter-form/index.tsx" badgeLabel="Storefront" badgeColor="blue"
1028 "use client"
1029
1030 import { subscribeToNewsletter } from "@lib/data/newsletter"
1031 import { SubmitButton } from "@modules/checkout/components/submit-button"
1032 import Input from "@modules/common/components/input"
1033 import { useState } from "react"
1034 import { toast } from "@medusajs/ui"
1035
1036 const NewsletterForm = () => {
1037 const [email, setEmail] = useState("")
1038 const [loading, setLoading] = useState(false)
1039
1040 const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
1041 e.preventDefault()
1042 setLoading(true)
1043 try {
1044 await subscribeToNewsletter(email)
1045 } catch (error) {
1046 console.error(error)
1047 // ignore, don't show error to user
1048 }
1049 toast.success("Thanks for subscribing!")
1050 setEmail("")
1051 setLoading(false)
1052 }
1053
1054 return (
1055 <div className="flex flex-col lg:flex-row items-center justify-between gap-8">
1056 <div className="flex-1 max-w-md">
1057 <h3 className="txt-compact-large-plus mb-2 text-ui-fg-base">Subscribe to our newsletter</h3>
1058 <p className="text-base-regular text-ui-fg-subtle">
1059 Receive updates on our latest products and exclusive offers.
1060 </p>
1061 </div>
1062 <div className="flex-1 max-w-md w-full">
1063 <form onSubmit={handleSubmit} className="flex gap-x-2">
1064 <div className="flex-1">
1065 <Input
1066 label="Email"
1067 name="email"
1068 type="email"
1069 autoComplete="off"
1070 required
1071 data-testid="newsletter-email-input"
1072 value={email}
1073 onChange={(e) => setEmail(e.target.value)}
1074 disabled={loading}
1075 />
1076 </div>
1077 <div className="flex items-end">
1078 <SubmitButton data-testid="newsletter-submit-button">
1079 Subscribe
1080 </SubmitButton>
1081 </div>
1082 </form>
1083 </div>
1084 </div>
1085 )
1086 }
1087
1088 export default NewsletterForm
1089 ```
1090
1091 You create a `NewsletterForm` component that renders a form with an email input and a submit button.
1092
1093 Once the customer enters their email and submits the form, you use the `subscribeToNewsletter` function you created to subscribe the customer to the newsletter.
1094
1095 You also show a toast notification to the customer indicating that they successfully subscribed to the newsletter.
1096
1097 The `toast` function is imported from [Medusa UI](!ui!), which requires adding `Toaster` component in the application's tree. So, import the `Toaster` component in the file `src/app/[countryCode]/(main)/layout.tsx`:
1098
1099 ```tsx title="src/app/[countryCode]/(main)/layout.tsx" badgeLabel="Storefront" badgeColor="blue"
1100 import { Toaster } from "@medusajs/ui"
1101 ```
1102
1103 Then, in the `PageLayout` component's return statement, add the `Toaster` component after the `Footer` component:
1104
1105 ```tsx title="src/app/[countryCode]/(main)/layout.tsx" badgeLabel="Storefront" badgeColor="blue"
1106 return (
1107 <>
1108 {/* ... */}
1109 <Footer />
1110 <Toaster />
1111 </>
1112 )
1113 ```
1114
1115 ### c. Add Newsletter Form to the Footer
1116
1117 Finally, you'll add the `NewsletterForm` component to the storefront's footer.
1118
1119 In the file `src/modules/layout/components/footer/index.tsx`, import the `NewsletterForm` component:
1120
1121 ```tsx title="src/modules/layout/components/footer/index.tsx" badgeLabel="Storefront" badgeColor="blue"
1122 import NewsletterForm from "@modules/layout/components/newsletter-form"
1123 ```
1124
1125 Then, in the `Footer` component's return statement, add the following before the `div` wrapping the copyright text:
1126
1127 ```tsx title="src/modules/layout/components/footer/index.tsx" badgeLabel="Storefront" badgeColor="blue"
1128 <div className="border-t border-ui-border-base py-16">
1129 <NewsletterForm />
1130 </div>
1131 ```
1132
1133 This will show the newsletter subscription form in the footer of the storefront, before the copyright text.
1134
1135 ### Test out the Newsletter Subscription Form
1136
1137 You'll now test out the newsletter subscription functionality.
1138
1139 First, run the following command in the `apps/backend` directory to start the Medusa server:
1140
1141 ```bash npm2yarn badgeLabel="Medusa Application" badgeColor="green"
1142 npm run dev
1143 ```
1144
1145 Then, in a separate terminal, run the following command in the Next.js Starter Storefront's directory to start the Next.js server:
1146
1147 ```bash npm2yarn
1148 npm run dev
1149 ```
1150
1151 Next, open your browser at `http://localhost:8000` to view the storefront. If you scroll down to the footer, you should see the newsletter subscription form.
1152
1153 ![Next.js Starter Storefront with the newsletter subscription form in the footer](https://res.cloudinary.com/dza7lstvk/image/upload/v1750688006/Medusa%20Resources/CleanShot_2025-06-23_at_17.12.48_2x_bjrylk.png)
1154
1155 Enter an email address in the form and click the "Subscribe" button. You'll see a success toast message indicating that you successfully subscribed to the newsletter.
1156
1157 You can verify that the subscription was successful in your Mailchimp dashboard by going to the "Audience" page. You'll see the email address you entered in the newsletter subscription form listed in your audience.
1158
1159 ![Next.js Starter Storefront with the newsletter subscription form success message](https://res.cloudinary.com/dza7lstvk/image/upload/v1750688118/Medusa%20Resources/CleanShot_2025-06-23_at_17.15.01_2x_wetvkx.png)
1160
1161 If you set up the welcome email automation flow in Mailchimp, you'll receive a welcome email.
1162
1163 ![Welcome email received from Mailchimp](https://res.cloudinary.com/dza7lstvk/image/upload/v1750688154/Medusa%20Resources/CleanShot_2025-06-23_at_12.33.09_2x_zdteda.png)
1164
1165 ---
1166
1167 ## Step 5: Create Automated Product Newsletter
1168
1169 Next, you'll schedule sending a newsletter for new products once a week. Customers subscribed to the newsletter will receive an email with the latest products added to your Medusa store.
1170
1171 To automate the newsletter, you will:
1172
1173 1. Create a workflow that retrieves the latest products and sends a notification with the product data.
1174 2. Create a scheduled job that runs the workflow automatically once a week.
1175
1176 ### a. Create the Workflow
1177
1178 A [workflow](!docs!/learn/fundamentals/workflows) is a series of actions, called steps, that complete a task with rollback and retry mechanisms. In Medusa, you build commerce features in workflows, then execute them in other customizations, such as subscribers, scheduled jobs, and API routes.
1179
1180 You'll create a workflow that retrieves the latest products added to your Medusa store, then creates a notification with the product data useful to send the newsletter.
1181
1182 Create the file `src/workflows/send-newsletter.ts` with the following content:
1183
1184 export const workflowHighlights = [
1185 ["17", "transform", "Compute the cutoff date in a `transform` so it is evaluated at runtime."],
1186 ["21", "useQueryGraphStep", "Retrieve the products created in the last 7 days."],
1187 ["36", "when", "Check whether there are new products."],
1188 ["38", "sendNotificationsStep", "Create a notification with the new products data."],
1189 ]
1190
1191 ```ts title="src/workflows/send-newsletter.ts" highlights={workflowHighlights}
1192 import {
1193 createWorkflow,
1194 transform,
1195 when,
1196 WorkflowResponse,
1197 } from "@medusajs/framework/workflows-sdk"
1198 import {
1199 sendNotificationsStep,
1200 useQueryGraphStep,
1201 } from "@medusajs/medusa/core-flows"
1202
1203 export const sendNewProductsNewsletter = createWorkflow(
1204 "send-new-products-newsletter",
1205 (input) => {
1206 // Get products created in the last 7 days
1207 // 7 days * 24 hours * 60 minutes * 60 seconds * 1000 milliseconds
1208 const createdAfter = transform({}, () => {
1209 return new Date(Date.now() - 7 * 24 * 60 * 60 * 1000)
1210 })
1211
1212 const { data: products } = useQueryGraphStep({
1213 entity: "product",
1214 fields: [
1215 "title",
1216 "handle",
1217 "thumbnail",
1218 "description",
1219 ],
1220 filters: {
1221 created_at: {
1222 $gte: createdAfter,
1223 },
1224 },
1225 })
1226
1227 when({ products }, ({ products }) => products.length > 0)
1228 .then(() => {
1229 sendNotificationsStep([
1230 {
1231 to: "audience", // will be filled in by provider
1232 channel: "email",
1233 template: "new-products",
1234 data: {
1235 products,
1236 },
1237 },
1238 ])
1239 })
1240
1241 return new WorkflowResponse(void 0)
1242 }
1243 )
1244 ```
1245
1246 You create a workflow using `createWorkflow` from the Workflows SDK. It accepts the workflow's unique name as a first parameter.
1247
1248 `createWorkflow` accepts as a second parameter a constructor function, which is the workflow's implementation.
1249
1250 In the workflow's constructor function, you:
1251
1252 1. Use the [useQueryGraphStep](/references/helper-steps/useQueryGraphStep) to retrieve products created in the last 7 days. You retrieve the product's title, handle, thumbnail, and description fields.
1253 2. Use the [when-then](!docs!/learn/fundamentals/workflows/conditions) utility to send the notification only if there are new products. `when` receives two parameters:
1254 - An object to use in the condition function.
1255 - A condition function that receives the first parameter object and returns a boolean indicating whether to execute the steps in the `then` block.
1256 3. If the `when` condition is met, you use the [sendNotificationsStep](/references/medusa-workflows/steps/sendNotificationsStep) to create a notification with the following properties:
1257 - `to`: The audience to send the notification to. This will be filled in by the Mailchimp Notification Module Provider, so you use a placeholder value.
1258 - `channel`: The channel to send the notification through, which is `email` in this case.
1259 - `template`: The template to use for the notification, which is `new-products`.
1260 - `data`: An object containing the products retrieved from the query step.
1261
1262 Finally, you return an instance of `WorkflowResponse` indicating that the workflow was completed successfully.
1263
1264 <Note title="Why use when-then?">
1265
1266 You can't perform data manipulation in a workflow's constructor function. Instead, the Workflows SDK includes utility functions like `when` to perform typical operations that require accessing data values. Learn more about workflow constraints in the [Workflow Constraints](!docs!/learn/fundamentals/workflows/constructor-constraints) documentation.
1267
1268 </Note>
1269
1270 ### b. Create a Scheduled Job
1271
1272 To automate executing a task at a specified interval, you can create a [scheduled job](!docs!/learn/fundamentals/scheduled-jobs). A scheduled job is a background task that runs at a specified interval, such as every hour or every day.
1273
1274 To create a scheduled job, create the file `src/jobs/send-weekly-newsletter.ts` with the following content:
1275
1276 ```ts title="src/jobs/send-weekly-newsletter.ts"
1277 import {
1278 MedusaContainer,
1279 } from "@medusajs/framework/types"
1280 import { sendNewProductsNewsletter } from "../workflows/send-newsletter"
1281 import {
1282 ContainerRegistrationKeys,
1283 } from "@medusajs/framework/utils"
1284
1285 export default async function myCustomJob(container: MedusaContainer) {
1286 const logger = container.resolve(
1287 ContainerRegistrationKeys.LOGGER
1288 )
1289
1290 logger.info("Sending weekly newsletter...")
1291
1292 await sendNewProductsNewsletter(container)
1293 .run({
1294 input: {},
1295 })
1296
1297 logger.info("Newsletter sent successfully")
1298 }
1299
1300 export const config = {
1301 name: "send-weekly-newsletter",
1302 schedule: "0 0 * * 0", // Every Sunday at midnight
1303 }
1304 ```
1305
1306 A scheduled job file must export:
1307
1308 - An asynchronous function that executes the job's logic. The function receives the [Medusa container](!docs!/learn/fundamentals/medusa-container) as a parameter.
1309 - An object with the job's configuration, including the name and the schedule. The schedule is a cron job pattern as a string.
1310 - You set the schedule to run the job every Sunday at midnight, which is represented by the cron pattern `0 0 * * 0`.
1311
1312 In the job function, you:
1313
1314 1. Resolve the [Logger](!docs!/learn/debugging-and-testing/logging) utility from the Medusa container to log messages.
1315 2. Log a message indicating that the newsletter is being sent.
1316 3. Execute the `sendNewProductsNewsletter` workflow by invoking it, passing the Medusa container as a parameter, then calling its `run` method.
1317 4. Log a message indicating that the newsletter was sent successfully.
1318
1319 ### Test Automated Newsletter
1320
1321 To test the automated newsletter, change the schedule of the job in `src/jobs/send-weekly-newsletter.ts` to run every minute by changing the `schedule` property in the job's configuration:
1322
1323 ```ts title="src/jobs/send-weekly-newsletter.ts"
1324 export const config = {
1325 name: "send-weekly-newsletter",
1326 schedule: "* * * * *", // Every minute
1327 }
1328 ```
1329
1330 Also, if you didn't create any products in the past week, make sure to [create a few products in the Medusa Admin](!user-guide!/products/create).
1331
1332 Then, run the following command in the `apps/backend` directory to start the Medusa server:
1333
1334 ```bash npm2yarn badgeLabel="Medusa Application" badgeColor="green"
1335 npm run dev
1336 ```
1337
1338 Wait for a minute for the scheduled job to run. You should see the following logs in the terminal:
1339
1340 ```bash
1341 info: Sending weekly newsletter...
1342 info: Newsletter sent successfully
1343 ```
1344
1345 This indicates that the scheduled job ran successfully.
1346
1347 To confirm that the newsletter was sent, check the Mailchimp dashboard by going to the "Campaigns" page. You'll find a new campaign with the title "New Products" and the date it was sent.
1348
1349 ![Mailchimp campaigns page with the New Products campaign highlighted](https://res.cloudinary.com/dza7lstvk/image/upload/v1750689882/Medusa%20Resources/CleanShot_2025-06-23_at_17.44.27_2x_tkdtwm.png)
1350
1351 If you also subscribed to the newsletter, you should receive an email with the latest products added to your Medusa store.
1352
1353 ![Mailchimp New Products newsletter email](https://res.cloudinary.com/dza7lstvk/image/upload/v1750689914/Medusa%20Resources/CleanShot_2025-06-23_at_13.29.07_2x_m5xpht.png)
1354
1355 Make sure to revert the job's schedule back to run every Sunday at midnight by changing the `schedule` property in the job's configuration:
1356
1357 ```ts title="src/jobs/send-weekly-newsletter.ts"
1358 export const config = {
1359 name: "send-weekly-newsletter",
1360 schedule: "0 0 * * 0", // Every Sunday at midnight
1361 }
1362 ```
1363
1364 ---
1365
1366 ## Next Steps
1367
1368 You've now integrated Mailchimp with Medusa to allow customers to subscribe to a newsletter and to send automated newsletters about new products.
1369
1370 You can expand this feature and integration to:
1371
1372 - Send newsletters about other events, such as new collections or special offers. Refer to the [Events Reference](/references/events) for the list of events you can listen to.
1373 - Customize the registration form in the storefront to add an "opt-in for newsletter" checkbox.
1374 - Customize the notifications to match your business's brand, or use templates defined in Mailchimp instead.
1375
1376 If you're new to Medusa, check out the [main documentation](!docs!/learn), where you'll get a more in-depth understanding of all the concepts you've used in this guide and more.
1377
1378 To learn more about the commerce features that Medusa provides, check out Medusa's [Commerce Modules](../../../commerce-modules/page.mdx).
1379
1380 ### Troubleshooting
1381
1382 If you encounter issues during your development, check out the [troubleshooting guides](../../../troubleshooting/page.mdx).
1383
1384 ### Getting Help
1385
1386 If you encounter issues not covered in the troubleshooting guides:
1387
1388 1. Visit the [Medusa GitHub repository](https://github.com/medusajs/medusa) to report issues or ask questions.
1389 2. Join the [Medusa Discord community](https://discord.gg/medusajs) for real-time support from community members.
1390 3. Contact the [sales team](https://medusajs.com/contact/) to get help from the Medusa team.