Retrieve Logged-In Customer in Storefront

In this guide, you'll learn how to retrieve a customer after they've been authenticated in your storefront.

Prerequisites: Set the Customer's Authentication Token#

When using the JS SDK, make sure that you've set the customer's authentication token using the setToken function:

Code
sdk.client.setToken(token)

You can learn more in the Login Customer and Third-Party Login guides.


Retrieve Logged-In Customer#

To retrieve the logged-in customer, send a request to the Get Customer API route:

Code
1sdk.store.customer.retrieve()2.then(({ customer }) => {3  // use customer...4  console.log(customer)5})

This will retrieve the authenticated customer's details. The Get Customer API route returns a customer field, which is a customer object.

Notice that the JS SDK automatically passes the necessary authentication headers or cookies based on your authentication configurations, as explained in the Login Customer guide.

If you're not using the JS SDK, you need to pass the authentication token in the request headers or cookies accordingly:

  • If you authenticate the customer with bearer authorization, pass the token in the authorization header of the request.
  • If you authenticate the customer with cookie session, pass the credentials: include option to the fetch function.

Restrict Access to Authenticated Customers#

In your storefront, it's common to restrict access to certain pages to authenticated customers only.

For example, you may want to restrict access to the customer's profile page to authenticated customers only.

To do this, you can try to retrieve the customer's details. If the request fails, you can redirect the customer to the login page.

For example:

Code
1sdk.store.customer.retrieve()2.then(({ customer }) => {3  // use customer...4  console.log(customer)5})6.catch(() => {7  // redirect to login page8})

The catch block will only execute if the request fails, which means that the customer is not authenticated. You can add the redirect logic to the catch block based on your storefront framework.

Tip: If you're building a React storefront, you can use the useCustomer hook defined in the Customer Context guide to check if the customer is set. If not, you can redirect the customer to the login page.
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