1 {"slug":"/references/notification-provider-module","title":"How to Create a Notification Module Provider","frontmatter":{"slug":"/references/notification-provider-module","tags":["notification","server","how to"],"sidebar_label":"Create Notification Provider"},"toc":[{"title":"Implementation Example","id":"implementation-example","level":2},{"title":"1. Create Module Provider Directory","id":"1-create-module-provider-directory","level":2},{"title":"2. Create the Notification Module Provider's Service","id":"2-create-the-notification-module-provider-s-service","level":2},{"title":"constructor","id":"constructor","level":3},{"title":"Example","id":"example","level":4},{"title":"identifier","id":"identifier","level":3},{"title":"Example","id":"example-1","level":4},{"title":"validateOptions","id":"validateoptions","level":3},{"title":"Example","id":"example-2","level":4},{"title":"Parameters","id":"validateoptions-parameters","level":4},{"title":"send","id":"send","level":3},{"title":"Example","id":"example-3","level":4},{"title":"Parameters","id":"send-parameters","level":4},{"title":"Returns","id":"send-returns","level":4},{"title":"3. Create Module Provider Definition File","id":"3-create-module-provider-definition-file","level":2},{"title":"4. Use Module Provider","id":"4-use-module-provider","level":2},{"title":"5. Test it Out","id":"5-test-it-out","level":2},{"title":"Create Subscriber","id":"create-subscriber","level":3},{"title":"Create User","id":"create-user","level":3}],"blocks":[{"kind":"markdown","html":"In this document, you’ll learn how to create a Notification Module Provider and the methods you must implement in it."},{"kind":"markdown","html":"---"},{"kind":"heading","level":2,"text":"Implementation Example","id":"implementation-example"},{"kind":"markdown","html":"As you implement your Notification Module Provider, it can be useful to refer to an existing provider and how it's implemeted.\n\nIf you need to refer to an existing implementation as an example, check the [SendGrid Notification Module Provider in the Medusa repository](https://github.com/medusajs/medusa/tree/develop/packages/modules/providers/notification-sendgrid).\n\n---"},{"kind":"heading","level":2,"text":"1. Create Module Provider Directory","id":"1-create-module-provider-directory"},{"kind":"markdown","html":"Start by creating a new directory for your module provider.\n\nIf you're creating the module provider in a Medusa application, create it under the `src/modules` directory. For example, `src/modules/my-notification`.\n\nIf you're creating the module provider in a plugin, create it under the `src/providers` directory. For example, `src/providers/my-notification`."},{"kind":"note","variant":"note","html":"The rest of this guide always uses the `src/modules/my-notification` directory as an example."},{"kind":"markdown","html":"---"},{"kind":"heading","level":2,"text":"2. Create the Notification Module Provider's Service","id":"2-create-the-notification-module-provider-s-service"},{"kind":"markdown","html":"Create the file `src/modules/my-notification/service.ts` that holds the implementation of the notification service.\n\nThe Notification Module Provider's main service must extend the `AbstractNotificationProviderService` class imported from `@medusajs/framework/utils`:\n\n```ts title=\"src/modules/my-notification/service.ts\"\nimport { \n AbstractNotificationProviderService\n} from \"@medusajs/framework/utils\"\n\nclass MyNotificationProviderService extends AbstractNotificationProviderService {\n // TODO add methods\n}\n\nexport default MyNotificationProviderService\n```"},{"kind":"heading","level":3,"text":"constructor","id":"constructor"},{"kind":"markdown","html":"The constructor allows you to access resources from the module's container using the first parameter,\nand the module's options using the second parameter.\n\nIf you're creating a client or establishing a connection with a third-party service, do it in the constructor."},{"kind":"heading","level":4,"text":"Example","id":"example"},{"kind":"markdown","html":"```ts\nimport { AbstractNotificationProviderService } from \"@medusajs/framework/utils\"\nimport { Logger } from \"@medusajs/framework/types\"\n\ntype InjectedDependencies = {\n logger: Logger\n}\n\ntype Options = {\n apiKey: string\n}\n\nclass MyNotificationProviderService extends AbstractNotificationProviderService {\n protected logger_: Logger\n protected options_: Options\n // assuming you're initializing a client\n protected client\n\n constructor (\n { logger }: InjectedDependencies,\n options: Options\n ) {\n super()\n\n this.logger_ = logger\n this.options_ = options\n\n // assuming you're initializing a client\n this.client = new Client(options)\n }\n}\n\nexport default MyNotificationProviderService\n```"},{"kind":"heading","level":3,"text":"identifier","id":"identifier"},{"kind":"markdown","html":"Each notification provider has a unique ID used to identify it."},{"kind":"heading","level":4,"text":"Example","id":"example-1"},{"kind":"markdown","html":"```ts\nclass MyNotificationProviderService extends AbstractNotificationProviderService {\n static identifier = \"my-notification\"\n // ...\n}\n```"},{"kind":"heading","level":3,"text":"validateOptions","id":"validateoptions"},{"kind":"markdown","html":"This method validates the options of the provider set in `medusa-config.ts`.\nImplementing this method is optional. It's useful if your provider requires custom validation.\n\nIf the options aren't valid, throw an error."},{"kind":"heading","level":4,"text":"Example","id":"example-2"},{"kind":"markdown","html":"```ts\nclass MyNotificationProviderService extends AbstractNotificationProviderService {\n static validateOptions(options: Record<any, any>) {\n if (!options.apiKey) {\n throw new MedusaError(\n MedusaError.Types.INVALID_DATA,\n \"API key is required in the provider's options.\"\n )\n }\n }\n}\n```"},{"kind":"heading","level":4,"text":"Parameters","id":"validateoptions-parameters"},{"kind":"typeList","sectionTitle":"validateOptions","types":[{"name":"options","type":"`Record<any, any>`","description":"The provider's options.","optional":false,"defaultValue":"","expandable":false,"children":[]}]},{"kind":"heading","level":3,"text":"send","id":"send"},{"kind":"markdown","html":"This method is used to send a notification using the third-party provider or your custom logic."},{"kind":"heading","level":4,"text":"Example","id":"example-3"},{"kind":"markdown","html":"```ts\n// other imports...\nimport {\n ProviderSendNotificationDTO,\n ProviderSendNotificationResultsDTO\n} from \"@medusajs/framework/types\"\n\nclass MyNotificationProviderService extends AbstractNotificationProviderService {\n // ...\n async send(\n notification: ProviderSendNotificationDTO\n ): Promise<ProviderSendNotificationResultsDTO> {\n // TODO send the notification using a third-party\n // provider or custom logic.\n // for example:\n return this.client.send({\n email: notification.to,\n template: notification.template,\n template_data: notification.data\n })\n }\n}\n```"},{"kind":"heading","level":4,"text":"Parameters","id":"send-parameters"},{"kind":"typeList","sectionTitle":"send","types":[{"name":"notification","type":"[ProviderSendNotificationDTO](/references/types/NotificationTypes/interfaces/types.NotificationTypes.ProviderSendNotificationDTO)","description":"The details of the\nnotification to send.","optional":false,"defaultValue":"","expandable":false,"children":[{"name":"to","type":"`string`","description":"The recipient of the notification. It can be email, phone number, or username, depending on the channel.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"from","type":"`null` \\| `string`","description":"The sender of the notification. It can be email, phone number, or username, depending on the channel.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"attachments","type":"`null` \\| [Attachment](/references/types/NotificationTypes/interfaces/types.NotificationTypes.Attachment)[]","description":"Optional attachments for the notification.","optional":true,"defaultValue":"","expandable":false,"children":[{"name":"content","type":"`string`","description":"The content of the attachment, encoded as a binary string.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"filename","type":"`string`","description":"The filename of the attachment.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"content_type","type":"`string`","description":"The MIME type of the attachment.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"disposition","type":"`string`","description":"The disposition of the attachment, For example, \"inline\" or \"attachment\".","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"id","type":"`string`","description":"The ID, if the attachment is meant to be referenced within the body of the message.","optional":true,"defaultValue":"","expandable":false,"children":[]}]},{"name":"channel","type":"`string`","description":"The channel through which the notification is sent, such as 'email' or 'sms'","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"template","type":"`string`","description":"The template name in the provider's system.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"data","type":"`null` \\| `Record<string, unknown>`","description":"The data that gets passed over to the provider for rendering the notification.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"provider_data","type":"`null` \\| `Record<string, unknown>`","description":"Additional data specific to the provider or channel. For example, cc and bcc for emails.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"content","type":"`null` \\| [NotificationContent](/references/types/NotificationTypes/interfaces/types.NotificationTypes.NotificationContent)","description":"The content that gets passed to the provider.","optional":true,"defaultValue":"","expandable":false,"children":[{"name":"subject","type":"`string`","description":"the subject of the notification","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"text","type":"`string`","description":"the text content of the notification","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"html","type":"`string`","description":"the html content of the notification","optional":true,"defaultValue":"","expandable":false,"children":[]}]}]}]},{"kind":"heading","level":4,"text":"Returns","id":"send-returns"},{"kind":"typeList","sectionTitle":"send","types":[{"name":"Promise","type":"Promise&#60;[ProviderSendNotificationResultsDTO](/references/types/NotificationTypes/interfaces/types.NotificationTypes.ProviderSendNotificationResultsDTO)&#62;","optional":false,"defaultValue":"","description":"The result of sending\nthe notification.","expandable":false,"children":[]}]},{"kind":"markdown","html":"---"},{"kind":"heading","level":2,"text":"3. Create Module Provider Definition File","id":"3-create-module-provider-definition-file"},{"kind":"markdown","html":"Create the file `src/modules/my-notification/index.ts` with the following content:\n\n```ts title=\"src/modules/my-notification/index.ts\"\nimport MyNotificationProviderService from \"./service\"\nimport { \n ModuleProvider, \n Modules\n} from \"@medusajs/framework/utils\"\n\nexport default ModuleProvider(Modules.NOTIFICATION, {\n services: [MyNotificationProviderService],\n})\n```\n\nThis exports the module provider's definition, indicating that the `MyNotificationProviderService` is the module provider's service."},{"kind":"note","variant":"note","title":"Tip","html":"A notification module provider can have export multiple provider services, where each are registered as a separate notification provider."},{"kind":"markdown","html":"---"},{"kind":"heading","level":2,"text":"4. Use Module Provider","id":"4-use-module-provider"},{"kind":"markdown","html":"To use your Notification Module Provider, add it to the `providers` array of the Notification Module in `medusa-config.ts`:"},{"kind":"note","variant":"note","html":"The Notification Module accepts one provider per channel."},{"kind":"markdown","html":"```ts title=\"medusa-config.ts\"\nmodule.exports = defineConfig({\n // ...\n modules: [\n {\n resolve: \"@medusajs/medusa/notification\",\n options: {\n providers: [\n // default provider\n {\n resolve: \"@medusajs/medusa/notification-local\",\n id: \"local\",\n options: {\n name: \"Local Notification Provider\",\n channels: [\"feed\"],\n },\n },\n {\n // if module provider is in a plugin, use `plugin-name/providers/my-notification`\n resolve: \"./src/modules/my-notification\",\n id: \"my-notification\",\n options: {\n channels: [\"email\"],\n // provider options...\n },\n },\n ],\n },\n },\n ]\n})\n```\n\nMake sure to specify the correct channels for your provider in the `channels` option.\n\n---"},{"kind":"heading","level":2,"text":"5. Test it Out","id":"5-test-it-out"},{"kind":"heading","level":3,"text":"Create Subscriber","id":"create-subscriber"},{"kind":"markdown","html":"To test out the provider, create a subscriber at `src/subscribers/user-created.ts` with the following content:\n\n```ts title=\"src/subscribers/user-created.ts\"\nimport { Modules } from \"@medusajs/framework/utils\"\nimport {\n SubscriberArgs,\n type SubscriberConfig,\n} from \"@medusajs/medusa\"\n\nexport default async function userCreatedHandler({\n event: { data },\n container,\n}: SubscriberArgs<{ id: string }>) {\n const notificationModuleService = container.resolve(\n Modules.NOTIFICATION\n )\n const query = container.resolve(\"query\")\n\n const { data: [user] } = await query.graph({\n entity: \"user\",\n fields: [\"*\"],\n filters: {\n id: data.id,\n }\n })\n\n await notificationModuleService.createNotifications({\n to: user.email,\n channel: \"email\",\n template: \"new-user\"\n })\n}\n\nexport const config: SubscriberConfig = {\n event: \"user.created\",\n}\n```\n\nIn the subscriber, you resolve the Notification and User modules. Then, you use the User Module's main service to retrieve the user's details.\n\nFinally, you use the Notification Module's main service to send a notification to the user's email through the `email` channel (assuming that's your provider's channel).\n\nMake sure to replace the value of `template` to the ID of the template in your provider."},{"kind":"heading","level":3,"text":"Create User","id":"create-user"},{"kind":"markdown","html":"Use the following command to create a user:\n\n```bash\nnpx medusa user -e admin@test.com -p supersecret\n```\n\nAfter the user is created, the subscriber is executed, sending the notification using your provider."}]}