1 ---
2 tags:
3 - customer
4 - storefront
5 - auth
6 products:
7 - customer
8 - auth
9 ---
10
11 import { CodeTabs, CodeTab, Prerequisites, Table } from "docs-ui"
12
13 export const metadata = {
14 title: `Register Customer with Email Verification in Storefront`,
15 }
16
17 # {metadata.title}
18
19 In this guide, you'll learn how to implement a customer registration flow with email verification in your storefront.
20
21 <Note>
22
23 If you don't have email verification enabled in the Medusa application, follow the [Register Customer in Storefront](../register/page.mdx) guide instead.
24
25 </Note>
26
27 <Note>
28
29 This guide has been updated since Medusa [v2.16.0](https://github.com/medusajs/medusa/releases/tag/v2.16.0), which made changes to the overall verification flow.
30
31 </Note>
32
33 <Prerequisites
34 items={[
35 {
36 text: "Medusa v2.16.0 or later",
37 link: "!docs!/learn/update"
38 },
39 {
40 text: "Email verification email sending implemented in the Medusa application",
41 link: "/commerce-modules/auth/email-verification"
42 }
43 ]}
44 />
45
46 ## Register Customer with Verification Flow
47
48 By default, Medusa doesn't require email verification for customers. When [email verification is enabled](../../../commerce-modules/auth/email-verification/page.mdx#enable-email-verification), the registration flow is as follows:
49
50 ```mermaid
51 sequenceDiagram
52 actor C as Customer
53 participant S as Storefront
54 participant M as Medusa
55 C->>S: Submit form
56 S->>M: Register
57 M-->>S: Registration token
58 S->>M: Login
59 M-->>S: Verification required
60 S->>M: Request email
61 M->>C: Verification email
62 C->>S: Click link
63 S->>M: Confirm token
64 M-->>S: Verified
65 C->>S: Log in
66 S->>M: Login
67 M-->>S: Token
68 S->>M: Create customer
69 S->>M: Re-login
70 M-->>S: Active token
71 ```
72
73 1. Show the customer a form to enter their details.
74 2. Send a `POST` request to the `/auth/customer/emailpass/register` [Get Registration Token](!api!/store/auth/retrieve-registration-jwt-token) API route to obtain a registration JWT token.
75 3. Request returns a registration JWT token if the registration is successful.
76 4. Redirect customer to login.
77 5. Send a `POST` request to the `/auth/customer/emailpass` [Login Customer](!api!/store/auth/authenticate-customer) API route, passing the registration JWT token in the header.
78 6. Request returns an object indicating that verification is required.
79 7. Send a `POST` request to the `/auth/verification/request` [Request Verification](!api!/store/auth/request-verification) API route to send the verification email to the customer.
80 8. Customer receives the email and clicks the verification link, which is a page in the storefront.
81 9. The verification page sends a `POST` request to the `/auth/verification/confirm` [Confirm Verification](!api!/store/auth/confirm-verification) API route to verify the customer's email using the `token` query parameter in the URL.
82 10. Once the email is verified, the customer can log in.
83 11. During login, if the email is verified but the customer's account is not active, send a request to the [Register Customer API route](!api!/store/customers/register-customer) passing the login JWT token in the header.
84 12. Login the customer again to obtain an active JWT token.
85
86 This guide will cover how to:
87
88 1. Create a registration page with email verification.
89 2. Handle the login flow for customers that need to verify their email.
90 3. Create a verification page that the customer receives in the email.
91
92 ---
93
94 ## Step 1: Create the Registration Page
95
96 The registration page implements steps one to four of the [email verification flow](#register-customer-with-verification-flow). The page shows a form to collect the customer's details, sends a request to the registration API route to obtain a registration token, then redirects the customer to the login page.
97
98 The following example shows the updated registration page:
99
100 <CodeTabs group="store-request">
101 <CodeTab label="React" value="react">
102
103 export const registerHighlights = [
104 ["24", "register", "Register the customer to obtain a registration token."],
105 ["31", "if", "Surface unexpected errors. An existing-identity error is expected and handled below."],
106 ["46", "localStorage.setItem", "Persist the first and last name to use after verification on the login page."],
107 ["51", "", "Redirect the customer to the login page to continue the flow."],
108 ]
109
110 ```tsx highlights={registerHighlights} collapsibleLines="54-92" expandButtonLabel="Show form"
111 "use client" // include with Next.js 13+
112
113 import { useState } from "react"
114 import { sdk } from "@/lib/sdk"
115 import { FetchError } from "@medusajs/js-sdk"
116
117 export default function Register() {
118 const [loading, setLoading] = useState(false)
119 const [firstName, setFirstName] = useState("")
120 const [lastName, setLastName] = useState("")
121 const [email, setEmail] = useState("")
122 const [password, setPassword] = useState("")
123
124 const handleRegistration = async (
125 e: React.MouseEvent<HTMLButtonElement, MouseEvent>
126 ) => {
127 e.preventDefault()
128 if (!firstName || !lastName || !email || !password) {
129 return
130 }
131 setLoading(true)
132
133 try {
134 await sdk.auth.register("customer", "emailpass", {
135 email,
136 password,
137 })
138 } catch (error) {
139 const fetchError = error as FetchError
140
141 if (
142 fetchError.statusText !== "Unauthorized" ||
143 fetchError.message !== "Identity with email already exists"
144 ) {
145 setLoading(false)
146 alert(`An error occurred while creating account: ${fetchError}`)
147 return
148 }
149 // another identity (for example, admin user) exists
150 // with the same email. The customer can still log in
151 // to link a customer record.
152 }
153
154 // persist signup fields so the login page can use them
155 // to create the customer after verification.
156 localStorage.setItem(
157 "pending_customer",
158 JSON.stringify({ email, firstName, lastName })
159 )
160 setLoading(false)
161 // TODO redirect to the login page
162 }
163
164 return (
165 <form>
166 <input
167 type="text"
168 name="first_name"
169 value={firstName}
170 placeholder="First Name"
171 onChange={(e) => setFirstName(e.target.value)}
172 />
173 <input
174 type="text"
175 name="last_name"
176 value={lastName}
177 placeholder="Last Name"
178 onChange={(e) => setLastName(e.target.value)}
179 />
180 <input
181 type="email"
182 name="email"
183 value={email}
184 placeholder="Email"
185 onChange={(e) => setEmail(e.target.value)}
186 />
187 <input
188 type="password"
189 name="password"
190 value={password}
191 placeholder="Password"
192 onChange={(e) => setPassword(e.target.value)}
193 />
194 <button
195 disabled={loading}
196 onClick={handleRegistration}
197 >
198 Register
199 </button>
200 </form>
201 )
202 }
203 ```
204
205 </CodeTab>
206 <CodeTab label="JS SDK" value="js-sdk">
207
208 export const registerSdkHighlights = [
209 ["6", "register", "Register the customer to obtain a registration token."],
210 ["13", "if", "Surface unexpected errors. An existing-identity error is expected and handled below."],
211 ["25", "localStorage.setItem", "Persist the first and last name to use after verification on the login page."],
212 ["29", "", "Redirect the customer to the login page to continue the flow."],
213 ]
214
215 ```ts highlights={registerSdkHighlights}
216 // other imports...
217 import { FetchError } from "@medusajs/js-sdk"
218
219 const handleRegistration = async () => {
220 try {
221 await sdk.auth.register("customer", "emailpass", {
222 email,
223 password,
224 })
225 } catch (error) {
226 const fetchError = error as FetchError
227
228 if (
229 fetchError.statusText !== "Unauthorized" ||
230 fetchError.message !== "Identity with email already exists"
231 ) {
232 alert(`An error occurred while creating account: ${fetchError}`)
233 return
234 }
235 // another identity exists with the same email.
236 // the customer can still log in to link a customer record.
237 }
238
239 // persist signup fields so the login page can use them.
240 localStorage.setItem(
241 "pending_customer",
242 JSON.stringify({ email, firstName, lastName })
243 )
244 // redirect the customer to the login page.
245 }
246 ```
247
248 </CodeTab>
249 </CodeTabs>
250
251 In the above example, you implement the registration flow as follows:
252
253 - Obtain a registration JWT token from the `/auth/customer/emailpass/register` API route using the `auth.register` method. The token isn't usable until the customer verifies their email, which the login page handles.
254 - Persist the customer's first and last name in `localStorage` so that the login page can use them to create the customer after verification.
255 - If an error is thrown:
256 - If the error is an existing identity error, the customer can still continue to the login page to link a customer record. This is useful when another identity, such as an admin user, exists with the same email.
257 - For other errors, show an alert and exit execution.
258 - After registering, redirect the customer to the login page to continue the registration flow.
259
260 The JS SDK automatically stores and re-uses the authentication headers or session in the `auth.register` and `auth.login` methods. So, if you're not using the JS SDK, make sure to pass the received authentication tokens as explained in the [API reference](!api!/store#1-bearer-authorization-with-jwt-tokens).
261
262 ---
263
264 ## Step 2: Create the Login Page
265
266 The login page implements steps five to twelve of the [email verification flow](#register-customer-with-verification-flow). When the customer logs in, if verification is required, request the verification email and prompt the customer to check their inbox.
267
268 After the customer verifies their email and logs in again, if the email is verified but the customer's account is not active, send a request to the [Register Customer API route](!api!/store/customers/register-customer) passing the login JWT token in the header, then log in the customer again to obtain an active JWT token.
269
270 The following example shows the updated login page:
271
272 <CodeTabs group="store-request">
273 <CodeTab label="React" value="react">
274
275 export const loginHighlights = [
276 ["25", "login", "Send a request to obtain a JWT token."],
277 ["34", "if", "Check whether the response indicates that verification is required."],
278 ["37", "request", "Request the verification email to be sent to the customer."],
279 ["42", "alert", "Show a `check your email` message to the customer."],
280 ["54", "decodeToken", "Decode the token to check if the customer is activated."],
281 ["56", "!payload?.actor_id", "Check whether customer is active."],
282 ["59", "localStorage.getItem", "Retrieve the persisted first and last name."],
283 ["62", "create", "Create the customer record using the registration token."],
284 ["73", "login", "Re-login to mint a token with the populated `actor_id`."],
285 ]
286
287 ```tsx highlights={loginHighlights} collapsibleLines="87-105" expandButtonLabel="Show form"
288 "use client" // include with Next.js 13+
289
290 import { useState } from "react"
291 import { sdk } from "@/lib/sdk"
292 import { decodeToken } from "react-jwt"
293
294 export default function Login() {
295 const [loading, setLoading] = useState(false)
296 const [email, setEmail] = useState("")
297 const [password, setPassword] = useState("")
298
299 const handleLogin = async (
300 e: React.MouseEvent<HTMLButtonElement, MouseEvent>
301 ) => {
302 e.preventDefault()
303 if (!email || !password) {
304 return
305 }
306
307 setLoading(true)
308
309 let result: string | { verification_required: boolean } | { location: string }
310
311 try {
312 result = await sdk.auth.login("customer", "emailpass", {
313 email,
314 password,
315 })
316 } catch (error) {
317 alert(`An error occurred while logging in: ${error}`)
318 return
319 }
320
321 if (typeof result === "object" && "verification_required" in result && result.verification_required) {
322 // resend the verification email and route the customer back
323 // to the pending-verification UI.
324 await sdk.auth.verification.request({
325 entity_id: email,
326 entity_type: "email",
327 })
328 setLoading(false)
329 alert(`We sent a verification link to ${email}. Check your inbox.`)
330 return
331 }
332
333 if (typeof result !== "string") {
334 alert(
335 "Authentication requires more actions, which isn't supported by this flow."
336 )
337 return
338 }
339
340 let token = result
341 const payload = decodeToken(token) as { actor_id?: string } | null
342
343 if (!payload?.actor_id) {
344 // link a customer to the auth identity using the registration token.
345 const pending = JSON.parse(
346 localStorage.getItem("pending_customer") || "{}"
347 )
348
349 await sdk.store.customer.create(
350 {
351 email,
352 first_name: pending.firstName,
353 last_name: pending.lastName,
354 },
355 {},
356 { authorization: `Bearer ${token}` }
357 )
358
359 // re-login to mint a token with the populated actor_id.
360 token = (await sdk.auth.login("customer", "emailpass", {
361 email,
362 password,
363 })) as string
364
365 localStorage.removeItem("pending_customer")
366 }
367
368 // all next requests are authenticated.
369 const { customer } = await sdk.store.customer.retrieve()
370 console.log(customer)
371 setLoading(false)
372 }
373
374 return (
375 <form>
376 <input
377 type="email"
378 name="email"
379 value={email}
380 placeholder="Email"
381 onChange={(e) => setEmail(e.target.value)}
382 />
383 <input
384 type="password"
385 name="password"
386 value={password}
387 placeholder="Password"
388 onChange={(e) => setPassword(e.target.value)}
389 />
390 <button
391 disabled={loading}
392 onClick={handleLogin}
393 >
394 Login
395 </button>
396 </form>
397 )
398 }
399 ```
400
401 </CodeTab>
402 <CodeTab label="JS SDK" value="js-sdk">
403
404 export const loginSdkHighlights = [
405 ["7", "login", "Send a request to obtain a JWT token."],
406 ["16", "if", "Check whether the response indicates that verification is required."],
407 ["17", "request", "Request the verification email to be sent to the customer."],
408 ["21", "alert", "Show a `check your email` message to the customer."],
409 ["31", "decodeToken", "Decode the token to check if the customer is activated."],
410 ["33", "!payload?.actor_id", "Check whether customer is active."],
411 ["35", "localStorage.getItem", "Retrieve the persisted first and last name."],
412 ["38", "create", "Create the customer record using the registration token."],
413 ["48", "login", "Re-login to mint a token with the populated `actor_id`."],
414 ]
415
416 ```ts highlights={loginSdkHighlights}
417 import { decodeToken } from "react-jwt"
418
419 const handleLogin = async () => {
420 let result: string | { verification_required: boolean } | { location: string }
421
422 try {
423 result = await sdk.auth.login("customer", "emailpass", {
424 email,
425 password,
426 })
427 } catch (error) {
428 alert(`An error occurred while logging in: ${error}`)
429 return
430 }
431
432 if (typeof result === "object" && "verification_required" in result && result.verification_required) {
433 await sdk.auth.verification.request({
434 entity_id: email,
435 entity_type: "email",
436 })
437 alert(`We sent a verification link to ${email}. Check your inbox.`)
438 return
439 }
440
441 if (typeof result !== "string") {
442 alert("Authentication requires more actions, which isn't supported by this flow.")
443 return
444 }
445
446 let token = result
447 const payload = decodeToken(token) as { actor_id?: string } | null
448
449 if (!payload?.actor_id) {
450 const pending = JSON.parse(
451 localStorage.getItem("pending_customer") || "{}"
452 )
453
454 await sdk.store.customer.create(
455 {
456 email,
457 first_name: pending.firstName,
458 last_name: pending.lastName,
459 },
460 {},
461 { authorization: `Bearer ${token}` }
462 )
463
464 token = (await sdk.auth.login("customer", "emailpass", {
465 email,
466 password,
467 })) as string
468
469 localStorage.removeItem("pending_customer")
470 }
471
472 const { customer } = await sdk.store.customer.retrieve()
473 console.log(customer)
474 }
475 ```
476
477 </CodeTab>
478 </CodeTabs>
479
480 In the example above, you:
481
482 1. Create a `handleLogin` function that logs in a customer.
483 2. In the function, you log in the customer using the `sdk.auth.login` method.
484 - If the response indicates that verification is required, resend the verification email and show a "check your email" message.
485 - If an error occurs, show an alert and exit execution.
486 - The method may return an object with a `location` property. This occurs when using third-party authentication providers. Learn more about implementing third-party authentication in the [Third-Party Login](../third-party-login/page.mdx) guide.
487 - If the response is a token string, decode it to check if the `actor_id` is present.
488 - If it's not present, it means that the customer record hasn't been created yet, so you create it using the registration token, then log in again to mint a token with the populated `actor_id`.
489 3. If no errors occur, all subsequent requests are now authenticated. As an example, you send a request to obtain the logged-in customer's details.
490
491 <Note title="Why re-login instead of `sdk.auth.refresh`?">
492
493 The post-register token's `actor_id` is empty, and `sdk.auth.refresh` can return another empty-`actor_id` token or fail. A fresh login after the customer is linked is guaranteed to produce a valid token.
494
495 </Note>
496
497 ### Persisting Extra Signup Fields
498
499 Because customer creation is deferred to first login, any extra fields you collect at registration (`first_name`, `last_name`, `phone`, and so on) need to survive until then. You have two options:
500
501 - **Option A (simplest):** Only collect `email` and `password` at signup. Collect the rest on a "complete your profile" page after first login.
502 - **Option B:** Persist the extra fields temporarily and read them in the login flow before calling `customer.create`. The example in this guide uses Option B with `localStorage`, which works across tabs.
503
504 If you keep the extra fields in component state only, they are lost the moment the customer closes the tab to open their email. Persist to `localStorage` (or a similar storage) before showing the pending-verification UI.
505
506 ### Handle Verification with Server Actions and Session Authentication
507
508 If you implement the login flow in a server action using session-based authentication, the session cookie set by the `/auth/session` API route isn't persisted between calls in the same server action. So, when the login response indicates that verification is required, you must pass the token returned in that response manually as a bearer token in the `Authorization` header when requesting the verification email.
509
510 For example, where `token` is the response of the `sdk.auth.login` method:
511
512 ```ts
513 if (typeof token === "object" && token.verification_required) {
514 // In a server action there's no cookie jar, so a
515 // session cookie set by /auth/session wouldn't carry
516 // over to the next request. Pass the actorless token
517 // returned from login directly as a bearer token to
518 // authenticate the verification request instead.
519 await sdk.client.fetch("/auth/verification/request", {
520 method: "POST",
521 headers: {
522 Authorization: `Bearer ${token.token}`,
523 },
524 body: {
525 entity_id: email,
526 entity_type: "email",
527 code_provider: "token",
528 },
529 })
530
531 return { verification_required: true }
532 }
533 ```
534
535 This guide's examples are otherwise client-side and rely on `localStorage` and the JS SDK's automatic token storage. If your storefront uses session-based authentication (like the official Next.js starter), make sure the session cookie is persisted between requests. The bearer-token caveat above applies anywhere you request a verification email, including the resend flow that runs after an unverified login.
536
537 ---
538
539 ## Step 3: Create the Verify Account Page
540
541 Next, create a page in your storefront at the path that the verification link points to (for example, `/verify-account`). The page reads the `token` from the query string and sends it to the [Confirm Verification API route](!api!/store/auth/confirm-verification) to verify the customer's email.
542
543 For example, create the page at `src/app/verify-account/page.tsx` with the following content:
544
545 <CodeTabs group="store-request">
546 <CodeTab label="React" value="react">
547
548 export const verifyHighlights = [
549 ["8", "useSearchParams", "Read the token from the query string."],
550 ["22", "confirm", "Verify the customer's email."],
551 ]
552
553 ```tsx highlights={verifyHighlights}
554 "use client"
555
556 import { useEffect, useState } from "react"
557 import { useSearchParams, useRouter } from "next/navigation"
558 import { sdk } from "@/lib/sdk"
559
560 export default function VerifyAccount() {
561 const searchParams = useSearchParams()
562 const router = useRouter()
563 const token = searchParams.get("token")
564 const [state, setState] = useState<"verifying" | "success" | "error">(
565 "verifying"
566 )
567
568 useEffect(() => {
569 if (!token) {
570 setState("error")
571 return
572 }
573
574 sdk.auth.verification
575 .confirm({ code: token })
576 .then(() => setState("success"))
577 .catch(() => setState("error"))
578 }, [token])
579
580 if (state === "verifying") {
581 return <div>Verifying your email...</div>
582 }
583
584 if (state === "success") {
585 return (
586 <div>
587 <p>Your email is verified. You can now log in.</p>
588 <button onClick={() => router.push("/login")}>Go to login</button>
589 </div>
590 )
591 }
592
593 return (
594 <div>
595 <p>
596 The verification link is invalid or has expired. Log in
597 again to receive a new verification email.
598 </p>
599 <button onClick={() => router.push("/login")}>Go to login</button>
600 </div>
601 )
602 }
603 ```
604
605 </CodeTab>
606 <CodeTab label="JS SDK" value="js-sdk">
607
608 export const verifySdkHighlights = [
609 ["3", "URLSearchParams", "Read the token from the query string."],
610 ["13", "confirm", "Verify the customer's email."],
611 ]
612
613 ```ts highlights={verifySdkHighlights}
614 import { sdk } from "@/lib/sdk"
615
616 const searchParams = new URLSearchParams(window.location.search)
617 const token = searchParams.get("token")
618
619 const handleVerification = async () => {
620 if (!token) {
621 alert("Invalid verification link.")
622 return
623 }
624
625 try {
626 await sdk.auth.verification.confirm({ code: token })
627 alert("Email verified. You can now log in.")
628 } catch (error) {
629 alert(
630 "The link is invalid or has expired. Log in again to get a new email."
631 )
632 }
633 }
634 ```
635
636 </CodeTab>
637 </CodeTabs>
638
639 You add handling for three states in the verification page:
640
641 - `verifying`: The page is verifying the token by sending a request to the Medusa application.
642 - `success`: The token is verified. The customer can now log in.
643 - `error`: The token is invalid or expired. The customer is directed back to the login page to receive a new verification email.
644
645 When the page loads, the `useEffect` hook reads the `token` from the query string and sends it to the `sdk.auth.verification.confirm` method. If the request succeeds, the state is set to `success`. Otherwise, it's set to `error`.