Customer Context in Storefront

In this guide, you'll learn how to create a customer context in your storefront.

Why Create a Customer Context?#

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 JS SDK documentation.
Code
1"use client" // include with Next.js 13+2
3import { 4  createContext, 5  useContext, 6  useEffect, 7  useState,8} from "react"9import { HttpTypes } from "@medusajs/types"10import { sdk } from "@/lib/sdk"11
12type CustomerContextType = {13  customer: HttpTypes.StoreCustomer | undefined14  setCustomer: React.Dispatch<15    React.SetStateAction<HttpTypes.StoreCustomer | undefined>16  >17}18
19const CustomerContext = createContext<CustomerContextType | null>(null)20
21type CustomerProviderProps = {22  children: React.ReactNode23}24
25export const CustomerProvider = ({26  children,27}: CustomerProviderProps) => {28  const [customer, setCustomer] = useState<29    HttpTypes.StoreCustomer30  >()31
32  useEffect(() => {33    if (customer) {34      return35    }36
37    sdk.store.customer.retrieve()38    .then(({ customer }) => {39      setCustomer(customer)40    })41    .catch((err) => {42      // customer isn't logged in43    })44  }, [])45
46  return (47    <CustomerContext.Provider value={{48      customer,49      setCustomer,50    }}>51      {children}52    </CustomerContext.Provider>53  )54}55
56export const useCustomer = () => {57  const context = useContext(CustomerContext)58
59  if (!context) {60    throw new Error("useCustomer must be used within a CustomerProvider")61  }62
63  return context64}

The CustomerProvider handles retrieving the authenticated customer from the Medusa 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:

app/layout.tsx
13}14
15export default function RootLayout({16  children,17}: Readonly<{18  children: React.ReactNode;19}>) {20  return (21    <html lang="en">22      <body className={inter.className}>23        <RegionProvider>24          <CustomerProvider>25            {/* Other providers... */}26            <CartProvider>27              {children}28            </CartProvider>29          </CustomerProvider>30        </RegionProvider>31      </body>32    </html>33  )34}

Use useCustomer Hook#

Now, you can use the useCustomer hook in child components of CustomerProvider.

For example:

Code
1"use client" // include with Next.js 13+2// ...3import { useCustomer } from "@/providers/customer"4
5export default function Profile() {6  const { customer } = useCustomer()7  // ...8}
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