Raw
1 ---
2 tags:
3 - customer
4 - storefront
5 - auth
6 products:
7 - customer
8 - auth
9 ---
10
11 import { Prerequisites, CodeTabs, CodeTab, Details } from "docs-ui"
12
13 export const metadata = {
14 title: `Third-Party or Social Login in Storefront`,
15 }
16
17 # {metadata.title}
18
19 In this guide, you'll learn how to implement third-party or social login in your storefront. You'll implement the flow using Google as an example.
20
21 ## Summary
22
23 By following the steps in this guide, you'll learn how to:
24
25 - Create a login page with a button that starts the third-party login process. This redirects customers to the third-party service for authentication.
26 - Create a callback page that the third-party service redirects to after authentication. This page receives query parameters from the third-party service and uses them to validate the authentication in Medusa.
27
28 These are the pages you need in your storefront to allow customers to log in or create an account using a third-party service.
29
30 ![Diagram with a summary of the third-party login flow in the storefront.](https://res.cloudinary.com/dza7lstvk/image/upload/v1758108102/third-party-storefront-summary_z1h5hx.jpg)
31
32 <Prerequisites
33 items={[
34 {
35 text: "Google OAuth credentials configured. This is required for using the Google Auth Module Provider.",
36 },
37 {
38 text: "Install the Google Auth Module Provider in your Medusa application, or the provider you're using.",
39 link: "/commerce-modules/auth/auth-providers/google"
40 },
41 {
42 text: "JS SDK installed and configured in your storefront, with the authentication method you're using (JWT or session) configured.",
43 link: "../login/page.mdx#login-customer-methods"
44 }
45 ]}
46 />
47
48 ## Step 1: Login Button in Storefront
49
50 In your storefront, you'll have a login page with different login options. One of those options will be a button that starts the third-party login process. For example, a "Login with Google" button.
51
52 When the customer clicks the "Login with Google" button, send a request to the [Authenticate Customer API route](!api!/store/auth/authenticate-customer). This returns the URL to redirect the customer to Google for authentication.
53
54 For example:
55
56 <Note title="Tip">
57
58 Learn how to install and configure the JS SDK in the [JS SDK documentation](../../../js-sdk/page.mdx).
59
60 </Note>
61
62 <CodeTabs group="authenticated-request">
63 <CodeTab label="React" value="react">
64
65 export const reactHighlights = [
66 ["7", "login", "Send a request to the Authenticate Customer API route"],
67 ["9", "result.location", "If the request returns a location, redirect to that location to continue the authentication"],
68 ["16", "", "If the token isn't returned, the authentication has failed"],
69 ["24", "retrieve", "Retrieve the customer's details as an example of testing authentication"]
70 ]
71
72 ```tsx highlights={reactHighlights}
73 "use client" // include with Next.js 13+
74
75 import { sdk } from "@/lib/sdk"
76
77 export default function Login() {
78 const loginWithGoogle = async () => {
79 const result = await sdk.auth.login("customer", "google", {})
80
81 if (typeof result === "object" && result.location) {
82 // redirect to Google for authentication
83 window.location.href = result.location
84
85 return
86 }
87
88 if (typeof result !== "string") {
89 // result failed, show an error
90 alert("Authentication failed")
91 return
92 }
93
94 // Customer was previously authenticated, and its token is now stored in the JS SDK.
95 // all subsequent requests are authenticated
96 const { customer } = await sdk.store.customer.retrieve()
97
98 console.log(customer)
99 }
100
101 return (
102 <div>
103 <button onClick={loginWithGoogle}>Login with Google</button>
104 </div>
105 )
106 }
107 ```
108
109 </CodeTab>
110 <CodeTab label="JS SDK" value="js-sdk">
111
112 export const jsSdkHighlights = [
113 ["2", "login", "Send a request to the Authenticate Customer API route"],
114 ["4", "", "If the request returns a location, redirect to that location to continue the authentication"],
115 ["11", "", "If the token isn't returned, the authentication has failed"],
116 ["19", "retrieve", "Retrieve the customer's details as an example of testing authentication"]
117 ]
118
119 ```ts highlights={jsSdkHighlights}
120 const loginWithGoogle = async () => {
121 const result = await sdk.auth.login("customer", "google", {})
122
123 if (typeof result === "object" && result.location) {
124 // redirect to Google for authentication
125 window.location.href = result.location
126
127 return
128 }
129
130 if (typeof result !== "string") {
131 // result failed, show an error
132 alert("Authentication failed")
133 return
134 }
135
136 // Customer was previously authenticated, and its token is now stored in the JS SDK.
137 // all subsequent requests are authenticated
138 const { customer } = await sdk.store.customer.retrieve()
139
140 console.log(customer)
141 }
142 ```
143
144 </CodeTab>
145 </CodeTabs>
146
147 You define a `loginWithGoogle` function that:
148
149 - Sends a request to the `/auth/customer/google` API route using the JS SDK's `auth.login` method.
150 - If you're using a provider other than Google, replace `google` in the `login` method with your provider ID.
151 - If the response is an object with a `location` property, redirect to the returned page for authentication with the third-party service.
152 - If the response is not an object or a string, the authentication has failed.
153 - If the response is a string, it's the customer's authentication token. This means the customer has been authenticated before.
154 - All subsequent requests by the JS SDK are now authenticated. As an example, you can retrieve the customer's details using the `store.customer.retrieve` method.
155
156 <Note title="Tip">
157
158 The JS SDK sets and passes authentication headers or session cookies automatically based on your [configured authentication method](../../../js-sdk/auth/overview/page.mdx). If you're not using the JS SDK, make sure to pass the necessary headers in your request as explained in the [API reference](!api!/store/authentication).
159
160 </Note>
161
162 ---
163
164 ## Step 2: Callback Page in Storefront
165
166 After the customer clicks the "Login with Google" button, they're redirected to Google to authenticate. Once they authenticate with Google, they're redirected back to your storefront to the callback page. You set this page's URL in Google's OAuth credentials configurations.
167
168 ![Google OAuth credentials settings showing the Redirect URI field](https://res.cloudinary.com/dza7lstvk/image/upload/v1758106535/CleanShot_2025-09-17_at_13.55.18_2x_baalfu.png)
169
170 In this step, you'll create the callback page that handles the response from Google and creates or retrieves the customer account. You'll implement the page step-by-step to explain the different parts of the flow. You can copy the full page code from the [Full Code Example for Third-Party Login Callback Page](#full-code-example-for-third-party-login-callback-page) section.
171
172 ### a. Install the React-JWT Library
173
174 First, install the [react-jwt library](https://www.npmjs.com/package/react-jwt) in your storefront:
175
176 ```bash npm2yarn
177 npm install react-jwt
178 ```
179
180 You'll use it to decode the token that Medusa returns after validating the authentication callback.
181
182 ### b. Implement the Callback Page
183
184 Then, create a new page in your storefront that will be used as the callback/redirect URI destination:
185
186 <CodeTabs group="authenticated-request">
187 <CodeTab label="React" value="react">
188
189 export const sendCallbackReactHighlights = [
190 ["12", "queryParams", "The query parameters received from Google, such as `code` and `state`"],
191 ["21", "callback", "Send a request to the Validate Authentication Callback API route"],
192 ["28", "catch", "If an error occurs, show an alert and exit execution"]
193 ]
194
195 ```tsx highlights={sendCallbackReactHighlights}
196 "use client" // include with Next.js 13+
197
198 import { HttpTypes } from "@medusajs/types"
199 import { useEffect, useMemo, useState } from "react"
200 import { decodeToken } from "react-jwt"
201 import { sdk } from "@/lib/sdk"
202
203 export default function GoogleCallback() {
204 const [loading, setLoading] = useState(true)
205 const [customer, setCustomer] = useState<HttpTypes.StoreCustomer>()
206 // for other than Next.js
207 const queryParams = useMemo(() => {
208 const searchParams = new URLSearchParams(window.location.search)
209 return Object.fromEntries(searchParams.entries())
210 }, [])
211
212 const sendCallback = async () => {
213 let token = ""
214
215 try {
216 token = await sdk.auth.callback(
217 "customer",
218 "google",
219 // pass all query parameters received from the
220 // third party provider
221 queryParams
222 )
223 } catch (error) {
224 alert("Authentication Failed")
225
226 throw error
227 }
228
229 return token
230 }
231
232 // TODO add more functions
233
234 return (
235 <div>
236 {loading && <span>Loading...</span>}
237 {customer && <span>Created customer {customer.email} with Google.</span>}
238 </div>
239 )
240 }
241 ```
242
243 </CodeTab>
244 <CodeTab label="JS SDK" value="js-sdk">
245
246 export const sendCallbackFetchHighlights = [
247 ["6", "queryParams", "The query parameters received from Google, such as `code` and `state`"],
248 ["12", "callback", "Send a request to the Validate Authentication Callback API route"],
249 ["19", "catch", "If an error occurs, show an alert and exit execution"]
250 ]
251
252 ```ts highlights={sendCallbackFetchHighlights}
253 import { decodeToken } from "react-jwt"
254
255 // ...
256
257 const searchParams = new URLSearchParams(window.location.search)
258 const queryParams = Object.fromEntries(searchParams.entries())
259
260 const sendCallback = async () => {
261 let token = ""
262
263 try {
264 token = await sdk.auth.callback(
265 "customer",
266 "google",
267 // pass all query parameters received from the
268 // third party provider
269 queryParams
270 )
271 } catch (error) {
272 alert("Authentication Failed")
273
274 throw error
275 }
276
277 return token
278 }
279
280 // TODO add more functions...
281 ```
282
283 </CodeTab>
284 </CodeTabs>
285
286 You add a new page. In the page's component, you define the `sendCallback` function that sends a request to the [Validate Callback API route](!api!/store/auth/validate-authentication-callback), passing it all query parameters received from Google. These include the `code` and `state` parameters.
287
288 <Note title="Tip">
289
290 The JS SDK stores the JWT token returned by the Validate Callback API route automatically. It attaches this token to subsequent requests. If you're building this authentication flow without the JS SDK, you need to pass it manually to the next requests.
291
292 </Note>
293
294 ### c. Create Customer Function
295
296 Next, you'll add to the page a function that creates a customer. You'll use this function if the customer is authenticating with the third-party service for the first time.
297
298 Replace the `TODO` after the `sendCallback` function with the following:
299
300 export const createCustomerHighlights = [
301 ["3", "create", "Create a customer"]
302 ]
303
304 ```ts highlights={createCustomerHighlights} title="JS SDK / React Applicable"
305 const createCustomer = async (email: string) => {
306 // create customer
307 await sdk.store.customer.create({
308 email,
309 })
310 }
311
312 // TODO add more functions...
313 ```
314
315 You add the function `createCustomer` which creates a customer when this is the first time the customer is authenticating with the third-party service.
316
317 <Note title="Tip">
318
319 This method assumes that the token received from the [Validate Callback API route](!api!/store/auth/validate-authentication-callback) is already set in the JS SDK. So, if you're implementing this flow without using the JS SDK, make sure to pass the token received from the [Validate Callback API route](!api!/store/auth/validate-authentication-callback) in the [authorization Bearer header](!api!/store/authentication).
320
321 </Note>
322
323 ### d. Refresh Token Function
324
325 Next, you'll add to the page a function that refreshes the authentication token after creating the customer. This is necessary to ensure that the token includes the created customer's details.
326
327 Replace the new `TODO` with the following:
328
329 export const refreshTokenHighlights = [
330 ["3", "refresh", "Fetch a new token for the created customer"]
331 ]
332
333 ```ts highlights={refreshTokenHighlights} title="JS SDK / React Applicable"
334 const refreshToken = async () => {
335 // refresh the token
336 const result = await sdk.auth.refresh()
337 }
338
339 // TODO add more functions...
340 ```
341
342 You add the function `refreshToken` that sends a request to the [Refresh Token API route](!api!/store/auth/refresh-authentication-token) to retrieve a new token for the created customer.
343
344 The `refreshToken` method also updates the token stored by the JS SDK, ensuring that subsequent requests use that token.
345
346 <Note title="Tip">
347
348 This method assumes that the token received from the [Validate Callback API route](!api!/store/auth/validate-authentication-callback) is already set in the JS SDK. So, if you're implementing this flow without using the JS SDK, make sure to pass the token in the [authorization Bearer header](!api!/store/authentication). Make sure to also update the token stored in your application after refreshing it.
349
350 </Note>
351
352 ### e. Validate Callback Function
353
354 Finally, you'll add to the page a function that validates the authentication callback in Medusa and creates or retrieves the customer account. It will use the functions added earlier.
355
356 Add in the place of the new `TODO` the `validateCallback` function that runs when the page first loads to validate the authentication:
357
358 export const validateReactHighlights = [
359 ["2", "sendCallback", "Validate the callback in Medusa and retrieve the authentication token"],
360 ["6", "shouldCreateCustomer", "Check if the decoded token has an `actor_id` property to decide whether a customer needs to be created"],
361 ["9", "createCustomer", "Create a customer if the decoded token doesn't have `actor_id`"],
362 ["11", "refreshToken", "Fetch a new token for the created customer"],
363 ["15", "retrieve", "Retrieve the customer's details as an example of testing authentication"]
364 ]
365
366 ```tsx highlights={validateReactHighlights}
367 const validateCallback = async () => {
368 const token = await sendCallback()
369
370 const decodedToken = decodeToken(token) as { actor_id: string, user_metadata: Record<string, unknown> }
371
372 const shouldCreateCustomer = decodedToken.actor_id === ""
373
374 if (shouldCreateCustomer) {
375 await createCustomer(decodedToken.user_metadata.email as string)
376
377 await refreshToken()
378 }
379
380 // use token to send authenticated requests
381 const { customer: customerData } = await sdk.store.customer.retrieve()
382
383 setCustomer(customerData)
384 setLoading(false)
385 }
386
387 // TODO run validateCallback when the page loads
388 ```
389
390 The `validateCallback` function uses the functions added earlier to implement the following flow:
391
392 1. Send a request to the [Validate Callback API route](!api!/store/auth/validate-authentication-callback). This returns an authentication token.
393 - The `sendCallback` function also sets the token in the JS SDK. This passes the token in subsequent requests.
394 2. Decode the token to check if it has an `actor_id` property.
395 - If the property exists, the customer is already registered. The authentication token can be used for subsequent authenticated requests.
396 - If the property doesn't exist, this is the first time the customer is authenticating with the third-party service. So:
397 1. Create a customer. The `user_metadata` in the decoded token will hold the customer's information in the third-party provider, such as their `email`. You can use this value as the customer's email in Medusa.
398 2. Refetch the customer's authentication token.
399 3. Use the token for subsequent authenticated requests.
400 3. Retrieve the customer's details as an example of testing authentication.
401
402 ### f. Run the Callback Validation on Page Load
403
404 Finally, you need to run the `validateCallback` function when the page first loads. In React, you can do that using the `useEffect` hook.
405
406 For example, replace the last `TODO` with the following:
407
408 ```tsx
409 useEffect(() => {
410 if (!loading) {
411 return
412 }
413
414 validateCallback()
415 }, [loading])
416 ```
417
418 This runs the `validateCallback` function when the page first loads. If the validation is successful, the customer is authenticated.
419
420 You can show a success message or redirect the customer to another page. For example, use another `useEffect` hook to redirect the customer to the homepage after successful authentication:
421
422 ```tsx
423 useEffect(() => {
424 if (!customer) {
425 return
426 }
427
428 // redirect to homepage after successful authentication
429 window.location.href = "/"
430 }, [customer])
431 ```
432
433 ### Full Code Example for Third-Party Login Callback Page
434
435 <CodeTabs group="authenticated-request">
436 <CodeTab label="React" value="react">
437
438 ```tsx
439 "use client" // include with Next.js 13+
440
441 import { HttpTypes } from "@medusajs/types"
442 import { useEffect, useMemo, useState } from "react"
443 import { decodeToken } from "react-jwt"
444 import { sdk } from "@/lib/sdk"
445
446 export default function GoogleCallback() {
447 const [loading, setLoading] = useState(true)
448 const [customer, setCustomer] = useState<HttpTypes.StoreCustomer>()
449 // for other than Next.js
450 const queryParams = useMemo(() => {
451 const searchParams = new URLSearchParams(window.location.search)
452 return Object.fromEntries(searchParams.entries())
453 }, [])
454
455 const sendCallback = async () => {
456 let token = ""
457
458 try {
459 token = await sdk.auth.callback(
460 "customer",
461 "google",
462 // pass all query parameters received from the
463 // third party provider
464 queryParams
465 )
466 } catch (error) {
467 alert("Authentication Failed")
468
469 throw error
470 }
471
472 return token
473 }
474
475 const createCustomer = async () => {
476 // create customer
477 await sdk.store.customer.create({
478 email: "example@medusajs.com",
479 })
480 }
481
482 const refreshToken = async () => {
483 // refresh the token
484 const result = await sdk.auth.refresh()
485 }
486
487 const validateCallback = async () => {
488 const token = await sendCallback()
489
490 const decodedToken = decodeToken(token) as { actor_id: string, user_metadata: Record<string, unknown> }
491
492 const shouldCreateCustomer = decodedToken.actor_id === ""
493
494 if (shouldCreateCustomer) {
495 await createCustomer(decodedToken.user_metadata.email as string)
496
497 await refreshToken()
498 }
499
500 // use token to send authenticated requests
501 const { customer: customerData } = await sdk.store.customer.retrieve()
502
503 setCustomer(customerData)
504 setLoading(false)
505 }
506
507 useEffect(() => {
508 if (!loading) {
509 return
510 }
511
512 validateCallback()
513 }, [loading])
514
515 useEffect(() => {
516 if (!customer) {
517 return
518 }
519
520 // TODO redirect to homepage after successful authentication
521 }, [customer])
522
523 return (
524 <div>
525 {loading && <span>Loading...</span>}
526 {customer && <span>Created customer {customer.email} with Google.</span>}
527 </div>
528 )
529 }
530 ```
531
532 </CodeTab>
533 <CodeTab label="JS SDK" value="js-sdk">
534
535 ```ts
536 import { decodeToken } from "react-jwt"
537
538 // ...
539
540 const queryParams = new URLSearchParams(window.location.search)
541 const code = queryParams.get("code")
542 const state = queryParams.get("state")
543
544
545 const sendCallback = async () => {
546 let token = ""
547
548 try {
549 token = await sdk.auth.callback(
550 "customer",
551 "google",
552 // pass all query parameters received from the
553 // third party provider
554 queryParams
555 )
556 } catch (error) {
557 alert("Authentication Failed")
558
559 throw error
560 }
561
562 return token
563 }
564
565 const createCustomer = async () => {
566 // create customer
567 await sdk.store.customer.create({
568 email: "example@medusajs.com",
569 })
570 }
571
572 const refreshToken = async () => {
573 // refresh the token
574 const result = await sdk.auth.refresh()
575 }
576
577 const validateCallback = async () => {
578 const token = await sendCallback()
579
580 const shouldCreateCustomer = (decodeToken(token) as { actor_id: string }).actor_id === ""
581
582 if (shouldCreateCustomer) {
583 await createCustomer()
584
585 await refreshToken()
586 }
587
588 // all subsequent requests are authenticated
589 const { customer: customerData } = await sdk.store.customer.retrieve()
590
591 setCustomer(customerData)
592 setLoading(false)
593 }
594 ```
595
596 </CodeTab>
597 </CodeTabs>
598
599 ---
600
601 ## Deep Dive: Third-Party Login Flow in Storefront
602
603 In this section, you'll find a general overview of the third-party login flow in the storefront. This is useful if you're not using the JS SDK or want to understand the flow better.
604
605 If you already set up the [Auth Module Provider](../../../commerce-modules/auth/auth-providers/page.mdx) in your Medusa application, you can log in a customer with a third-party service, such as Google or GitHub, using the following flow:
606
607 ![Diagram illustrating the authentication flow between the storefront, Medusa application, and the third-party service.](https://res.cloudinary.com/dza7lstvk/image/upload/v1725531068/Medusa%20Resources/Social_Media_Graphics_third-party-auth-customer_kfn3k3.jpg)
608
609 1. Authenticate the customer with the [Authenticate Customer API route](!api!/store/auth/authenticate-customer). It may return:
610 - A URL in a `location` property to authenticate with a third-party service, such as Google. When you receive this property, redirect to the returned location.
611 - A token in a `token` property. In this case, the customer was previously logged in with the third-party service. No additional actions are required. You can use the token to send subsequent authenticated requests.
612 2. Once authentication with the third-party service finishes, it redirects back to the storefront with query parameters such as `code` and `state`. Make sure your third-party service is configured to redirect to your storefront's callback page after successful authentication.
613 3. In the storefront's callback page, send a request to the [Validate Authentication Callback API route](!api!/store/auth/validate-authentication-callback). Pass the query parameters (`code`, `state`, etc.) received from the third-party service.
614 - Medusa validates the authentication with the third-party service.
615 4. If the callback validation is successful, you'll receive the authentication token. Decode the received token in the storefront using tools like [react-jwt](https://www.npmjs.com/package/react-jwt).
616 - If the decoded data has an `actor_id` property, the customer is already registered. Use this token for subsequent authenticated requests.
617 - If not, follow the rest of the steps.
618 5. The customer is not registered yet. Use the received token from the Validate Authentication Callback API route to create the customer using the [Create Customer API route](!api!/store/customers/register-customer).
619 6. Send a request to the [Refresh Token Route](!api!/store/auth/refresh-authentication-token) to retrieve a new token for the customer. Pass the token from the Validate Authentication Callback API in the header.
620 7. Use the token for subsequent authenticated requests, such as retrieving the customer's details using the [Retrieve Customer API route](!api!/store/customers/get-customer).