Raw
1 ---
2 sidebar_label: "Send Email Verification"
3 tags:
4 - notification
5 - how to
6 - server
7 ---
8
9 import { Prerequisites, Note } from "docs-ui"
10
11 export const metadata = {
12 title: `Send Email Verification Notification`,
13 }
14
15 # {metadata.title}
16
17 In this guide, you'll learn how to enable email verification requirement for customers in your Medusa application, and how to send email verification notifications.
18
19 <Note>
20
21 The steps of this guide have changed since Medusa [v2.16.0](https://github.com/medusajs/medusa/releases/tag/v2.16.0). It now uses the `http.authVerificationsPerActor` configuration instead of the `require_verification` option in the Emailpass Auth Module Provider.
22
23 </Note>
24
25 <Prerequisites
26 items={[
27 {
28 text: "Medusa v2.16.0 or later",
29 link: "!docs!/learn/update"
30 },
31 {
32 text: "Notification Module Provider for the email channel, such as SendGrid or Resend",
33 link: "/infrastructure-modules/notification#what-is-a-notification-module-provider"
34 }
35 ]}
36 />
37
38 ## How Email Verification Works
39
40 By default, customers can register an account and log in to your Medusa store without verifying their email address. You can enable email verification to require customers to verify their email address before they can log in.
41
42 When email verification is enabled, the customer registration flow changes to the following:
43
44 ```mermaid
45 sequenceDiagram
46 actor C as Customer
47 participant S as Store
48 C->>S: Register
49 S->>C: Send verification email
50 C->>S: Click verification link
51 S->>C: Email verified
52 C->>S: Log in
53 ```
54
55 1. A customer registers an account by providing their email and password.
56 2. The customer receives an email with a verification link. The link points to a page in your storefront that verifies the customer's email when visited.
57 3. The customer clicks the verification link, which verifies their email address and completes the registration process.
58 4. The customer can now log in to their account.
59
60 This guide focuses on the backend implementation of this flow, which involves enabling email verification and sending the verification email.
61
62 To implement the storefront part of the flow, refer to the [Verify Customer Account in Storefront guide](../../../storefront-development/customers/verify-account/page.mdx).
63
64 ---
65
66 ## Enable Email Verification
67
68 To enable email verification, set the `http.authVerificationsPerActor` configuration in `medusa-config.ts`:
69
70 export const configHighlights = [
71 ["6", "authVerificationsPerActor", "Object specifying the required verification methods per actor type. Include `customer` to require email verification for customers."],
72 ]
73
74 ```ts title="medusa-config.ts" highlights={configHighlights}
75 module.exports = defineConfig({
76 // ...
77 projectConfig: {
78 // ...
79 http: {
80 authVerificationsPerActor: {
81 customer: [
82 {
83 entity_type: "email",
84 auth_provider: "emailpass",
85 },
86 ],
87 },
88 },
89 },
90 })
91 ```
92
93 The `http.authVerificationsPerActor` configuration is an object that specifies the required verification methods for each actor type. The value for each actor type is an array of objects, each specifying a verification method. In this case, you include the `customer` actor type and specify that email verification is required using the `emailpass` auth provider.
94
95 <Note>
96
97 Learn more in the [authVerificationsPerActor configuration reference](!docs!/learn/configurations/medusa-config#httpauthVerificationsPerActor).
98
99 </Note>
100
101 ---
102
103 ## Send Email Verification Notification
104
105 When the storefront requests to send an email verification notification, Medusa emits the `auth.verification_requested` event. You can listen to this event in a [subscriber](!docs!/learn/fundamentals/events-and-subscribers) to send the email verification notification.
106
107 <Note>
108
109 The `auth.verification_requested` event payload changed in Medusa v2.17.0. The `actor_type` and `provider_identity_id` fields were removed, `provider` was renamed to `code_provider`, and `entity_type` was added. If you have a subscriber written before v2.17.0, update it to use the payload described in this guide.
110
111 </Note>
112
113 ### Prerequisite Configurations
114
115 #### Notification Module Provider for Email Channel
116
117 To send the email verification notification, you need a [Notification Module Provider](../../../infrastructure-modules/notification/page.mdx#what-is-a-notification-module-provider) configured for the email channel, such as [SendGrid](../../../infrastructure-modules/notification/sendgrid/page.mdx) or [Resend](../../../integrations/guides/resend/page.mdx).
118
119 For development purposes, you can set the [Notification Local Module Provider](../../../infrastructure-modules/notification/local/page.mdx)'s channel to `email` in `medusa-config.ts`:
120
121 ```ts title="medusa-config.ts"
122 module.exports = defineConfig({
123 // ...
124 modules: [
125 {
126 resolve: "@medusajs/medusa/notification",
127 options: {
128 providers: [
129 // ...
130 {
131 resolve: "@medusajs/medusa/notification-local",
132 id: "local",
133 options: {
134 channels: ["email"],
135 },
136 },
137 ],
138 },
139 },
140 ],
141 })
142 ```
143
144 This will log the email verification notification to the console when it's sent, instead of actually sending an email.
145
146 #### Storefront URL Configuration
147
148 To format the verification link in the email, you need to set the URL to your storefront in `medusa-config.ts`. You can use the `admin.storefrontUrl` configuration for that:
149
150 ```ts title="medusa-config.ts"
151 module.exports = defineConfig({
152 // ...
153 admin: {
154 storefrontUrl: process.env.STOREFRONT_URL || "https://storefront.com",
155 },
156 })
157 ```
158
159 This will allow you to use the `admin.storefrontUrl` value in the subscriber when formatting the verification link. If `admin.storefrontUrl` is not set, you can use a placeholder URL as shown in the subscriber example below.
160
161 ### Email Verification Notification Subscriber
162
163 To send the email verification notification when the `auth.verification_requested` event is emitted, create a [subscriber](!docs!/learn/fundamentals/events-and-subscribers) at `src/subscribers/send-email-verification.ts` with the following content:
164
165 ```ts title="src/subscribers/send-email-verification.ts"
166 import {
167 SubscriberArgs,
168 type SubscriberConfig,
169 } from "@medusajs/medusa"
170 import {
171 Modules,
172 ContainerRegistrationKeys,
173 } from "@medusajs/framework/utils"
174
175 export default async function verificationRequestedHandler({
176 event: { data: {
177 entity_id: email,
178 entity_type,
179 code,
180 } },
181 container,
182 }: SubscriberArgs<{
183 entity_id: string
184 entity_type: string
185 code_provider: string
186 auth_identity_id: string
187 code: string
188 expires_at: string
189 metadata?: Record<string, unknown>
190 }>) {
191 // only handle email verifications.
192 if (entity_type !== "email") {
193 return
194 }
195
196 const notificationModuleService = container.resolve(
197 Modules.NOTIFICATION
198 )
199 const config = container.resolve(
200 ContainerRegistrationKeys.CONFIG_MODULE
201 )
202
203 const urlPrefix = config.admin.storefrontUrl || "https://storefront.com"
204
205 console.log(`${urlPrefix}/verify-account?token=${code}&email=${email}`)
206
207 await notificationModuleService.createNotifications({
208 to: email,
209 channel: "email",
210 // TODO replace with template ID in notification provider
211 template: "email-verification",
212 data: {
213 // a URL to a frontend application
214 verification_url: `${urlPrefix}/verify-account?token=${code}&email=${email}`,
215 },
216 })
217 }
218
219 export const config: SubscriberConfig = {
220 event: "auth.verification_requested",
221 }
222 ```
223
224 #### Event Payload
225
226 This subscriber receives in the event payload an object with the following properties:
227
228 - `entity_id`: The identifier of the provider identity to verify. For email verification, this is the customer's email address.
229 - `entity_type`: The kind of entity being verified, such as `email`. You check that it's `email` before sending the notification, since you only want to handle email verifications.
230 - `code`: The verification code to include in the verification link. When the customer clicks the verification link, the storefront should send the code back to the Medusa application to verify the customer's email address.
231 - `code_provider`: The verification provider used to generate the code. By default, this is `token`.
232 - `auth_identity_id`: The ID of the auth identity for which the verification was requested.
233 - `expires_at`: The date and time at which the verification code expires.
234 - `metadata`: Optional metadata included in the verification request.
235
236 #### Subscriber Implementation
237
238 In the subscriber, you first check that the `entity_type` is `email` to only handle email verifications. Then, you format the storefront URL either using the value of `admin.storefrontUrl` set in `medusa-config.ts` or a placeholder URL. You need this URL to format the verification link sent in the email.
239
240 Then, you send a notification using the Notification Module's main service. You pass the following properties to the `createNotifications` method:
241
242 - `to`: The email address of the customer to which the verification email should be sent.
243 - `channel`: The channel to send the notification through. In this case, it's `email`.
244 - `template`: The ID of the template to use for the notification. This depends on your Notification Module Provider. For example, if you're using the SendGrid Notification Module Provider, this should be the ID of a SendGrid template that you've set up to format the email verification notification.
245 - `data`: The data to be passed to the template when sending the notification. In this case, you pass the `verification_url` property, which contains the verification link to be included in the email.
246
247 The verification link points to a page in your storefront, such as `/verify-account`, which should handle verifying the customer's email when visited.
248
249 ---
250
251 ## Handle Email Verification in Storefront
252
253 When the customer clicks the verification link, they should be directed to a page in your storefront that sends the token back to the Medusa application to verify the customer's email address.
254
255 To learn how to implement this part of the flow, refer to the [Verify Customer Account in Storefront guide](../../../storefront-development/customers/verify-account/page.mdx).
256
257 ---
258
259 ## Example Notification Templates
260
261 The following section provides example notification templates for some Notification Module Providers.
262
263 ### SendGrid
264
265 <Note>
266
267 Refer to the [SendGrid Notification Module Provider](../../../infrastructure-modules/notification/sendgrid/page.mdx) documentation for more details on how to set up SendGrid.
268
269 </Note>
270
271 The following HTML template can be used with SendGrid to send an email verification email:
272
273 ```html
274 <!DOCTYPE html>
275 <html>
276 <head>
277 <meta charset="utf-8">
278 <meta name="viewport" content="width=device-width, initial-scale=1.0">
279 <title>Verify Your Email</title>
280 <style>
281 body {
282 font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif;
283 background-color: #ffffff;
284 margin: 0;
285 padding: 20px;
286 }
287 .container {
288 max-width: 465px;
289 margin: 40px auto;
290 border: 1px solid #eaeaea;
291 border-radius: 5px;
292 padding: 20px;
293 }
294 .header {
295 text-align: center;
296 margin: 30px 0;
297 }
298 .title {
299 color: #000000;
300 font-size: 24px;
301 font-weight: normal;
302 margin: 0;
303 }
304 .content {
305 margin: 32px 0;
306 }
307 .text {
308 color: #000000;
309 font-size: 14px;
310 line-height: 24px;
311 margin: 0 0 16px 0;
312 }
313 .button-container {
314 text-align: center;
315 margin: 32px 0;
316 }
317 .verify-button {
318 background-color: #000000;
319 border-radius: 3px;
320 color: #ffffff;
321 font-size: 12px;
322 font-weight: 600;
323 text-decoration: none;
324 text-align: center;
325 padding: 12px 20px;
326 display: inline-block;
327 }
328 .verify-button:hover {
329 background-color: #333333;
330 }
331 .url-section {
332 margin: 32px 0;
333 }
334 .url-link {
335 color: #2563eb;
336 text-decoration: none;
337 font-size: 14px;
338 line-height: 24px;
339 word-break: break-all;
340 }
341 .disclaimer {
342 margin: 32px 0;
343 }
344 .disclaimer-text {
345 color: #666666;
346 font-size: 12px;
347 line-height: 24px;
348 margin: 0 0 8px 0;
349 }
350 .security-footer {
351 margin-top: 32px;
352 padding-top: 20px;
353 border-top: 1px solid #eaeaea;
354 }
355 .security-text {
356 color: #666666;
357 font-size: 12px;
358 line-height: 24px;
359 margin: 0;
360 }
361 </style>
362 </head>
363 <body>
364 <div class="container">
365 <div class="header">
366 <h1 class="title">Verify Your Email</h1>
367 </div>
368
369 <div class="content">
370 <p class="text">
371 Hello,
372 </p>
373 <p class="text">
374 Thanks for creating an account. Please confirm your email address by clicking the button below to complete your registration.
375 </p>
376 </div>
377
378 <div class="button-container">
379 <a href="{{verification_url}}" class="verify-button">
380 Verify Email
381 </a>
382 </div>
383
384 <div class="url-section">
385 <p class="text">
386 Or copy and paste this URL into your browser:
387 </p>
388 <a href="{{verification_url}}" class="url-link">
389 {{verification_url}}
390 </a>
391 </div>
392
393 <div class="disclaimer">
394 <p class="disclaimer-text">
395 This verification link will expire soon for security reasons.
396 </p>
397 <p class="disclaimer-text">
398 If you didn't create an account, you can safely ignore this email.
399 </p>
400 </div>
401
402 <div class="security-footer">
403 <p class="security-text">
404 For security reasons, never share this verification link with anyone. If you're having trouble with the button above, copy and paste the URL into your web browser.
405 </p>
406 </div>
407 </div>
408 </body>
409 </html>
410 ```
411
412 Make sure to pass the `verification_url` variable to the template, which contains the URL to verify the customer's email.
413
414 You can also customize the template further to show other information.
415
416 ### Resend
417
418 If you've integrated Resend as explained in the [Resend Integration Guide](../../../integrations/guides/resend/page.mdx), you can add a new template for email verification at `src/modules/resend/emails/email-verification.tsx`:
419
420 ```tsx title="src/modules/resend/emails/email-verification.tsx"
421 import {
422 Text,
423 Container,
424 Heading,
425 Html,
426 Section,
427 Tailwind,
428 Head,
429 Preview,
430 Body,
431 Link,
432 Button,
433 } from "@react-email/components"
434
435 type EmailVerificationEmailProps = {
436 verification_url: string
437 }
438
439 function EmailVerificationEmailComponent({ verification_url }: EmailVerificationEmailProps) {
440 return (
441 <Html>
442 <Head />
443 <Preview>Verify your email</Preview>
444 <Tailwind>
445 <Body className="bg-white my-auto mx-auto font-sans px-2">
446 <Container className="border border-solid border-[#eaeaea] rounded my-[40px] mx-auto p-[20px] max-w-[465px]">
447 <Section className="mt-[32px]">
448 <Heading className="text-black text-[24px] font-normal text-center p-0 my-[30px] mx-0">
449 Verify Your Email
450 </Heading>
451 </Section>
452
453 <Section className="my-[32px]">
454 <Text className="text-black text-[14px] leading-[24px]">
455 Hello,
456 </Text>
457 <Text className="text-black text-[14px] leading-[24px]">
458 Thanks for creating an account. Please confirm your email address by clicking the button below to complete your registration.
459 </Text>
460 </Section>
461
462 <Section className="text-center mt-[32px] mb-[32px]">
463 <Button
464 className="bg-[#000000] rounded text-white text-[12px] font-semibold no-underline text-center px-5 py-3"
465 href={verification_url}
466 >
467 Verify Email
468 </Button>
469 </Section>
470
471 <Section className="my-[32px]">
472 <Text className="text-black text-[14px] leading-[24px]">
473 Or copy and paste this URL into your browser:
474 </Text>
475 <Link
476 href={verification_url}
477 className="text-blue-600 no-underline text-[14px] leading-[24px] break-all"
478 >
479 {verification_url}
480 </Link>
481 </Section>
482
483 <Section className="my-[32px]">
484 <Text className="text-[#666666] text-[12px] leading-[24px]">
485 This verification link will expire soon for security reasons.
486 </Text>
487 <Text className="text-[#666666] text-[12px] leading-[24px] mt-2">
488 If you didn't create an account, you can safely ignore this email.
489 </Text>
490 </Section>
491
492 <Section className="mt-[32px] pt-[20px] border-t border-solid border-[#eaeaea]">
493 <Text className="text-[#666666] text-[12px] leading-[24px]">
494 For security reasons, never share this verification link with anyone. If you're having trouble with the button above, copy and paste the URL into your web browser.
495 </Text>
496 </Section>
497 </Container>
498 </Body>
499 </Tailwind>
500 </Html>
501 )
502 }
503
504 export const emailVerificationEmail = (props: EmailVerificationEmailProps) => (
505 <EmailVerificationEmailComponent {...props} />
506 )
507
508 // Mock data for preview/development
509 const mockEmailVerification: EmailVerificationEmailProps = {
510 verification_url: "https://your-app.com/verify-account?token=sample-verification-token-123&email=user@example.com",
511 }
512
513 export default () => <EmailVerificationEmailComponent {...mockEmailVerification} />
514 ```
515
516 Feel free to customize the email template further to match your branding and style, or to add additional information.
517
518 Then, in the Resend Module's service at `src/modules/resend/service.ts`, add the new template to the `templates` object and `Templates` type:
519
520 ```ts title="src/modules/resend/service.ts"
521 // other imports...
522 import { emailVerificationEmail } from "./emails/email-verification"
523
524 enum Templates {
525 // ...
526 EMAIL_VERIFICATION = "email-verification",
527 }
528
529 const templates: {[key in Templates]?: (props: unknown) => React.ReactNode} = {
530 // ...
531 [Templates.EMAIL_VERIFICATION]: emailVerificationEmail,
532 }
533 ```
534
535 Finally, find the `getTemplateSubject` function in the `ResendNotificationProviderService` and add a case for the `EMAIL_VERIFICATION` template:
536
537 ```ts title="src/modules/resend/service.ts"
538 class ResendNotificationProviderService extends AbstractNotificationProviderService {
539 // ...
540
541 private getTemplateSubject(template: Templates) {
542 // ...
543 switch (template) {
544 // ...
545 case Templates.EMAIL_VERIFICATION:
546 return "Verify Your Email"
547 }
548 }
549 }
550 ```
551