Send Invite User Email Notification

In this guide, you'll learn how to handle the invite.created and invite.resent events to send an invite email (or other notification type) to the user.

Looking for no-code docs? Refer to the Manage Invites user guide to learn how to manage invites using the Medusa Admin.

User Invite Flow Overview#

Diagram showcasing the user invite flow detailed below

Admin users can add new users to their store by sending them an invite. The flow for inviting users is as follows:

  1. An admin user invites a user either through the Medusa Admin or using the Create Invite API route.
  2. The invite is created and the invite.created event is emitted.
    • At this point, you can handle the event to send an email or notification to the user.
  3. The invited user receives the invite and can accept it, which creates a new user.

The admin user can also resend the invite if the invited user doesn't receive the invite or doesn't accept it before expiry, which emits the invite.resent event.

In this guide, you'll implement a subscriber that handles the invite.created and invite.resent events to send an email to the user.

After adding the subscriber, you will have a complete user invite flow that you can utilize either through the Medusa Admin or using the Admin APIs.


Prerequisites: Notification Module Provider#

To send an email or notification to the user, you must have a Notification Module Provider set up.

Medusa provides providers like SendGrid and Resend, and you can also create your own custom provider.

Refer to the Notification Module documentation for a list of available providers and how to set them up.

Testing with the Local Notification Module Provider#

For testing purposes, you can use the Local Notification Module Provider by adding this to your medusa-config.ts:

