1 ---
2 tags:
3 - customer
4 - storefront
5 - auth
6 products:
7 - customer
8 - auth
9 ---
10
11 import { CodeTabs, CodeTab } from "docs-ui"
12
13 export const metadata = {
14 title: `Register Customer in Storefront`,
15 }
16
17 # {metadata.title}
18
19 In this guide, you'll learn how to register a customer in your storefront.
20
21 <Note title="Alternative Guides">
22
23 - This guide covers registration using email and password. For authentication with third-party providers, refer to the [Third-Party Login](../third-party-login/page.mdx) guide.
24 - If you have email verification enabled, refer to the [Verify Account](../verify-account/page.mdx) guide instead.
25
26 </Note>
27
28 ## Register Customer Flow
29
30 To register a customer, you implement the following steps:
31
32 ![A diagram illustrating the flow of the register customer flow](https://res.cloudinary.com/dza7lstvk/image/upload/v1743086184/Medusa%20Resources/register-flow_yv5uw2.jpg)
33
34 1. Show the customer a form to enter their details.
35 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.
36 3. Send a request to the [Register Customer API route](!api!/store/customers/register-customer) passing the registration JWT token in the header.
37
38 However, a customer may enter an email that's already used either by an admin user, another customer, or a [custom actor type](../../../commerce-modules/auth/auth-identity-and-actor-types/page.mdx). To handle this scenario:
39
40 - Try to obtain a login token by sending a `POST` request to the `/auth/customer/emailpass` [Authenticate Customer](!api!/store/auth/authenticate-customer) API route. The customer is only allowed to register if their email and password match the existing identity. This allows admin users to log in or register as customers.
41 - If you obtained the login token successfully, register the customer using the login JWT token instead of the registration token. This will not remove the existing identity. So, for example, an admin user can also become a customer.
42
43 When you're using the JS SDK, this flow is simplified with quick registration and login methods. The rest of this guide uses the JS SDK to demonstrate the registration flow. However, if you're not using the JS SDK, you can still implement the same flow using the API routes.
44
45 <Note title="Tip">
46
47 Learn how to install and configure the JS SDK in the [JS SDK documentation](../../../js-sdk/page.mdx).
48
49 </Note>
50
51 ---
52
53 ## How to Implement the Register Customer Flow
54
55 An example implementation of the registration flow in a storefront:
56
57 <CodeTabs group="store-request">
58 <CodeTab label="React" value="react">
59
60 export const highlights = [
61 ["24", "register", "Send a request to set the registration token in the JS SDK."],
62 ["28", "catch", "Maybe another identity exists with the same email."],
63 ["31", "", "If an unexpected error occurs, exit the flow."],
64 ["38", "login", "Try to obtain a login JWT token."],
65 ["41", "catch", "The existing account belongs to another customer, so authentication failed."],
66 ["57", "create", "Send a request to create the customer."],
67 ["66", "TODO", "Redirect the customer to the log in page."],
68 ["67", "catch", "Handle registration failure"],
69 ]
70
71 ```tsx highlights={highlights} collapsibleLines="74-112" expandButtonLabel="Show form"
72 "use client" // include with Next.js 13+
73
74 import { useState } from "react"
75 import { sdk } from "@/lib/sdk"
76 import { FetchError } from "@medusajs/js-sdk"
77
78 export default function Register() {
79 const [loading, setLoading] = useState(false)
80 const [firstName, setFirstName] = useState("")
81 const [lastName, setLastName] = useState("")
82 const [email, setEmail] = useState("")
83 const [password, setPassword] = useState("")
84
85 const handleRegistration = async (
86 e: React.MouseEvent<HTMLButtonElement, MouseEvent>
87 ) => {
88 e.preventDefault()
89 if (!firstName || !lastName || !email || !password) {
90 return
91 }
92 setLoading(true)
93
94 try {
95 await sdk.auth.register("customer", "emailpass", {
96 email,
97 password,
98 })
99 } catch (error) {
100 const fetchError = error as FetchError
101
102 if (fetchError.statusText !== "Unauthorized" || fetchError.message !== "Identity with email already exists") {
103 alert(`An error occurred while creating account: ${fetchError}`)
104 return
105 }
106 // another identity (for example, admin user)
107 // exists with the same email. So, use the auth
108 // flow to login and create a customer.
109 const loginResponse = (await sdk.auth.login("customer", "emailpass", {
110 email,
111 password,
112 }).catch((e) => {
113 alert(`An error occurred while creating account: ${e}`)
114 }))
115
116 if (!loginResponse) {
117 return
118 }
119
120 if (typeof loginResponse !== "string") {
121 alert("Authentication requires more actions, which isn't supported by this flow.")
122 return
123 }
124 }
125
126 // create customer
127 try {
128 const { customer } = await sdk.store.customer.create({
129 first_name: firstName,
130 last_name: lastName,
131 email,
132 })
133
134 setLoading(false)
135
136 console.log(customer)
137 // TODO redirect to login page
138 } catch (error) {
139 console.error(error)
140 alert("Error: " + error)
141 return
142 }
143 }
144
145 return (
146 <form>
147 <input
148 type="text"
149 name="first_name"
150 value={firstName}
151 placeholder="First Name"
152 onChange={(e) => setFirstName(e.target.value)}
153 />
154 <input
155 type="text"
156 name="last_name"
157 value={lastName}
158 placeholder="Last Name"
159 onChange={(e) => setLastName(e.target.value)}
160 />
161 <input
162 type="email"
163 name="email"
164 value={email}
165 placeholder="Email"
166 onChange={(e) => setEmail(e.target.value)}
167 />
168 <input
169 type="password"
170 name="password"
171 value={password}
172 placeholder="Password"
173 onChange={(e) => setPassword(e.target.value)}
174 />
175 <button
176 disabled={loading}
177 onClick={handleRegistration}
178 >
179 Register
180 </button>
181 </form>
182 )
183 }
184 ```
185
186 </CodeTab>
187 <CodeTab label="JS SDK" value="js-sdk">
188
189 export const fetchHighlights = [
190 ["7", "register", "Send a request to obtain a registration JWT token."],
191 ["11", "catch", "Maybe another identity exists with the same email."],
192 ["21", "login", "Try to obtain a login JWT token."],
193 ["24", "catch", "The existing account belongs to another customer, so authentication failed."],
194 ["40", "create", "Send a request to register the customer."],
195 ["47", "TODO", "Redirect the customer to the log in page."],
196 ["48", "catch", "Handle registration failure"],
197 ]
198
199 ```ts highlights={fetchHighlights}
200 // other imports...
201 import { FetchError } from "@medusajs/js-sdk"
202
203 const handleRegistration = async () => {
204 // obtain registration JWT token
205 try {
206 await sdk.auth.register("customer", "emailpass", {
207 email,
208 password,
209 })
210 } catch (error) {
211 const fetchError = error as FetchError
212
213 if (fetchError.statusText !== "Unauthorized" || fetchError.message !== "Identity with email already exists") {
214 alert(`An error occurred while creating account: ${fetchError}`)
215 return
216 }
217 // another identity (for example, admin user)
218 // exists with the same email. So, use the auth
219 // flow to login and register a customer.
220 const loginResponse = (await sdk.auth.login("customer", "emailpass", {
221 email,
222 password,
223 }).catch((e) => {
224 alert(`An error occurred while creating account: ${e}`)
225 }))
226
227 if (!loginResponse) {
228 return
229 }
230
231 if (typeof loginResponse !== "string") {
232 alert("Authentication requires more actions, which isn't supported by this flow.")
233 return
234 }
235 }
236
237 // register customer
238 try {
239 const { customer } = await sdk.store.customer.create({
240 first_name: firstName,
241 last_name: lastName,
242 email,
243 })
244
245 console.log(customer)
246 // TODO redirect to login page
247 } catch (error) {
248 console.error(error)
249 alert("Error: " + error)
250 return
251 }
252 }
253 ```
254
255 </CodeTab>
256 </CodeTabs>
257
258 In the above example, you create a `handleRegistration` function that:
259
260 - Obtains a registration JWT token from the `/auth/customer/emailpass/register` API route using the `auth.register` method. If an error is thrown:
261 - If the error is an existing identity error, try retrieving the login JWT token from `/auth/customer/emailpass` API route using the `auth.login` method. This will fail if the existing identity has a different password, which doesn't allow the customer from registering.
262 - For other errors, show an alert and exit execution.
263 - The JS SDK automatically stores an 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)
264 - Send a request to the [Register Customer API route](!api!/store/customers/register-customer) to register the customer in Medusa.
265 - If an error occurs, show an alert and exit execution.
266 - As mentioned, the JS SDK automatically sends the authentication headers or session in all requests after registration or logging in. 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).
267 - Once the customer is registered successfully, you can either redirect the customer to the login page or log them in automatically, as explained in the [Login](../login/page.mdx) guide.
268