Raw
1 ---
2 tags:
3 - customer
4 - storefront
5 products:
6 - customer
7 ---
8
9 export const metadata = {
10 title: `Customer Context in Storefront`,
11 }
12
13 # {metadata.title}
14
15 In this guide, you'll learn how to create a customer context in your storefront.
16
17 ## Why Create a Customer Context?
18
19 Throughout your storefront, you'll need to access the logged-in customer to perform different actions, such as associating it with a cart.
20
21 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.
22
23 ---
24
25 ## Create Customer Context Provider
26
27 For example, create the following file that exports a `CustomerProvider` component and a `useCustomer` hook:
28
29 <Note title="Tip">
30
31 Learn how to install and configure the JS SDK in the [JS SDK documentation](../../../js-sdk/page.mdx).
32
33 </Note>
34
35
36 export const highlights = [
37 ["13", "customer", "Expose customer to children of the context provider."],
38 ["14", "setCustomer", "Allow the context provider's\nchildren to change the logged-in customer."],
39 ["25", "CustomerProvider", "The provider component to use in your component tree."],
40 ["37", "retrieve", "Try to retrieve the customer's details,\nif the customer is authentiated."],
41 ["56", "useCustomer", "The hook that child components of the provider use to access the customer."]
42 ]
43
44 ```tsx highlights={highlights}
45 "use client" // include with Next.js 13+
46
47 import {
48 createContext,
49 useContext,
50 useEffect,
51 useState,
52 } from "react"
53 import { HttpTypes } from "@medusajs/types"
54 import { sdk } from "@/lib/sdk"
55
56 type CustomerContextType = {
57 customer: HttpTypes.StoreCustomer | undefined
58 setCustomer: React.Dispatch<
59 React.SetStateAction<HttpTypes.StoreCustomer | undefined>
60 >
61 }
62
63 const CustomerContext = createContext<CustomerContextType | null>(null)
64
65 type CustomerProviderProps = {
66 children: React.ReactNode
67 }
68
69 export const CustomerProvider = ({
70 children,
71 }: CustomerProviderProps) => {
72 const [customer, setCustomer] = useState<
73 HttpTypes.StoreCustomer
74 >()
75
76 useEffect(() => {
77 if (customer) {
78 return
79 }
80
81 sdk.store.customer.retrieve()
82 .then(({ customer }) => {
83 setCustomer(customer)
84 })
85 .catch((err) => {
86 // customer isn't logged in
87 })
88 }, [])
89
90 return (
91 <CustomerContext.Provider value={{
92 customer,
93 setCustomer,
94 }}>
95 {children}
96 </CustomerContext.Provider>
97 )
98 }
99
100 export const useCustomer = () => {
101 const context = useContext(CustomerContext)
102
103 if (!context) {
104 throw new Error("useCustomer must be used within a CustomerProvider")
105 }
106
107 return context
108 }
109 ```
110
111 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](../login/page.mdx) and [Third-Party Login](../third-party-login/page.mdx) guides.
112
113 The `useCustomer` hook returns the value of the `CustomerContext`. Child components of `CustomerProvider` use this hook to access `customer` or `setCustomer`.
114
115 ---
116
117 ## Use CustomerProvider in Component Tree
118
119 To use the customer context's value, add the `CustomerProvider` high in your component tree.
120
121 For example, if you're using Next.js, add it to the `app/layout.tsx` or `src/app/layout.tsx` file:
122
123 ```tsx title="app/layout.tsx" collapsibleLines="1-14" highlights={[["24"]]}
124 import type { Metadata } from "next"
125 import { Inter } from "next/font/google"
126 import "./globals.css"
127 import { CartProvider } from "@/providers/cart"
128 import { RegionProvider } from "@/providers/region"
129 import { CustomerProvider } from "@/providers/customer"
130
131 const inter = Inter({ subsets: ["latin"] })
132
133 export const metadata: Metadata = {
134 title: "Create Next App",
135 description: "Generated by create next app",
136 }
137
138 export default function RootLayout({
139 children,
140 }: Readonly<{
141 children: React.ReactNode;
142 }>) {
143 return (
144 <html lang="en">
145 <body className={inter.className}>
146 <RegionProvider>
147 <CustomerProvider>
148 {/* Other providers... */}
149 <CartProvider>
150 {children}
151 </CartProvider>
152 </CustomerProvider>
153 </RegionProvider>
154 </body>
155 </html>
156 )
157 }
158 ```
159
160 ### Use useCustomer Hook
161
162 Now, you can use the `useCustomer` hook in child components of `CustomerProvider`.
163
164 For example:
165
166 ```tsx
167 "use client" // include with Next.js 13+
168 // ...
169 import { useCustomer } from "@/providers/customer"
170
171 export default function Profile() {
172 const { customer } = useCustomer()
173 // ...
174 }
175 ```