Customer Context in the Storefront
Share customer state across React components.
On this page
In this guide, you'll learn how to share logged-in customer state in a storefront.
Next.js App Router (recommended)
Do not keep the customer in a client context that fetches in useEffect.
On Next.js, retrieveCustomer(storeCode) in src/lib/data/customer.ts reads _aiminaabee_jwt and returns null when there is no token. Call it from layouts and account pages. After login or signup, setAuthToken and transferCart. After signout, clear the token and cart cookies.
See Login and Build a Next.js Storefront.
A client hook is fine for UI (avatar menu). It should call server actions or receive the customer from a server parent.
SPA: Customer Context Provider
Throughout your storefront, you'll need to access the logged-in customer to perform different actions, such as associating it with a cart.
So, if your storefront is React-based, you can create a customer context and add it at the top of your components tree. Then, you can access the logged-in customer anywhere in your storefront.
Create Customer Context Provider
For example, create the following file that exports a CustomerProvider component and a useCustomer hook:
Tip: Learn how to install and configure the JS SDK in the Getting started guide.
tsx
The CustomerProvider handles retrieving the authenticated customer from the Aiminaabee application. This assumes that the JS SDK is already configured for authentication and the customer's authentication token was set as explained in the Login in Storefront and Third-Party Login guides.
The useCustomer hook returns the value of the CustomerContext. Child components of CustomerProvider use this hook to access customer or setCustomer.
Use CustomerProvider in Component Tree
To use the customer context's value, add the CustomerProvider high in your component tree.
For example, if you're using Next.js, add it to the app/layout.tsx or src/app/layout.tsx file:
tsx
Use useCustomer Hook
Now, you can use the useCustomer hook in child components of CustomerProvider.
For example:
tsx