Connect Your Storefront to Medusa
In this guide, you’ll learn how to send requests from your storefront application to the Medusa application.
Connect to the Medusa Application#
To send requests from the storefront to the Medusa application’s Store API Routes, you have two options:
- For JavaScript frameworks: use Medusa’s JS SDK in any JavaScript framework. This NPM package facilitates interacting with the backend’s REST APIs. All Storefront Development guides use the JS SDK.
- For other frontend technologies: interact directly with the Medusa application by sending requests to its Store REST APIs.
Set Up the JS SDK#
To set up the JS SDK in your storefront application, install the @medusajs/js-sdk package with the types package:
Then, create a file that initializes the JS SDK client. For example, create the file src/lib/sdk.ts with the following content:
1import Medusa from "@medusajs/js-sdk"2 3let MEDUSA_BACKEND_URL = "http://localhost:9000"4 5if (process.env.NEXT_PUBLIC_MEDUSA_BACKEND_URL) {6 MEDUSA_BACKEND_URL = process.env.NEXT_PUBLIC_MEDUSA_BACKEND_URL7}8 9export const sdk = new Medusa({10 baseUrl: MEDUSA_BACKEND_URL,11 debug: process.env.NODE_ENV === "development",12 publishableKey: process.env.NEXT_PUBLIC_MEDUSA_PUBLISHABLE_KEY,13})
Where:
NEXT_PUBLIC_MEDUSA_BACKEND_URLis the URL of your Medusa application. Based on your storefront framework, make sure the environment variable is accessible in the browser. For example, in Next.js, prefix the variable name withNEXT_PUBLIC_.NEXT_PUBLIC_MEDUSA_PUBLISHABLE_KEYis the publishable API key of your storefront. Learn more in the Publishable API Keys guide.
You can then import the sdk instance from src/lib/sdk.ts and use it to send requests to the Medusa application. For example:
Refer to the JS SDK reference to learn more about using the SDK to interact with the Medusa application.
Configure Store CORS in Medusa#
The Medusa application’s API routes are guarded by a CORS middleware. Make sure to set the storeCors property of the http configuration in medusa-config.ts to the storefront’s URL.
For example:
Refer to the Medusa configuration guide to learn more about configuring CORS in the Medusa application.