www/apps/resources/app/storefront-development/customers/retrieve/page.mdx
import { CodeTabs, CodeTab } from "docs-ui"
export const metadata = {
title: 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.
When using the JS SDK, make sure that you've set the customer's authentication token using the setToken function:
sdk.client.setToken(token)
You can learn more in the Login Customer and Third-Party Login guides.
To retrieve the logged-in customer, send a request to the Get Customer API route:
sdk.store.customer.retrieve()
.then(({ customer }) => {
// use customer...
console.log(customer)
})
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:
credentials: include option to the fetch function.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:
sdk.store.customer.retrieve()
.then(({ customer }) => {
// use customer...
console.log(customer)
})
.catch(() => {
// redirect to login page
})
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.
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.