Raw
1 ---
2 sidebar_label: "Invite User Email"
3 tags:
4 - server
5 - how to
6 - notification
7 ---
8
9 export const metadata = {
10 title: `Send Invite User Email Notification`,
11 }
12
13 # {metadata.title}
14
15 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.
16
17 <Note title="Looking for no-code docs?">
18
19 Refer to the [Manage Invites](!user-guide!/settings/users/invites) user guide to learn how to manage invites using the Medusa Admin.
20
21 </Note>
22
23 ## User Invite Flow Overview
24
25 ![Diagram showcasing the user invite flow detailed below](https://res.cloudinary.com/dza7lstvk/image/upload/v1754047213/Medusa%20Resources/invite-user_uqspsv.jpg)
26
27 Admin users can add new users to their store by sending them an invite. The flow for inviting users is as follows:
28
29 1. An admin user invites a user either through the [Medusa Admin](!user-guide!/settings/users/invites) or using the [Create Invite API route](!api!/admin/invites/create-invite).
30 2. The invite is created and the `invite.created` event is emitted.
31 - At this point, you can handle the event to send an email or notification to the user.
32 3. The invited user receives the invite and can accept it, which creates a new user.
33 - The invited user can accept the invite either through the Medusa Admin or using the [Accept Invite API route](!api!/admin/invites/accept-invite).
34
35 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.
36
37 In this guide, you'll implement a subscriber that handles the `invite.created` and `invite.resent` events to send an email to the user.
38
39 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.
40
41 ---
42
43 ## Prerequisites: Notification Module Provider
44
45 To send an email or notification to the user, you must have a Notification Module Provider set up.
46
47 Medusa provides providers like [SendGrid](../../../infrastructure-modules/notification/sendgrid/page.mdx) and [Resend](../../../integrations/guides/resend/page.mdx), and you can also [create your own custom provider](/references/notification-provider-module).
48
49 Refer to the [Notification Module](../../../infrastructure-modules/notification/page.mdx#what-is-a-notification-module-provider) documentation for a list of available providers and how to set them up.
50
51 ### Testing with the Local Notification Module Provider
52
53 For testing purposes, you can use the [Local Notification Module Provider](../../../infrastructure-modules/notification/local/page.mdx) by adding this to your `medusa-config.ts`:
54
55 ```ts title="medusa-config.ts"
56 module.exports = defineConfig({
57 // ...
58 modules: [
59 {
60 resolve: "@medusajs/medusa/notification",
61 options: {
62 providers: [
63 // ...
64 {
65 resolve: "@medusajs/medusa/notification-local",
66 id: "local",
67 options: {
68 channels: ["email"],
69 },
70 },
71 ],
72 },
73 },
74 ],
75 })
76 ```
77
78 The Local provider logs email details to your terminal instead of sending actual emails, which is useful for development and testing.
79
80 ---
81
82 ## Create the Invite User Subscriber
83
84 To create a [subscriber](!docs!/learn/fundamentals/events-and-subscribers) that handles the `invite.created` and `invite.resent` events, create the file `src/subscribers/user-invited.ts` with the following content:
85
86 export const highlights = [
87 ["23", "invite", "Retrieve the invite's details."],
88 ["34", "backend_url", "Construct the backend URL."],
89 ["36", "adminPath", "Get the admin path from the config."],
90 ["38", "createNotifications", "Send the notification to the user."],
91 ["42", "channel", "Use the Notification Module Provider configured for the email channel."],
92 ["43", "data", "Pass the invite URL to the notification template."],
93 ["50", "event", "Subscribe to the invite events."]
94 ]
95
96 ```ts title="src/subscribers/user-invited.ts" highlights={highlights}
97 import { SubscriberArgs, type SubscriberConfig } from "@medusajs/framework"
98 import {
99 Modules,
100 ContainerRegistrationKeys,
101 } from "@medusajs/framework/utils"
102
103 export default async function inviteCreatedHandler({
104 event: { data },
105 container,
106 }: SubscriberArgs<{
107 id: string
108 }>) {
109 const query = container.resolve(
110 ContainerRegistrationKeys.QUERY
111 )
112 const notificationModuleService = container.resolve(
113 Modules.NOTIFICATION
114 )
115 const config = container.resolve(
116 ContainerRegistrationKeys.CONFIG_MODULE
117 )
118
119 const { data: [invite] } = await query.graph({
120 entity: "invite",
121 fields: [
122 "email",
123 "token",
124 ],
125 filters: {
126 id: data.id,
127 },
128 })
129
130 const backend_url = config.admin.backendUrl !== "/" ? config.admin.backendUrl :
131 "http://localhost:9000"
132 const adminPath = config.admin.path
133
134 await notificationModuleService.createNotifications({
135 to: invite.email,
136 // TODO replace with template ID in notification provider
137 template: "user-invited",
138 channel: "email",
139 data: {
140 invite_url: `${backend_url}${adminPath}/invite?token=${invite.token}`,
141 },
142 })
143 }
144
145 export const config: SubscriberConfig = {
146 event: [
147 "invite.created",
148 "invite.resent",
149 ],
150 }
151 ```
152
153 The subscriber receives the ID of the invite in the event payload. You resolve [Query](!docs!/learn/fundamentals/query) to fetch the invite details, including the email and token.
154
155 ### Invite URL
156
157 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:
158
159 1. The backend URL of the Medusa application, since the Medusa Admin is hosted on the same URL.
160 2. The admin path, which is the path to the Medusa Admin (for example, `/app`).
161
162 Note that the Medusa Admin has an invite form at `/invite?token=`, which accepts the invite token as a query parameter.
163
164 ### Notification Configurations
165
166 For the notification, you can configure the following fields:
167
168 - `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.
169 - Refer to the [Example Notification Templates](#example-notification-templates) section below for examples of notification templates to use.
170 - `channel`: The channel to send the notification through. In this case, it's set to `email`.
171 - `data`: The data to pass to the notification template. You can add additional fields as needed, such as the invited user's email.
172
173 ### Test It Out
174
175 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.
176
177 Start the Medusa application with the following command:
178
179 ```bash npm2yarn
180 npm run dev
181 ```
182
183 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!/settings/users/invites) user guide.
184
185 Once you create the invite, you should see that the `invite.created` event is emitted in the server's logs:
186
187 ```bash
188 info: Processing invite.created which has 1 subscribers
189 ```
190
191 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.
192
193 If you're using the Local provider, check your terminal for the logged email details.
194
195 ---
196
197 ## Example Notification Templates
198
199 The following section provides example notification templates for some Notification Module Providers.
200
201 ### SendGrid
202
203 <Note>
204
205 Refer to the [SendGrid Notification Module Provider](../../../infrastructure-modules/notification/sendgrid/page.mdx) documentation for more details on how to set up SendGrid.
206
207 </Note>
208
209 The following HTML template can be used with SendGrid to send an invite email:
210
211 ```html
212 <!DOCTYPE html>
213 <html>
214 <head>
215 <meta charset="utf-8">
216 <meta name="viewport" content="width=device-width, initial-scale=1.0">
217 <title>You're Invited!</title>
218 <style>
219 body {
220 font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif;
221 background-color: #ffffff;
222 margin: 0;
223 padding: 20px;
224 }
225 .container {
226 max-width: 465px;
227 margin: 40px auto;
228 border: 1px solid #eaeaea;
229 border-radius: 5px;
230 padding: 20px;
231 }
232 .header {
233 text-align: center;
234 margin: 30px 0;
235 }
236 .title {
237 color: #000000;
238 font-size: 24px;
239 font-weight: normal;
240 margin: 0;
241 }
242 .content {
243 margin: 32px 0;
244 }
245 .text {
246 color: #000000;
247 font-size: 14px;
248 line-height: 24px;
249 margin: 0 0 16px 0;
250 }
251 .button-container {
252 text-align: center;
253 margin: 32px 0;
254 }
255 .invite-button {
256 background-color: #000000;
257 border-radius: 3px;
258 color: #ffffff;
259 font-size: 12px;
260 font-weight: 600;
261 text-decoration: none;
262 text-align: center;
263 padding: 12px 20px;
264 display: inline-block;
265 }
266 .invite-button:hover {
267 background-color: #333333;
268 }
269 .url-section {
270 margin: 32px 0;
271 }
272 .url-link {
273 color: #2563eb;
274 text-decoration: none;
275 font-size: 14px;
276 line-height: 24px;
277 word-break: break-all;
278 }
279 .footer {
280 margin-top: 32px;
281 }
282 .footer-text {
283 color: #666666;
284 font-size: 12px;
285 line-height: 24px;
286 margin: 0;
287 }
288 </style>
289 </head>
290 <body>
291 <div class="container">
292 <div class="header">
293 <h1 class="title">You're Invited!</h1>
294 </div>
295
296 <div class="content">
297 <p class="text">
298 Hello{{#if email}} {{email}}{{/if}},
299 </p>
300 <p class="text">
301 You've been invited to join our platform. Click the button below to accept your invitation and set up your account.
302 </p>
303 </div>
304
305 <div class="button-container">
306 <a href="{{invite_url}}" class="invite-button">
307 Accept Invitation
308 </a>
309 </div>
310
311 <div class="url-section">
312 <p class="text">
313 Or copy and paste this URL into your browser:
314 </p>
315 <a href="{{invite_url}}" class="url-link">
316 {{invite_url}}
317 </a>
318 </div>
319
320 <div class="footer">
321 <p class="footer-text">
322 If you weren't expecting this invitation, you can ignore this email.
323 </p>
324 </div>
325 </div>
326 </body>
327 </html>
328 ```
329
330 Make sure to pass the `invite_url` variable to the template, which contains the URL to accept the invite.
331
332 You can also customize the template further to show other information, such as the user's email.
333
334 ### Resend
335
336 If you've integrated Resend as explained in the [Resend Integration Guide](../../../integrations/guides/resend/page.mdx), you can add a new template for user invites at `src/modules/resend/emails/user-invited.tsx`:
337
338 ```tsx title="src/modules/resend/emails/user-invited.tsx"
339 import {
340 Text,
341 Container,
342 Heading,
343 Html,
344 Section,
345 Tailwind,
346 Head,
347 Preview,
348 Body,
349 Link,
350 Button,
351 } from "@react-email/components"
352
353 type UserInvitedEmailProps = {
354 invite_url: string
355 email?: string
356 }
357
358 function UserInvitedEmailComponent({ invite_url, email }: UserInvitedEmailProps) {
359 return (
360 <Html>
361 <Head />
362 <Preview>You've been invited to join our platform</Preview>
363 <Tailwind>
364 <Body className="bg-white my-auto mx-auto font-sans px-2">
365 <Container className="border border-solid border-[#eaeaea] rounded my-[40px] mx-auto p-[20px] max-w-[465px]">
366 <Section className="mt-[32px]">
367 <Heading className="text-black text-[24px] font-normal text-center p-0 my-[30px] mx-0">
368 You're Invited!
369 </Heading>
370 </Section>
371
372 <Section className="my-[32px]">
373 <Text className="text-black text-[14px] leading-[24px]">
374 Hello{email ? ` ${email}` : ""},
375 </Text>
376 <Text className="text-black text-[14px] leading-[24px]">
377 You've been invited to join our platform. Click the button below to accept your invitation and set up your account.
378 </Text>
379 </Section>
380
381 <Section className="text-center mt-[32px] mb-[32px]">
382 <Button
383 className="bg-[#000000] rounded text-white text-[12px] font-semibold no-underline text-center px-5 py-3"
384 href={invite_url}
385 >
386 Accept Invitation
387 </Button>
388 </Section>
389
390 <Section className="my-[32px]">
391 <Text className="text-black text-[14px] leading-[24px]">
392 Or copy and paste this URL into your browser:
393 </Text>
394 <Link
395 href={invite_url}
396 className="text-blue-600 no-underline text-[14px] leading-[24px] break-all"
397 >
398 {invite_url}
399 </Link>
400 </Section>
401
402 <Section className="mt-[32px]">
403 <Text className="text-[#666666] text-[12px] leading-[24px]">
404 If you weren't expecting this invitation, you can ignore this email.
405 </Text>
406 </Section>
407 </Container>
408 </Body>
409 </Tailwind>
410 </Html>
411 )
412 }
413
414 export const userInvitedEmail = (props: UserInvitedEmailProps) => (
415 <UserInvitedEmailComponent {...props} />
416 )
417
418 // Mock data for preview/development
419 const mockInvite: UserInvitedEmailProps = {
420 invite_url: "https://your-app.com/app/invite/sample-token-123",
421 email: "user@example.com",
422 }
423
424 export default () => <UserInvitedEmailComponent {...mockInvite} />
425 ```
426
427 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.
428
429 Then, in the Resend Module's service at `src/modules/resend/service.ts`, add the new template to the `templates` object and `Templates` type:
430
431 ```ts title="src/modules/resend/service.ts"
432 // other imports...
433 import { userInvitedEmail } from "./emails/user-invited"
434
435 enum Templates {
436 // ...
437 USER_INVITED = "user-invited",
438 }
439
440 const templates: {[key in Templates]?: (props: unknown) => React.ReactNode} = {
441 // ...
442 [Templates.USER_INVITED]: userInvitedEmail,
443 }
444 ```
445
446 Finally, find the `getTemplateSubject` function in the `ResendNotificationProviderService` and add a case for the `USER_INVITED` template:
447
448 ```ts title="src/modules/resend/service.ts"
449 class ResendNotificationProviderService extends AbstractNotificationProviderService {
450 // ...
451
452 private getTemplateSubject(template: Templates) {
453 // ...
454 switch (template) {
455 // ...
456 case Templates.USER_INVITED:
457 return "You've been invited to join our platform"
458 }
459 }
460 }
461 ```