Medusa JS SDK
In this documentation, you'll learn how to install and use Medusa's JS SDK.
What is Medusa JS SDK?#
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.
How to Install Medusa JS SDK?#
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.
To install the Medusa JS SDK in other projects, such as a custom storefront, run the following command:
You install two libraries:
@medusajs/js-sdk
: the Medusa JS SDK.@medusajs/types
: Medusa's types library, which is useful if you're using TypeScript in your development.
Setup JS SDK#
In your project, create the following config.ts
file:
src/admin/lib/config.ts
.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 chapter.JS SDK Configurations#
The Medusa
initializer accepts as a parameter an object with the following properties:
Property | Description | Default |
---|---|---|
| A required string indicating the URL to the Medusa backend. | - |
| A string indicating the publishable API key to use in the storefront. You can retrieve it from the Medusa Admin. This is required for storefront applications. Otherwise, all requests will fail. | - |
| A string that specifies the user authentication method to use. Possible types are:
| - |
| A string that, when |
|
| A string that, when
|
|
| This option is only available after Medusa v2.5.1. It's an object or class that's used when
Learn more in the Authentication guide. | - |
| By default, if This option accepts a string to configure the value of
This option is only available after Medusa v2.1.1. |
|
| An object of key-value pairs indicating headers to pass in all requests, where the key indicates the name of the header field. | - |
| A string indicating the admin user's API key. If specified, it's used to send authenticated requests. | - |
| A boolean indicating whether to show debug messages of requests sent in the console. This is useful during development. |
|
| Replace the logger used by the JS SDK to log messages. The logger must be a class or object having the following methods:
| JavaScript's console is used by default. |
Manage Authentication in JS SDK#
The JS SDK supports different types of authentication methods and allow you to flexibly configure them.
To learn more about configuring authentication in the JS SDK and sending authenticated requests, refer to the Authentication guide.
Send Requests to Custom Routes#
The sidebar shows the different methods that you can use to send requests to Medusa's API routes.
To send requests to custom routes, the JS SDK has a client.fetch
method that wraps the JavaScript Fetch API that you can use. The method automatically appends configurations and headers, such as authentication headers, to your request.
For example, to send a request to a custom route at http://localhost:9000/custom
:
The fetch
method accepts as a first parameter the route's path relative to the baseUrl
configuration you passed when you initialized the SDK.
In the second parameter, you can pass an object of request configurations. 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.
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.
Stream Server-Sent Events#
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.
For example, consider you have the following custom API route at src/api/admin/stream/route.ts
:
1import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http"2 3export const GET = async (4 req: MedusaRequest,5 res: MedusaResponse6) => {7 res.writeHead(200, {8 "Content-Type": "text/event-stream",9 "Cache-Control": "no-cache",10 Connection: "keep-alive",11 })12 13 const interval = setInterval(() => {14 res.write("data: Streaming data...\n\n")15 }, 3000)16 17 req.on("close", () => {18 clearInterval(interval)19 res.end()20 })21 22 req.on("end", () => {23 clearInterval(interval)24 res.end()25 })26}
Then, you can use the client.fetchStream
method in a UI route to receive the streaming data:
1import { defineRouteConfig } from "@medusajs/admin-sdk"2import { Container, Heading, Button, Text } from "@medusajs/ui"3import { useState } from "react"4import { sdk } from "../../lib/sdk"5 6const StreamTestPage = () => {7 const [messages, setMessages] = useState<string[]>([])8 const [isStreaming, setIsStreaming] = useState(false)9 const [abortStream, setAbortStream] = useState<(() => void) | null>(null)10 11 const startStream = async () => {12 setIsStreaming(true)13 setMessages([])14 15 const { stream, abort } = await sdk.client.fetchStream("/admin/stream")16 17 if (!stream) {18 console.error("Failed to start stream")19 setIsStreaming(false)20 return21 }22 23 // Store the abort function for the abort button24 setAbortStream(() => abort)25 26 try {27 for await (const chunk of stream) {28 // Since the server sends plain text, convert to string29 const message = typeof chunk === "string" ? chunk : (chunk.data || String(chunk))30 setMessages((prev) => [...prev, message.trim()])31 }32 } catch (error) {33 // Don't log abort errors as they're expected when user clicks abort34 if (error instanceof Error && error.name !== "AbortError") {35 console.error("Stream error:", error)36 }37 } finally {38 setIsStreaming(false)39 setAbortStream(null)40 }41 }42 43 const handleAbort = () => {44 if (abortStream) {45 abortStream()46 setIsStreaming(false)47 setAbortStream(null)48 }49 }50 51 return (52 <Container className="p-6">53 <Heading level="h1" className="mb-6">54 fetchStream Example55 </Heading>56 57 <div className="space-y-4">58 <div className="flex gap-2">59 <Button 60 onClick={startStream} 61 disabled={isStreaming}62 variant="primary"63 >64 {isStreaming ? "Streaming..." : "Start Stream"}65 </Button>66 67 <Button 68 onClick={handleAbort} 69 disabled={!isStreaming}70 variant="secondary"71 >72 Abort Stream73 </Button>74 </div>75 76 <div className="border rounded p-4 h-64 overflow-y-auto bg-ui-bg-subtle">77 {messages.length === 0 ? (78 <Text className="text-ui-fg-muted">No messages yet...</Text>79 ) : (80 messages.map((msg, index) => (81 <div key={index} className="mb-2 text-sm">82 {msg}83 </div>84 ))85 )}86 </div>87 </div>88 </Container>89 )90}91 92export const config = defineRouteConfig({93 label: "Stream Test",94})95 96export default StreamTestPage
fetchStream
accepts the same parameters as fetch
, but it returns an object having two properties:
stream
: An AsyncGenerator that you can use to iterate over the streaming data.abort
: A function that you can call to abort the stream. This is useful when you want to stop receiving data from the server.
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.
Handle Errors#
If an error occurs in a request, the JS SDK throws a FetchError
object. This object has the following properties:
status
: The HTTP status code of the response.statusText
: The error code. For example,Unauthorized
.message
: The error message. For example,Invalid credentials
.
You can use these properties to handle errors in your application.
For example:
In the example above, you handle errors in two ways:
- Since the JS SDK's methods return a Promise, you can use the
catch
method to handle errors. - You can use the
try...catch
statement to handle errors when usingasync/await
. This is useful when you're executing the methods as part of a larger function.
In the catch
method or statement, you have access to the error object of type FetchError
.
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.
Pass Headers in Requests#
There are two ways to pass custom headers in requests when using the JS SDK:
- 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:
- 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:
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.
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.Medusa JS SDK Tips#
Use Tanstack (React) Query in Admin Customizations#
In admin customizations, use Tanstack Query with the JS SDK to send requests to custom or existing API routes.
Tanstack Query is installed by default in your Medusa application.
v5.64.2
as a development dependency.Use the configured SDK with the useQuery Tanstack Query hook to send GET
requests, and useMutation hook to send POST
or DELETE
requests.
For example:
Refer to Tanstack Query's documentation to learn more about sending Queries and Mutations.
Cache in Next.js Projects#
Every method of the SDK that sends requests accepts as a last parameter an object of key-value headers to pass in the request.
In Next.js storefronts or projects, pass the next.tags
header in the last parameter for data caching.
For example:
The tags
property accepts an array of tags that the data is cached under.
Then, to purge the cache later, use Next.js's revalidateTag
utility:
Learn more in the Next.js documentation.