Customer Context in Storefront

Throughout your storefront, you'll need to access the logged-in customer to perform different actions, such as associate it with a cart.

So, if your storefront is React-based, 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:

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"10
11type CustomerContextType = {12  customer: HttpTypes.StoreCustomer | undefined13  setCustomer: React.Dispatch<14    React.SetStateAction<HttpTypes.StoreCustomer | undefined>15  >16}17
18const CustomerContext = createContext<CustomerContextType | null>(null)19
20type CustomerProviderProps = {21  children: React.ReactNode22}23
24export const CustomerProvider = ({25  children,26}: CustomerProviderProps) => {27  const [customer, setCustomer] = useState<28    HttpTypes.StoreCustomer29  >()30
31  useEffect(() => {32    if (customer) {33      return34    }35
36    fetch(`http://localhost:9000/store/customers/me`, {37      credentials: "include",38      headers: {39        "x-publishable-api-key": process.env.NEXT_PUBLIC_MEDUSA_PUBLISHABLE_KEY || "temp",40      },41    })42    .then((res) => res.json())43    .then(({ customer }) => {44      setCustomer(customer)45    })46    .catch((err) => {47      // customer isn't logged in48    })49  }, [])50
51  return (52    <CustomerContext.Provider value={{53      customer,54      setCustomer,55    }}>56      {children}57    </CustomerContext.Provider>58  )59}60
61export const useCustomer = () => {62  const context = useContext(CustomerContext)63
64  if (!context) {65    throw new Error("useCustomer must be used within a CustomerProvider")66  }67
68  return context69}

The CustomerProvider handles retrieving the authenticated customer from the Medusa application.

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?
Edit this page
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