Third-Party or Social Login in Storefront

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.

Summary#

By following the steps in this guide, you'll learn how to:

  • Create a login page with a button that starts the third-party login process. This redirects customers to the third-party service for authentication.
  • 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.

These are the pages you need in your storefront to allow customers to log in or create an account using a third-party service.

Diagram with a summary of the third-party login flow in the storefront.

Step 1: Login Button in Storefront#

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.

When the customer clicks the "Login with Google" button, send a request to the Authenticate Customer API route. This returns the URL to redirect the customer to Google for authentication.

For example:

Tip: Learn how to install and configure the JS SDK in the JS SDK documentation.

You define a loginWithGoogle function that:

  • Sends a request to the /auth/customer/google API route using the JS SDK's auth.login method.
    • If you're using a provider other than Google, replace google in the login method with your provider ID.
  • If the response is an object with a location property, redirect to the returned page for authentication with the third-party service.
  • If the response is not an object or a string, the authentication has failed.
  • If the response is a string, it's the customer's authentication token. This means the customer has been authenticated before.
    • 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.
Tip: The JS SDK sets and passes authentication headers or session cookies automatically based on your configured authentication method. If you're not using the JS SDK, make sure to pass the necessary headers in your request as explained in the API reference.

Step 2: Callback Page in Storefront#

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.

Google OAuth credentials settings showing the Redirect URI field

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 section.

a. Install the React-JWT Library#

First, install the react-jwt library in your storefront:

You'll use it to decode the token that Medusa returns after validating the authentication callback.

b. Implement the Callback Page#

Then, create a new page in your storefront that will be used as the callback/redirect URI destination:

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, passing it all query parameters received from Google. These include the code and state parameters.

Tip: 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.

c. Create Customer Function#

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.

Replace the TODO after the sendCallback function with the following:

JS SDK / React Applicable
1const createCustomer = async () => {2  // create customer3  await sdk.store.customer.create({4    email: "example@medusajs.com",5  })6}7
8// TODO add more functions...

You add the function createCustomer which creates a customer when this is the first time the customer is authenticating with the third-party service.

Tip: This method assumes that the token received from the Validate Callback API route 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 in the authorization Bearer header.

d. Refresh Token Function#

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.

Replace the new TODO with the following:

JS SDK / React Applicable
1const refreshToken = async () => {2  // refresh the token3  const result = await sdk.auth.refresh()4}5
6// TODO add more functions...

You add the function refreshToken that sends a request to the Refresh Token API route to retrieve a new token for the created customer.

The refreshToken method also updates the token stored by the JS SDK, ensuring that subsequent requests use that token.

Tip: This method assumes that the token received from the Validate Callback API route 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. Make sure to also update the token stored in your application after refreshing it.

e. Validate Callback Function#

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.

Add in the place of the new TODO the validateCallback function that runs when the page first loads to validate the authentication:

The validateCallback function uses the functions added earlier to implement the following flow:

  1. Send a request to the Validate Callback API route. This returns an authentication token.
    • The sendCallback function also sets the token in the JS SDK. This passes the token in subsequent requests.
  2. Decode the token to check if it has an actor_id property.
  • If the property exists, the customer is already registered. The authentication token can be used for subsequent authenticated requests.
  • If the property doesn't exist, this is the first time the customer is authenticating with the third-party service. So:
    1. Create a customer.
    2. Refetch the customer's authentication token.
    3. Use the token for subsequent authenticated requests.
  1. Retrieve the customer's details as an example of testing authentication.

f. Run the Callback Validation on Page Load#

Finally, you need to run the validateCallback function when the page first loads. In React, you can do that using the useEffect hook.

For example, replace the last TODO with the following:

Code
1useEffect(() => {2  if (!loading) {3    return4  }5
6  validateCallback()7}, [loading])

This runs the validateCallback function when the page first loads. If the validation is successful, the customer is authenticated.

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:

Code
1useEffect(() => {2  if (!customer) {3    return4  }5
6  // redirect to homepage after successful authentication7  window.location.href = "/"8}, [customer])

Full Code Example for Third-Party Login Callback Page#


Deep Dive: Third-Party Login Flow in Storefront#

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.

If you already set up the Auth Module Provider in your Medusa application, you can log in a customer with a third-party service, such as Google or GitHub, using the following flow:

Diagram illustrating the authentication flow between the storefront, Medusa application, and the third-party service.

  1. Authenticate the customer with the Authenticate Customer API route. It may return:
    • 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.
    • 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.
  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.
  3. In the storefront's callback page, send a request to the Validate Authentication Callback API route. Pass the query parameters (code, state, etc.) received from the third-party service.
  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.
    • If the decoded data has an actor_id property, the customer is already registered. Use this token for subsequent authenticated requests.
    • If not, follow the rest of the steps.
  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.
  6. Send a request to the Refresh Token Route to retrieve a new token for the customer. Pass the token from the Validate Authentication Callback API in the header.
  7. Use the token for subsequent authenticated requests, such as retrieving the customer's details using the Retrieve Customer API route.
Was this page helpful?
Ask Anything
FAQ
What is Medusa?
How can I create a module?
How can I create a data model?
How do I create a workflow?
How can I extend a data model in the Product Module?
Recipes
How do I build a marketplace with Medusa?
How do I build digital products with Medusa?
How do I build subscription-based purchases with Medusa?
What other recipes are available in the Medusa documentation?
Chat is cleared on refresh
Line break