medusa-config.ts
1module.exports = defineConfig({2  // ...3  modules: [4    {5      resolve: "@medusajs/medusa/notification",6      options: {7        providers: [8          // ...9          {10            resolve: "@medusajs/medusa/notification-local",11            id: "local",12            options: {13              channels: ["email"],14            },15          },16        ],17      },18    },19  ],20})

The Local provider logs email details to your terminal instead of sending actual emails, which is useful for development and testing.


Create the Invite User Subscriber#

To create a subscriber that handles the invite.created and invite.resent events, create the file src/subscribers/user-invited.ts with the following content:

src/subscribers/user-invited.ts
1import { SubscriberArgs, type SubscriberConfig } from "@medusajs/framework"2
3export default async function inviteCreatedHandler({4  event: { data },5  container,6}: SubscriberArgs<{7  id: string8}>) {9  const query = container.resolve("query")10  const notificationModuleService = container.resolve(11    "notification"12  )13  const config = container.resolve("configModule")14
15  const { data: [invite] } = await query.graph({16    entity: "invite",17    fields: [18      "email",19      "token",20    ],21    filters: {22      id: data.id,23    },24  })25
26  const backend_url = config.admin.backendUrl !== "/" ? config.admin.backendUrl :27    "http://localhost:9000"28  const adminPath = config.admin.path29
30  await notificationModuleService.createNotifications({31    to: invite.email,32    // TODO replace with template ID in notification provider33    template: "user-invited",34    channel: "email",35    data: {36      invite_url: `${backend_url}${adminPath}/invite?token=${invite.token}`,37    },38  })39}40
41export const config: SubscriberConfig = {42  event: [43    "invite.created",44    "invite.resent",45  ],46}

The subscriber receives the ID of the invite in the event payload. You resolve Query to fetch the invite details, including the email and token.

Invite URL#

You then use the Notification Module's service to send an email to the user with the invite link. The invite link is constructed using:

  1. The backend URL of the Medusa application, since the Medusa Admin is hosted on the same URL.
  2. The admin path, which is the path to the Medusa Admin (for example, /app).

Note that the Medusa Admin has an invite form at /invite?token=, which accepts the invite token as a query parameter.

Notification Configurations#

For the notification, you can configure the following fields:

  • template: The template ID of the email to send. This ID depends on the Notification Module provider you use. For example, if you use SendGrid, this would be the ID of the SendGrid template.
  • channel: The channel to send the notification through. In this case, it's set to email.
  • data: The data to pass to the notification template. You can add additional fields as needed, such as the invited user's email.

Test It Out#

After you set up the Notification Module Provider, create a template in the provider, and create the subscriber, you can test the full invite flow.

Start the Medusa application with the following command:

Then, open the Medusa Admin (locally at http://localhost:9000/app) and go to Settings → Users. Create an invite as explained in the Manage Invites user guide.

Once you create the invite, you should see that the invite.created event is emitted in the server's logs:

Terminal
info:    Processing invite.created which has 1 subscribers

If you're using an email Notification Module Provider, check the recipient's email inbox for the invite email with the link to accept the invite.

If you're using the Local provider, check your terminal for the logged email details.


Example Notification Templates#

The following section provides example notification templates for some Notification Module Providers.

SendGrid#

Note: Refer to the SendGrid Notification Module Provider documentation for more details on how to set up SendGrid.

The following HTML template can be used with SendGrid to send an invite email:

Code
1<!DOCTYPE html>2<html>3<head>4    <meta charset="utf-8">5    <meta name="viewport" content="width=device-width, initial-scale=1.0">6    <title>You're Invited!</title>7    <style>8        body {9            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif;10            background-color: #ffffff;11            margin: 0;12            padding: 20px;13        }14        .container {15            max-width: 465px;16            margin: 40px auto;17            border: 1px solid #eaeaea;18            border-radius: 5px;19            padding: 20px;20        }21        .header {22            text-align: center;23            margin: 30px 0;24        }25        .title {26            color: #000000;27            font-size: 24px;28            font-weight: normal;29            margin: 0;30        }31        .content {32            margin: 32px 0;33        }34        .text {35            color: #000000;36            font-size: 14px;37            line-height: 24px;38            margin: 0 0 16px 0;39        }40        .button-container {41            text-align: center;42            margin: 32px 0;43        }44        .invite-button {45            background-color: #000000;46            border-radius: 3px;47            color: #ffffff;48            font-size: 12px;49            font-weight: 600;50            text-decoration: none;51            text-align: center;52            padding: 12px 20px;53            display: inline-block;54        }55        .invite-button:hover {56            background-color: #333333;57        }58        .url-section {59            margin: 32px 0;60        }61        .url-link {62            color: #2563eb;63            text-decoration: none;64            font-size: 14px;65            line-height: 24px;66            word-break: break-all;67        }68        .footer {69            margin-top: 32px;70        }71        .footer-text {72            color: #666666;73            font-size: 12px;74            line-height: 24px;75            margin: 0;76        }77    </style>78</head>79<body>80    <div class="container">81        <div class="header">82            <h1 class="title">You're Invited!</h1>83        </div>84
85        <div class="content">86            <p class="text">87                Hello{{#if email}} {{email}}{{/if}},88            </p>89            <p class="text">90                You've been invited to join our platform. Click the button below to accept your invitation and set up your account.91            </p>92        </div>93
94        <div class="button-container">95            <a href="{{invite_url}}" class="invite-button">96                Accept Invitation97            </a>98        </div>99
100        <div class="url-section">101            <p class="text">102                Or copy and paste this URL into your browser:103            </p>104            <a href="{{invite_url}}" class="url-link">105                {{invite_url}}106            </a>107        </div>108
109        <div class="footer">110            <p class="footer-text">111                If you weren't expecting this invitation, you can ignore this email.112            </p>113        </div>114    </div>115</body>116</html>

Make sure to pass the invite_url variable to the template, which contains the URL to accept the invite.

You can also customize the template further to show other information, such as the user's email.

Resend#

If you've integrated Resend as explained in the Resend Integration Guide, you can add a new template for user invites at src/modules/resend/emails/user-invited.tsx:

src/modules/resend/emails/user-invited.tsx
1import { 2  Text, 3  Container, 4  Heading, 5  Html, 6  Section, 7  Tailwind, 8  Head, 9  Preview, 10  Body, 11  Link,12  Button, 13} from "@react-email/components"14
15type UserInvitedEmailProps = {16  invite_url: string17  email?: string18}19
20function UserInvitedEmailComponent({ invite_url, email }: UserInvitedEmailProps) {21  return (22    <Html>23      <Head />24      <Preview>You've been invited to join our platform</Preview>25      <Tailwind>26        <Body className="bg-white my-auto mx-auto font-sans px-2">27          <Container className="border border-solid border-[#eaeaea] rounded my-[40px] mx-auto p-[20px] max-w-[465px]">28            <Section className="mt-[32px]">29              <Heading className="text-black text-[24px] font-normal text-center p-0 my-[30px] mx-0">30                You're Invited!31              </Heading>32            </Section>33
34            <Section className="my-[32px]">35              <Text className="text-black text-[14px] leading-[24px]">36                Hello{email ? ` ${email}` : ""},37              </Text>38              <Text className="text-black text-[14px] leading-[24px]">39                You've been invited to join our platform. Click the button below to accept your invitation and set up your account.40              </Text>41            </Section>42
43            <Section className="text-center mt-[32px] mb-[32px]">44              <Button45                className="bg-[#000000] rounded text-white text-[12px] font-semibold no-underline text-center px-5 py-3"46                href={invite_url}47              >48                Accept Invitation49              </Button>50            </Section>51
52            <Section className="my-[32px]">53              <Text className="text-black text-[14px] leading-[24px]">54                Or copy and paste this URL into your browser:55              </Text>56              <Link57                href={invite_url}58                className="text-blue-600 no-underline text-[14px] leading-[24px] break-all"59              >60                {invite_url}61              </Link>62            </Section>63
64            <Section className="mt-[32px]">65              <Text className="text-[#666666] text-[12px] leading-[24px]">66                If you weren't expecting this invitation, you can ignore this email.67              </Text>68            </Section>69          </Container>70        </Body>71      </Tailwind>72    </Html>73  )74}75
76export const userInvitedEmail = (props: UserInvitedEmailProps) => (77  <UserInvitedEmailComponent {...props} />78)79
80// Mock data for preview/development81const mockInvite: UserInvitedEmailProps = {82  invite_url: "https://your-app.com/app/invite/sample-token-123",83  email: "user@example.com",84}85
86export default () => <UserInvitedEmailComponent {...mockInvite} />

Feel free to customize the email template further to match your branding and style, or to add additional information such as the user's email.

Then, in the Resend Module's service at src/modules/resend/service.ts, add the new template to the templates object and Templates type:

src/modules/resend/service.ts
1// other imports...2import { userInvitedEmail } from "./emails/user-invited"3
4enum Templates {5  // ...6  USER_INVITED = "user-invited",7}8
9const templates: {[key in Templates]?: (props: unknown) => React.ReactNode} = {10  // ...11  [Templates.USER_INVITED]: userInvitedEmail,12}

Finally, find the getTemplateSubject function in the ResendNotificationProviderService and add a case for the USER_INVITED template:

src/modules/resend/service.ts
1class ResendNotificationProviderService extends AbstractNotificationProviderService {2  // ...3
4  private getTemplateSubject(template: Templates) {5    // ...6    switch (template) {7      // ...8      case Templates.USER_INVITED:9        return "You've been invited to join our platform"10    }11  }12}
Was this page helpful?
Ask Anything
FAQ
What is Medusa?
How can I create a module?
How can I create a data model?
How do I create a workflow?
How can I extend a data model in the Product Module?
Recipes
How do I build a marketplace with Medusa?
How do I build digital products with Medusa?
How do I build subscription-based purchases with Medusa?
What other recipes are available in the Medusa documentation?
Chat is cleared on refresh
Line break