1 import { CodeTabs, CodeTab, Table, Prerequisites } from "docs-ui"
2
3 export const metadata = {
4 title: `Medusa JS SDK`,
5 }
6
7 # {metadata.title}
8
9 In this documentation, you'll learn how to install and use Medusa's JS SDK.
10
11 ## What is Medusa JS SDK?
12
13 Medusa's JS SDK is a library to easily send requests to your Medusa application. You can use it in your admin customizations or custom storefronts.
14
15 ---
16
17 ## How to Install Medusa JS SDK?
18
19 The Medusa JS SDK is available in your Medusa application by default. So, you don't need to install it before using it in your admin customizations.
20
21 To install the Medusa JS SDK in other projects, such as a custom storefront, run the following command:
22
23 ```bash npm2yarn
24 npm install @medusajs/js-sdk@latest @medusajs/types@latest
25 ```
26
27 You install two libraries:
28
29 - `@medusajs/js-sdk`: the Medusa JS SDK.
30 - `@medusajs/types`: Medusa's types library, which is useful if you're using TypeScript in your development.
31
32 ---
33
34 ## Setup JS SDK
35
36 In your project, create the following `config.ts` file:
37
38 <Note>
39
40 For admin customizations, create this file at `src/admin/lib/config.ts`.
41
42 </Note>
43
44 <CodeTabs group="sdk-project">
45 <CodeTab label="Admin (Medusa project)" value="admin-medusa-project">
46
47 ```ts title="src/admin/lib/sdk.ts"
48 import Medusa from "@medusajs/js-sdk"
49
50 export const sdk = new Medusa({
51 baseUrl: import.meta.env.VITE_BACKEND_URL || "/",
52 debug: import.meta.env.DEV,
53 auth: {
54 type: "session",
55 },
56 })
57 ```
58
59 </CodeTab>
60 <CodeTab label="Admin (Medusa Plugin)" value="admin-medusa-plugin">
61
62 ```ts title="src/admin/lib/sdk.ts"
63 import Medusa from "@medusajs/js-sdk"
64
65 export const sdk = new Medusa({
66 baseUrl: __BACKEND_URL__ || "/",
67 debug: import.meta.env.DEV,
68 auth: {
69 type: "session",
70 },
71 })
72 ```
73
74 </CodeTab>
75 <CodeTab label="Storefront" value="storefront">
76
77 ```ts title="sdk.ts"
78 import Medusa from "@medusajs/js-sdk"
79
80 let MEDUSA_BACKEND_URL = "http://localhost:9000"
81
82 if (process.env.NEXT_PUBLIC_MEDUSA_BACKEND_URL) {
83 MEDUSA_BACKEND_URL = process.env.NEXT_PUBLIC_MEDUSA_BACKEND_URL
84 }
85
86 export const sdk = new Medusa({
87 baseUrl: MEDUSA_BACKEND_URL,
88 debug: process.env.NODE_ENV === "development",
89 publishableKey: process.env.NEXT_PUBLIC_MEDUSA_PUBLISHABLE_KEY,
90 })
91 ```
92
93 </CodeTab>
94 </CodeTabs>
95
96 <Note title="Tip">
97
98 In Medusa Admin customizations that are created in a Medusa project, you use `import.meta.env` to access environment variables, whereas in customizations built in a Medusa plugin, you use the global variable `__BACKEND_URL__` to access the backend URL. You can learn more in the [Admin Environment Variables](!docs!/learn/fundamentals/admin/environment-variables) chapter.
99
100 </Note>
101
102 ### JS SDK Configurations
103
104 The `Medusa` initializer accepts as a parameter an object with the following properties:
105
106 <Table>
107 <Table.Header>
108 <Table.Row>
109 <Table.HeaderCell>
110 Property
111 </Table.HeaderCell>
112 <Table.HeaderCell className="w-2/5">
113 Description
114 </Table.HeaderCell>
115 <Table.HeaderCell>
116 Default
117 </Table.HeaderCell>
118 </Table.Row>
119 </Table.Header>
120 <Table.Body>
121 <Table.Row>
122 <Table.Cell>
123
124 `baseUrl`
125
126 </Table.Cell>
127 <Table.Cell>
128
129 A required string indicating the URL to the Medusa backend.
130
131 </Table.Cell>
132 <Table.Cell>
133
134 \-
135
136 </Table.Cell>
137 </Table.Row>
138 <Table.Row>
139 <Table.Cell>
140
141 `publishableKey`
142
143 </Table.Cell>
144 <Table.Cell>
145
146 A string indicating the publishable API key to use in the storefront. You can retrieve it from the Medusa Admin.
147
148 This is required for storefront applications. Otherwise, all requests will fail.
149
150 </Table.Cell>
151 <Table.Cell>
152
153 \-
154
155 </Table.Cell>
156 </Table.Row>
157 <Table.Row>
158 <Table.Cell>
159
160 `auth.type`
161
162 </Table.Cell>
163 <Table.Cell>
164
165 A string that specifies the user authentication method to use.
166
167 Possible types are:
168
169 - `session`: The user is authenticated with a cookie session.
170 - `jwt`: The user is authenticated with a JWT token that's passed in the Bearer authorization header.
171
172 </Table.Cell>
173 <Table.Cell>
174
175 \-
176
177 </Table.Cell>
178 </Table.Row>
179 <Table.Row>
180 <Table.Cell>
181
182 `auth.jwtTokenStorageKey`
183
184 </Table.Cell>
185 <Table.Cell>
186
187 A string that, when `auth.type` is `jwt`, specifies the key of the JWT token in the storage specified in the `auth.jwtTokenStorageMethod` configuration.
188
189 </Table.Cell>
190 <Table.Cell>
191
192 `medusa_auth_token`
193
194 </Table.Cell>
195 </Table.Row>
196 <Table.Row>
197 <Table.Cell>
198
199 `auth.jwtTokenStorageMethod`
200
201 </Table.Cell>
202 <Table.Cell>
203
204 A string that, when `auth.type` is `jwt`, specifies where the JWT token is stored. Possible values are:
205
206 - `local` for the Local Storage.
207 - `session` for the Session Storage.
208 - `memory` to store it within the SDK for the current application's runtime.
209 - `custom` to define custom storage using the `auth.storage` configuration. If `auth.storage` isn't defined, the SDK throws an error. This option is only available after Medusa v2.5.1.
210 - `nostore` to not store the token.
211
212 </Table.Cell>
213 <Table.Cell>
214
215 `local`
216
217 </Table.Cell>
218 </Table.Row>
219 <Table.Row>
220 <Table.Cell>
221
222 `auth.storage`
223
224 </Table.Cell>
225 <Table.Cell>
226
227 This option is only available after Medusa v2.5.1. It's an object or class that's used when `auth.jwtTokenStorageMethod` is `custom` to store the JWT token. It's useful when using the JS SDK in an environment where Local or Session Storage isn't available. The object or class must have the following methods:
228
229 - `setItem`: A function that accepts a key and value to store the JWT token.
230 - `getItem`: A function that accepts a key to retrieve the JWT token.
231 - `removeItem`: A function that accepts a key to remove the JWT token from storage.
232
233 Learn more in the [Authentication](./auth/overview/page.mdx#custom-authentication-storage-in-js-sdk) guide.
234
235 </Table.Cell>
236 <Table.Cell>
237
238 \-
239
240 </Table.Cell>
241 </Table.Row>
242 <Table.Row>
243 <Table.Cell>
244
245 `auth.fetchCredentials`
246
247 </Table.Cell>
248 <Table.Cell>
249
250 By default, if `auth.type` is `session`, the `credentials: include` option is passed in [fetch requests](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#including_credentials) under the hood. However, some platforms or environments may not support passing this option.
251
252 This option accepts a string to configure the value of `credentials` when the authentication type is `session`. It accepts one of the following values:
253
254 - `include`: (default) to pass the `credentials: include` option.
255 - `omit`: to pass the `credentials: omit` option.
256 - `same-origin`: to pass the `credentials: same-origin` option.
257
258 This option is only available after [Medusa v2.1.1](https://github.com/medusajs/medusa/releases/tag/v2.1.1).
259
260 </Table.Cell>
261 <Table.Cell>
262
263 `include`
264
265 </Table.Cell>
266 </Table.Row>
267 <Table.Row>
268 <Table.Cell>
269
270 `globalHeaders`
271
272 </Table.Cell>
273 <Table.Cell>
274
275 An object of key-value pairs indicating headers to pass in all requests, where the key indicates the name of the header field.
276
277 </Table.Cell>
278 <Table.Cell>
279
280 \-
281
282 </Table.Cell>
283 </Table.Row>
284 <Table.Row>
285 <Table.Cell>
286
287 `apiKey`
288
289 </Table.Cell>
290 <Table.Cell>
291
292 A string indicating the admin user's API key. If specified, it's used to send authenticated requests.
293
294 </Table.Cell>
295 <Table.Cell>
296
297 \-
298
299 </Table.Cell>
300 </Table.Row>
301 <Table.Row>
302 <Table.Cell>
303
304 `debug`
305
306 </Table.Cell>
307 <Table.Cell>
308
309 A boolean indicating whether to show debug messages of requests sent in the console. This is useful during development.
310
311 </Table.Cell>
312 <Table.Cell>
313
314 `false`
315
316 </Table.Cell>
317 </Table.Row>
318 <Table.Row>
319 <Table.Cell>
320
321 `logger`
322
323 </Table.Cell>
324 <Table.Cell>
325
326 Replace the logger used by the JS SDK to log messages. The logger must be a class or object having the following methods:
327
328 - `error`: A function that accepts an error message to log.
329 - `warn`: A function that accepts a warning message to log.
330 - `info`: A function that accepts an info message to log.
331 - `debug`: A function that accepts a debug message to log.
332
333 </Table.Cell>
334 <Table.Cell>
335
336 JavaScript's [console](https://developer.mozilla.org/en-US/docs/Web/API/console) is used by default.
337
338 </Table.Cell>
339 </Table.Row>
340 </Table.Body>
341 </Table>
342
343 ---
344
345 ## Manage Authentication in JS SDK
346
347 The JS SDK supports different types of authentication methods and allow you to flexibly configure them.
348
349 To learn more about configuring authentication in the JS SDK and sending authenticated requests, refer to the [Authentication](./auth/overview/page.mdx) guide.
350
351 ---
352
353 ## Send Requests to Custom Routes
354
355 The sidebar shows the different methods that you can use to send requests to Medusa's API routes.
356
357 To send requests to custom routes, the JS SDK has a `client.fetch` method that wraps the [JavaScript Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch) that you can use. The method automatically appends configurations and headers, such as authentication headers, to your request.
358
359 For example, to send a request to a custom route at `http://localhost:9000/custom`:
360
361 <CodeTabs group="request-type">
362 <CodeTab label="GET" value="get">
363
364 ```ts
365 sdk.client.fetch(`/custom`)
366 .then((data) => {
367 console.log(data)
368 })
369 ```
370
371 </CodeTab>
372 <CodeTab label="POST" value="post">
373
374 ```ts
375 sdk.client.fetch(`/custom`, {
376 method: "post",
377 body: {
378 id: "123",
379 },
380 }).then((data) => {
381 console.log(data)
382 })
383 ```
384
385 </CodeTab>
386 <CodeTab label="DELETE" value="delete">
387
388 ```ts
389 sdk.client.fetch(`/custom`, {
390 method: "delete",
391 }).then(() => {
392 console.log("success")
393 })
394 ```
395
396 </CodeTab>
397 </CodeTabs>
398
399 The `fetch` method accepts as a first parameter the route's path relative to the `baseUrl` configuration you passed when you initialized the SDK.
400
401 In the second parameter, you can pass an object of [request configurations](https://developer.mozilla.org/en-US/docs/Web/API/RequestInit). You don't need to configure the content-type to be JSON, or stringify the `body` or `query` value, as that's handled by the method.
402
403 The method returns a Promise that, when resolved, has the data returned by the request. If the request returns a JSON object, it'll be automatically parsed to a JavaScript object and returned.
404
405 ---
406
407 ## Download Binary or File Responses
408
409 By default, the `fetch` method sets the `accept` header of the request to `application/json`, so it parses the response as JSON and returns a JavaScript object.
410
411 The `fetch` method decides whether to parse the response as JSON based on the request's `accept` header, not the response's content type. So, if your custom route returns a binary or file response, such as a PDF or an image, you must override the `accept` header to a value other than `application/json`. The method then returns the raw [Response](https://developer.mozilla.org/en-US/docs/Web/API/Response) object without parsing it.
412
413 For example, to download a PDF file returned by a custom route:
414
415 ```tsx
416 const response: Response = await sdk.client.fetch(
417 `/admin/orders/${orderId}/invoice`,
418 {
419 method: "GET",
420 headers: {
421 accept: "application/pdf",
422 },
423 }
424 )
425
426 const blob = await response.blob()
427 const url = window.URL.createObjectURL(blob)
428 const link = document.createElement("a")
429 link.href = url
430 link.download = `invoice-${orderId}.pdf`
431 link.click()
432 window.URL.revokeObjectURL(url)
433 ```
434
435 In this example, you set the `accept` header to `application/pdf`, so the `fetch` method returns the raw `Response` object. You then use the [Response.blob](https://developer.mozilla.org/en-US/docs/Web/API/Response/blob) method to read the response as a [Blob](https://developer.mozilla.org/en-US/docs/Web/API/Blob), which you can download in the browser.
436
437 <Note>
438
439 Since the method returns the raw `Response` object in this case, type the returned value as `Response`. You're then responsible for reading the response's body, using methods like `blob`, [arrayBuffer](https://developer.mozilla.org/en-US/docs/Web/API/Response/arrayBuffer), or [text](https://developer.mozilla.org/en-US/docs/Web/API/Response/text).
440
441 </Note>
442
443 ---
444
445 ## Migrating from Fetch API to JS SDK
446
447 Prefer `sdk.client.fetch` over the raw [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch) when sending requests to your Medusa backend.
448
449 The JS SDK's `fetch` method automatically appends authentication headers and other configurations, such as the `globalHeaders` configuration, to your request. It also automatically parses the response to a JavaScript object if the response is a JSON object.
450
451 ### Changes in Error Handling
452
453 The raw `fetch` function only rejects its Promise on network errors. For error responses, such as a `404` or `500` status, the Promise still resolves, so a chained `then` callback runs as if the request succeeded. You must manually check the response's `ok` or `status` property to detect the error, and it's easy to forget to do so.
454
455 `sdk.client.fetch` instead throws a `FetchError` for any non-success status, so failures propagate to your `catch` block or `try...catch` statement. Learn how to handle these errors in the [Handle Errors](#handle-errors) section.
456
457 ---
458
459 ## Stream Server-Sent Events
460
461 The JS SDK supports streaming server-sent events (SSE) using the `client.fetchStream` method. This method is useful when you want to receive real-time updates from the server.
462
463 For example, consider you have the following custom API route at `src/api/admin/stream/route.ts`:
464
465 ```ts title="src/api/admin/stream/route.ts"
466 import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http"
467
468 export const GET = async (
469 req: MedusaRequest,
470 res: MedusaResponse
471 ) => {
472 res.writeHead(200, {
473 "Content-Type": "text/event-stream",
474 "Cache-Control": "no-cache",
475 Connection: "keep-alive",
476 })
477
478 const interval = setInterval(() => {
479 res.write("data: Streaming data...\n\n")
480 }, 3000)
481
482 req.on("close", () => {
483 clearInterval(interval)
484 res.end()
485 })
486
487 req.on("end", () => {
488 clearInterval(interval)
489 res.end()
490 })
491 }
492 ```
493
494 Then, you can use the `client.fetchStream` method in a UI route to receive the streaming data:
495
496 ```tsx title="src/admin/route/stream/page.tsx"
497 import { defineRouteConfig } from "@medusajs/admin-sdk"
498 import { Container, Heading, Button, Text } from "@medusajs/ui"
499 import { useState } from "react"
500 import { sdk } from "../../lib/sdk"
501
502 const StreamTestPage = () => {
503 const [messages, setMessages] = useState<string[]>([])
504 const [isStreaming, setIsStreaming] = useState(false)
505 const [abortStream, setAbortStream] = useState<(() => void) | null>(null)
506
507 const startStream = async () => {
508 setIsStreaming(true)
509 setMessages([])
510
511 const { stream, abort } = await sdk.client.fetchStream("/admin/stream")
512
513 if (!stream) {
514 console.error("Failed to start stream")
515 setIsStreaming(false)
516 return
517 }
518
519 // Store the abort function for the abort button
520 setAbortStream(() => abort)
521
522 try {
523 for await (const chunk of stream) {
524 // Since the server sends plain text, convert to string
525 const message = typeof chunk === "string" ? chunk : (chunk.data || String(chunk))
526 setMessages((prev) => [...prev, message.trim()])
527 }
528 } catch (error) {
529 // Don't log abort errors as they're expected when user clicks abort
530 if (error instanceof Error && error.name !== "AbortError") {
531 console.error("Stream error:", error)
532 }
533 } finally {
534 setIsStreaming(false)
535 setAbortStream(null)
536 }
537 }
538
539 const handleAbort = () => {
540 if (abortStream) {
541 abortStream()
542 setIsStreaming(false)
543 setAbortStream(null)
544 }
545 }
546
547 return (
548 <Container className="p-6">
549 <Heading level="h1" className="mb-6">
550 fetchStream Example
551 </Heading>
552
553 <div className="space-y-4">
554 <div className="flex gap-2">
555 <Button
556 onClick={startStream}
557 disabled={isStreaming}
558 variant="primary"
559 >
560 {isStreaming ? "Streaming..." : "Start Stream"}
561 </Button>
562
563 <Button
564 onClick={handleAbort}
565 disabled={!isStreaming}
566 variant="secondary"
567 >
568 Abort Stream
569 </Button>
570 </div>
571
572 <div className="border rounded p-4 h-64 overflow-y-auto bg-ui-bg-subtle">
573 {messages.length === 0 ? (
574 <Text className="text-ui-fg-muted">No messages yet...</Text>
575 ) : (
576 messages.map((msg, index) => (
577 <div key={index} className="mb-2 text-sm">
578 {msg}
579 </div>
580 ))
581 )}
582 </div>
583 </div>
584 </Container>
585 )
586 }
587
588 export const config = defineRouteConfig({
589 label: "Stream Test",
590 })
591
592 export default StreamTestPage
593 ```
594
595 `fetchStream` accepts the same parameters as `fetch`, but it returns an object having two properties:
596
597 - `stream`: An [AsyncGenerator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/AsyncGenerator) that you can use to iterate over the streaming data.
598 - `abort`: A function that you can call to abort the stream. This is useful when you want to stop receiving data from the server.
599
600 In this example, when the user clicks the "Start Stream" button, you start the stream and listen for incoming data. The data is received as chunks, which you can process and display in the UI.
601
602 ---
603
604 ## Handle Errors
605
606 If an error occurs in a request, the JS SDK throws a `FetchError` object. This object has the following properties:
607
608 - `status`: The HTTP status code of the response.
609 - `statusText`: The error code. For example, `Unauthorized`.
610 - `message`: The error message. For example, `Invalid credentials`.
611
612 You can use these properties to handle errors in your application.
613
614 For example:
615
616 <CodeTabs group="request-type">
617 <CodeTab label="Promise" value="promise">
618
619 ```ts
620 sdk.store.customer.listAddress()
621 .then(({ addresses, count, offset, limit }) => {
622 // no errors occurred
623 // do something with the data
624 console.log(addresses)
625 })
626 .catch((error) => {
627 const fetchError = error as FetchError
628
629 if (fetchError.statusText === "Unauthorized") {
630 // redirect to login page
631 } else {
632 // handle other errors
633 }
634 })
635 ```
636
637 </CodeTab>
638 <CodeTab label="Async/Await" value="async-await">
639
640 ```ts
641 try {
642 const {
643 addresses,
644 count,
645 offset,
646 limit,
647 } = await sdk.store.customer.listAddress()
648 // no errors occurred
649 // do something with the data
650 console.log(addresses)
651 } catch (error) {
652 const fetchError = error as FetchError
653
654 if (fetchError.statusText === "Unauthorized") {
655 // redirect to login page
656 } else {
657 // handle other errors
658 }
659 }
660 ```
661
662 </CodeTab>
663 </CodeTabs>
664
665 In the example above, you handle errors in two ways:
666
667 - Since the JS SDK's methods return a Promise, you can use the `catch` method to handle errors.
668 - You can use the `try...catch` statement to handle errors when using `async/await`. This is useful when you're executing the methods as part of a larger function.
669
670 In the `catch` method or statement, you have access to the error object of type `FetchError`.
671
672 An example of handling the error is to check if the error's `statusText` is `Unauthorized`. If so, you can redirect the customer to the login page. Otherwise, you can handle other errors by showing an alert, for example.
673
674 ---
675
676 ## Pass Headers in Requests
677
678 There are two ways to pass custom headers in requests when using the JS SDK:
679
680 1. Using the `globalHeaders` configuration: This is useful when you want to pass the same headers in all requests. For example, if you want to pass a custom header for tracking purposes:
681
682 ```ts
683 const sdk = new Medusa({
684 // ...
685 globalHeaders: {
686 "x-tracking-id": "123456789",
687 },
688 })
689 ```
690
691 2. Using the headers parameter of a specific method. Every method has as a last parameter a headers parameter, which is an object of headers to pass in the request. This is useful when you want to pass a custom header in specific requests. For example, to disable HTTP compression for specific requests:
692
693 ```ts
694 sdk.store.product.list({
695 limit,
696 offset,
697 }, {
698 "x-no-compression": "false",
699 })
700 ```
701
702 In the example above, you pass the `x-no-compression` header in the request to disable HTTP compression. You pass it as the last parameter of the `sdk.store.product.list` method.
703
704 <Note title="Tip">
705
706 The JS SDK appends request-specific headers to authentication headers and headers configured in the `globalHeaders` configuration. So, in the example above, the `x-no-compression` header is passed in the request along with the authentication headers and any headers configured in the `globalHeaders` configuration.
707
708 </Note>
709
710 ---
711
712 ## Localization with JS SDK
713
714 <Prerequisites
715 items={[
716 {
717 text: "Translation Module Configured",
718 link: "/commerce-modules/translation#configure-translation-module",
719 }
720 ]}
721 />
722
723 If you support [localization](../storefront-development/localization/page.mdx) in your storefront, you can use the `setLocale` method of the JS SDK.
724
725 The `setLocale` method stores the locale in the JS SDK to pass the it as a `x-medusa-locale` header in all subsequent requests. Also, if your application supports `localStorage`, the method sets the locale in the `medusa_locale` key of the `localStorage`.
726
727 For example, to set the locale to French (France):
728
729 ```ts
730 sdk.setLocale("fr-FR")
731 // products content is fetched in French
732 const { products } = await sdk.store.product.list()
733 ```
734
735 The `setLocale` method accepts the locale string in the [IETF BCP 47 standard](https://gist.github.com/typpo/b2b828a35e683b9bf8db91b5404f1bd1). All subsequent requests sent using the JS SDK will include the specified locale in the `x-medusa-locale` header.
736
737 In the above example, the product content, such as title and description, is fetched in French and falls back to the original content if translations aren't available.
738
739 You can also retrieve the currently set locale using the `getLocale` method:
740
741 ```ts
742 const currentLocale = sdk.getLocale()
743 console.log(currentLocale) // "fr-FR"
744 ```
745
746 <Note>
747
748 Learn more about localization and translations in the [Translation Module](../commerce-modules/translation/page.mdx) guide.
749
750 </Note>
751
752 ---
753
754 ## Medusa JS SDK Tips
755
756 ### Use Tanstack (React) Query in Admin Customizations
757
758 In admin customizations, use [Tanstack Query](https://tanstack.com/query/latest) with the JS SDK to send requests to custom or existing API routes.
759
760 Tanstack Query is installed by default in your Medusa application.
761
762 <Note type="warning">
763
764 Do not install Tanstack Query as that will cause unexpected errors in your development. If you prefer installing it for better auto-completion in your code editor, make sure to install `v5.64.2` as a development dependency.
765
766 </Note>
767
768 Use the [configured SDK](#setup-js-sdk) with the [useQuery](https://tanstack.com/query/latest/docs/framework/react/reference/useQuery#usequery) Tanstack Query hook to send `GET` requests, and [useMutation](https://tanstack.com/query/latest/docs/framework/react/reference/useMutation#usemutation) hook to send `POST` or `DELETE` requests.
769
770 For example:
771
772 <CodeTabs group="query-type">
773 <CodeTab label="Query" value="query">
774
775 export const queryHighlights = [
776 ["8", "useQuery", "Use Tanstack Query's `useQuery` to send a `GET` request."],
777 ["9", "sdk.admin.product.list", "Use the SDK to send the request."],
778 ["10", "queryKey", "Specify the key used to cache data."]
779 ]
780
781 ```tsx title="src/admin/widgets/product-widget.ts"
782 import { defineWidgetConfig } from "@medusajs/admin-sdk"
783 import { Button, Container } from "@medusajs/ui"
784 import { useQuery } from "@tanstack/react-query"
785 import { sdk } from "../lib/config"
786 import { DetailWidgetProps, HttpTypes } from "@medusajs/framework/types"
787
788 const ProductWidget = () => {
789 const { data, isLoading } = useQuery({
790 queryFn: () => sdk.admin.product.list(),
791 queryKey: ["products"],
792 })
793
794 return (
795 <Container className="divide-y p-0">
796 {isLoading && <span>Loading...</span>}
797 {data?.products && (
798 <ul>
799 {data.products.map((product) => (
800 <li key={product.id}>{product.title}</li>
801 ))}
802 </ul>
803 )}
804 </Container>
805 )
806 }
807
808 export const config = defineWidgetConfig({
809 zone: "product.list",
810 })
811
812 export default ProductWidget
813 ```
814
815 </CodeTab>
816 <CodeTab label="Mutation" value="mutation">
817
818 ```tsx title="src/admin/widgets/product-widget.ts"
819 import { defineWidgetConfig } from "@medusajs/admin-sdk"
820 import { Button, Container } from "@medusajs/ui"
821 import { useMutation } from "@tanstack/react-query"
822 import { sdk } from "../lib/config"
823 import { DetailWidgetProps, HttpTypes } from "@medusajs/framework/types"
824
825 const ProductWidget = ({
826 data: productData,
827 }: DetailWidgetProps<HttpTypes.AdminProduct>) => {
828 const { mutateAsync } = useMutation({
829 mutationFn: (payload: HttpTypes.AdminUpdateProduct) =>
830 sdk.admin.product.update(productData.id, payload),
831 onSuccess: () => alert("updated product"),
832 })
833
834 const handleUpdate = () => {
835 mutateAsync({
836 title: "New Product Title",
837 })
838 }
839
840 return (
841 <Container className="divide-y p-0">
842 <Button onClick={handleUpdate}>Update Title</Button>
843 </Container>
844 )
845 }
846
847 export const config = defineWidgetConfig({
848 zone: "product.details",
849 })
850
851 export default ProductWidget
852 ```
853
854 </CodeTab>
855 </CodeTabs>
856
857 Refer to Tanstack Query's documentation to learn more about sending [Queries](https://tanstack.com/query/latest/docs/framework/react/reference/useQuery#usequery) and [Mutations](https://tanstack.com/query/latest/docs/framework/react/reference/useMutation#usemutation).
858
859 ### Cache in Next.js Projects
860
861 Every method of the SDK that sends requests accepts as a last parameter an object of key-value headers to pass in the request.
862
863 In Next.js storefronts or projects, pass the `next.tags` header in the last parameter for data caching.
864
865 For example:
866
867 ```ts highlights={[["2", "next"], ["3", "tags", "An array of tags to cache the data under."]]}
868 sdk.store.product.list({}, {
869 next: {
870 tags: ["products"],
871 },
872 })
873 ```
874
875 The `tags` property accepts an array of tags that the data is cached under.
876
877 Then, to purge the cache later, use Next.js's `revalidateTag` utility:
878
879 ```ts
880 import { revalidateTag } from "next/cache"
881
882 // ...
883
884 revalidateTag("products")
885 ```
886
887 Learn more in the [Next.js documentation](https://nextjs.org/docs/app/building-your-application/caching#fetch-optionsnexttags-and-revalidatetag).