> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/medusajs/medusa/llms.txt
> Use this file to discover all available pages before exploring further.

# JavaScript SDK Overview

> Learn about the Medusa JavaScript SDK for building commerce applications

# JavaScript SDK Overview

The Medusa JavaScript SDK (`@medusajs/js-sdk`) is a comprehensive client library for interacting with the Medusa API. It provides a type-safe, modern interface for building commerce applications across various frontend frameworks and environments.

## Features

The JavaScript SDK offers powerful features to streamline your development:

* **Type-Safe API**: Full TypeScript support with auto-completion and type checking
* **Unified Interface**: Consistent API across admin, store, and authentication methods
* **Flexible Authentication**: Support for JWT tokens, session-based auth, and OAuth providers
* **Environment Agnostic**: Works in browsers, Node.js, and React Native
* **Custom Storage**: Configurable token storage with localStorage, sessionStorage, or custom implementations
* **Advanced Networking**: Built-in support for Server-Sent Events (SSE) and streaming responses
* **Locale Support**: Multi-language support with automatic locale header management
* **Configurable Headers**: Global and per-request custom headers including Next.js cache tags

## Use Cases

### Storefront Development

Build modern e-commerce storefronts with React, Vue, or vanilla JavaScript:

```tsx theme={null}
import Medusa from "@medusajs/js-sdk"

const sdk = new Medusa({ 
  baseUrl: "https://api.example.com",
  publishableKey: "pk_..."
})

// List products
const { products } = await sdk.store.product.list()

// Create a cart
const { cart } = await sdk.store.cart.create({ 
  region_id: "reg_123" 
})

// Add items to cart
await sdk.store.cart.createLineItem(cart.id, {
  variant_id: "variant_123",
  quantity: 2
})
```

### Admin Dashboard

Manage your commerce backend with full admin capabilities:

```tsx theme={null}
import Medusa from "@medusajs/js-sdk"

const sdk = new Medusa({ 
  baseUrl: "https://api.example.com",
  apiKey: "sk_..."
})

// Authenticate admin user
await sdk.auth.login("user", "emailpass", {
  email: "admin@example.com",
  password: "password"
})

// Manage products
const { products } = await sdk.admin.product.list()

// Create a product
const { product } = await sdk.admin.product.create({
  title: "New Product",
  // ... product details
})

// Update orders
const { order } = await sdk.admin.order.update("order_123", {
  // ... order updates
})
```

### Mobile Applications

Integrate Medusa into React Native or other mobile frameworks:

```tsx theme={null}
import Medusa from "@medusajs/js-sdk"
import AsyncStorage from '@react-native-async-storage/async-storage'

const sdk = new Medusa({
  baseUrl: "https://api.example.com",
  publishableKey: "pk_...",
  auth: {
    type: "jwt",
    jwtTokenStorageMethod: "custom",
    storage: {
      getItem: (key) => AsyncStorage.getItem(key),
      setItem: (key, value) => AsyncStorage.setItem(key, value),
      removeItem: (key) => AsyncStorage.removeItem(key)
    }
  }
})
```

### Server-Side Rendering (SSR)

Use the SDK in Next.js, Nuxt, or other SSR frameworks:

```tsx theme={null}
import Medusa from "@medusajs/js-sdk"

// Server component or API route
const sdk = new Medusa({ 
  baseUrl: process.env.MEDUSA_API_URL,
  publishableKey: process.env.MEDUSA_PUBLISHABLE_KEY
})

// Use Next.js cache tags
const { products } = await sdk.store.product.list({
  fields: "id,title,thumbnail"
}, {
  "cache-control": {
    tags: ["products"]
  }
})
```

## Architecture

The SDK is organized into several key components:

### Main SDK Class

The `Medusa` class is the entry point that provides access to all SDK functionality:

```tsx theme={null}
class Medusa {
  client: Client        // Low-level HTTP client
  admin: Admin          // Admin API methods
  store: Store          // Storefront API methods
  auth: Auth            // Authentication methods
  
  setLocale(locale: string)  // Set active locale
  getLocale(): string        // Get current locale
}
```

### Admin API

The `admin` namespace provides access to all administrative operations:

* `product`, `productVariant`, `productCollection`, `productCategory`
* `order`, `draftOrder`, `claim`, `exchange`, `return`
* `customer`, `customerGroup`
* `inventory`, `stockLocation`, `reservation`
* `payment`, `paymentCollection`
* `promotion`, `campaign`
* `region`, `currency`, `taxRate`, `taxRegion`
* `user`, `invite`, `apiKey`
* And many more...

### Store API

The `store` namespace provides customer-facing operations:

* `product`, `collection`, `category`
* `cart` (create, update, manage items, shipping, complete)
* `order` (list, retrieve, transfer)
* `customer` (profile, addresses)
* `region`
* `payment`, `fulfillment`

### Authentication

The `auth` namespace handles all authentication flows:

* `login()` - Authenticate users, customers, or custom actors
* `register()` - Register new users
* `logout()` - Clear authentication
* `callback()` - Handle OAuth callbacks
* `refresh()` - Refresh authentication tokens
* `resetPassword()` - Initiate password reset
* `updateProvider()` - Update authentication credentials

### Client

The low-level `Client` class handles HTTP communication:

* Automatic header management (auth, locale, publishable key)
* Request/response transformation
* Query parameter serialization
* Error handling with `FetchError`
* Server-Sent Events (SSE) support via `fetchStream()`

## Authentication Methods

### JWT Authentication (Default)

Store JWT tokens in browser storage:

```tsx theme={null}
const sdk = new Medusa({
  baseUrl: "https://api.example.com",
  auth: {
    type: "jwt",
    jwtTokenStorageMethod: "local" // or "session", "memory", "custom"
  }
})
```

### Session-Based Authentication

Use HTTP-only cookies for enhanced security:

```tsx theme={null}
const sdk = new Medusa({
  baseUrl: "https://api.example.com",
  auth: {
    type: "session",
    fetchCredentials: "include" // Send cookies with requests
  }
})
```

### API Key Authentication

Use API keys for server-to-server communication:

```tsx theme={null}
const sdk = new Medusa({
  baseUrl: "https://api.example.com",
  apiKey: "sk_..." // Admin API key
})
```

## Error Handling

The SDK throws `FetchError` instances for failed requests:

```tsx theme={null}
import { FetchError } from "@medusajs/js-sdk"

try {
  const { product } = await sdk.store.product.retrieve("invalid_id")
} catch (error) {
  if (error instanceof FetchError) {
    console.error(`HTTP ${error.status}: ${error.message}`)
    console.error(error.statusText)
  }
}
```

## Next Steps

<CardGroup cols={2}>
  <Card title="Installation" icon="download" href="/sdk/installation">
    Learn how to install and initialize the SDK in your project
  </Card>

  <Card title="SDK Methods" icon="code" href="/sdk/methods">
    Explore available methods and client usage patterns
  </Card>
</CardGroup>
