Raw
1 ---
2 tags:
3 - customer
4 - storefront
5 - auth
6 products:
7 - customer
8 - auth
9 ---
10
11 import { CodeTabs, CodeTab, Table } from "docs-ui"
12
13 export const metadata = {
14 title: `Login Customer in Storefront`,
15 }
16
17 # {metadata.title}
18
19 In this guide, you'll learn about the two ways to login a customer in your storefront.
20
21 <Note title="Alternative Guides">
22
23 - This guide covers login 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 ## Login Customer Methods
29
30 There are two ways to login a customer in your storefront:
31
32 1. Using a JWT token. This JWT token is obtained from the `/auth/customer/emailpass` API route and is used as a bearer token in the authorization header of all requests.
33 2. Using a cookie session. This method uses the `/auth/session` API route to set the authenticated session ID in the cookies.
34
35 The JS SDK simplifies the login approach in a single `auth.login` method. The upcoming sections explain the authentication approach whether you're using the JS SDK or not.
36
37 ### Which Authentication Method Should You Use?
38
39 The authentication method you choose depends on your use case and the type of storefront you're building.
40
41 Refer to the [JS SDK Authentication](../../../js-sdk/auth/overview/page.mdx) guide to learn more about the differences between JWT and session authentication and which one is best for your use case.
42
43 ### JS SDK Authentication Configuration
44
45 Before implementing the login flow, you need to configure in the JS SDK the authentication method you're using in your storefront. This defines how the JS SDK will handle sending authenticated requests after the customer is authenticated.
46
47 For example, add the following configuration to your JS SDK initialization:
48
49 <Note title="Tip">
50
51 Learn how to install and configure the JS SDK in the [JS SDK documentation](../../../js-sdk/page.mdx).
52
53 </Note>
54
55 <CodeTabs group="authenticated-configuration">
56 <CodeTab label="JWT" value="jwt">
57
58 ```ts
59 export const sdk = new Medusa({
60 // ...
61 auth: {
62 type: "jwt",
63 },
64 })
65 ```
66
67 </CodeTab>
68 <CodeTab label="Session" value="session">
69
70 ```ts
71 export const sdk = new Medusa({
72 // ...
73 auth: {
74 type: "session",
75 },
76 })
77 ```
78
79 </CodeTab>
80 </CodeTabs>
81
82 The JS SDK will now pass the JWT token or the session ID cookie in the authorization header of all subsequent requests based on the authentication method you've configured.
83
84 Refer to the [JS SDK Authentication](../../../js-sdk/auth/overview/page.mdx#custom-authentication-storage-in-js-sdk) guide for more information about these configurations, as well as other authentication configurations.
85
86 <Note title="Tip">
87
88 By default, when you choose the `jwt` method, the JWT token is stored in the browser's `localStorage`. However, you can change how the token is stored, which is useful in environments where `localStorage` is not available. For example, in React Native.
89
90 To learn how to change the storage method with an example for a React Native storefront, refer to the [JS SDK Authentication](../../../js-sdk/auth/overview/page.mdx#custom-authentication-storage-in-js-sdk) guide.
91
92 </Note>
93
94 ---
95
96 ## Authentication with JS SDK
97
98 The JS SDK provides an `auth.login` method that handles all authentication steps based on the configured authentication method. Then, all subsequent requests will have the necessary authentication headers or cookies.
99
100 For example, to implement the login flow in your storefront with the JS SDK:
101
102 <CodeTabs group="store-request">
103 <CodeTab label="React" value="react">
104
105 export const highlights = [
106 ["24", "login", "Send a request to obtain a JWT token."],
107 ["28", "catch", "If an error occurs, show an alert and exit execution."],
108 ["33", "", "If the token is not a string, show an alert and exit execution."],
109 ["39", "retrieve", "Retrieve the customer's details as an example of testing authentication."],
110 ]
111
112 ```tsx highlights={highlights} collapsibleLines="45-69" expandButtonLabel="Show form"
113 "use client" // include with Next.js 13+
114
115 import { useState } from "react"
116 import { sdk } from "@/lib/sdk"
117
118 export default function Login() {
119 const [loading, setLoading] = useState(false)
120 const [email, setEmail] = useState("")
121 const [password, setPassword] = useState("")
122
123 const handleLogin = async (
124 e: React.MouseEvent<HTMLButtonElement, MouseEvent>
125 ) => {
126 e.preventDefault()
127 if (!email || !password) {
128 return
129 }
130
131 setLoading(true)
132
133 let token: string | { location: string }
134
135 try {
136 token = await sdk.auth.login("customer", "emailpass", {
137 email,
138 password,
139 })
140 } catch (error) {
141 alert(`An error occurred while logging in: ${error}`)
142 return
143 }
144
145 if (typeof token !== "string") {
146 alert("Authentication requires more actions, which isn't supported by this flow.")
147 return
148 }
149
150 // all next requests will be authenticated
151 const { customer } = await sdk.store.customer.retrieve()
152
153 console.log(customer)
154 setLoading(false)
155 }
156
157 return (
158 <form>
159 <input
160 type="email"
161 name="email"
162 value={email}
163 placeholder="Email"
164 onChange={(e) => setEmail(e.target.value)}
165 />
166 <input
167 type="password"
168 name="password"
169 value={password}
170 placeholder="Password"
171 onChange={(e) => setPassword(e.target.value)}
172 />
173 <button
174 disabled={loading}
175 onClick={handleLogin}
176 >
177 Login
178 </button>
179 </form>
180 )
181 }
182 ```
183
184 </CodeTab>
185 <CodeTab label="JS SDK" value="js-sdk">
186
187 export const fetchHighlights = [
188 ["5", "login", "Send a request to obtain a JWT token."],
189 ["9", "catch", "If an error occurs, show an alert and exit execution."],
190 ["14", "", "If the token is not a string, show an alert and exit execution."],
191 ["20", "retrieve", "Retrieve the customer's details as an example of testing authentication."],
192 ]
193
194 ```ts highlights={fetchHighlights}
195 const handleLogin = async () => {
196 let token: string | { location: string }
197
198 try {
199 token = await sdk.auth.login("customer", "emailpass", {
200 email,
201 password,
202 })
203 } catch (error) {
204 alert(`An error occurred while logging in: ${error}`)
205 return
206 }
207
208 if (typeof token !== "string") {
209 alert("Authentication requires more actions, which isn't supported by this flow.")
210 return
211 }
212
213 // all next requests will be authenticated
214 const { customer } = await sdk.store.customer.retrieve()
215
216 console.log(customer)
217 }
218 ```
219
220 </CodeTab>
221 </CodeTabs>
222
223 In the example above, you:
224
225 1. Create a `handleLogin` function that logs in a customer.
226 2. In the function, you log in the customer using the `sdk.auth.login` method.
227 - If an error occurs, show an alert and exit execution.
228 - 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.
229 - Otherwise, the authentication was successful.
230 3. All subsequent requests are now authenticated. As an example, you send a request to obtain the logged-in customer's details.
231
232 ---
233
234 ## Authentication without JS SDK
235
236 If you're not using the JS SDK, the next sections cover the general flow for authenticating a customer in your storefront for both methods.
237
238 ## 1. Using a JWT Token
239
240 The first authentication approach is to pass an authenticated JWT token in the authorization header of all requests. You can do that by:
241
242 1. Retrieving a JWT token from the `/auth/customer/emailpass` [Authenticate Customer API route](!api!/store/auth/authenticate-customer):
243
244 ```bash
245 curl -X POST '{backend_url}/auth/customer/emailpass' \
246 -H 'Content-Type: application/json' \
247 --data-raw '{
248 "email": "customer@gmail.com",
249 "password": "supersecret"
250 }'
251 ```
252
253 2. Passing the token in the authorization header of all subsequent requests, as explained in the [API reference](!api!/store#1-bearer-authorization-with-jwt-tokens):
254
255 ```bash
256 Authorization: Bearer {jwt_token}
257 ```
258
259 You can store the obtained JWT token based on your use case. For example, you can store it in the browser's `localStorage` or `sessionStorage`. This way, you can retrieve it later and pass it in the authorization header of all requests.
260
261 ### 2. Using a Cookie Session
262
263 The second authentication approach is to authenticate the customer with a cookie session. You do that by:
264
265 1. Retrieving a JWT token from the `/auth/customer/emailpass` [Authenticate Customer API route](!api!/store/auth/authenticate-customer):
266
267 ```bash
268 curl -X POST '{backend_url}/auth/customer/emailpass' \
269 -H 'Content-Type: application/json' \
270 --data-raw '{
271 "email": "customer@gmail.com",
272 "password": "supersecret"
273 }'
274 ```
275
276 2. Sending a request to the `/auth/session` [Authentication Session API route](!api!/store/auth/set-authentication-session) passing in the authorization header the token as a Bearer token. This sets the authenticated session ID in the cookies:
277
278 ```bash
279 curl -X POST '{backend_url}/auth/session' \
280 -H 'Authorization: Bearer {jwt_token}'
281 ```
282
283 3. Passing the cookie session ID in all subsequent requests:
284
285 <CodeTabs group="request-type">
286 <CodeTab label="cURL" value="curl">
287
288 ```bash
289 curl '{backend_url}/store/products' \
290 -H 'Cookie: connect.sid={sid}'
291 ```
292
293 </CodeTab>
294 <CodeTab label="Fetch" value="fetch">
295
296 ```ts highlights={[["2", "credentials", "Passes the cookie session ID in your request."]]}
297 fetch(`<BACKEND_URL>/store/products`, {
298 credentials: "include",
299 })
300 ```
301
302 </CodeTab>
303
304 </CodeTabs>