serverMedusaClient


This server utility is using @medusajs/js-sdk under the hood and gives you access to the Medusa client.

Check the official documentation of Medusa JS Client to learn more about all the available options here

Fetching data from Medusa on the Server

To use the server utility you first need to enable the server option in the module configuration as shown below:

export default defineNuxtConfig({  modules: ['nuxt-medusa'],  medusa: {    server: true  }})

Then, let's create a new api endpoint server/api/products.ts:

import { serverMedusaClient } from '#medusa/server'export default eventHandler(async (event) => {  const client = serverMedusaClient(event)  const { products } = await client.store.product.list()  return { products }})

In here, we are registering a new eventHandler that will create a connection to the Medusa platform and then fetch the product list that can be later returned.

Finally, let's fetch this data in our Vue components by using useFetch as shown below:

<script lang="ts" setup>  const { data } = await useFetch('/api/products')  const products = data.value.products</script>

Fetching data as an authenticated user

To fetch the data as an authenticated user (for example to get data about the currently logged in user) on the server you need to pass the cookies that are sent from the browser as custom headers to the method as shown below:

import { serverMedusaClient } from '#medusa/server'export default eventHandler(async (event) => {  const client = serverMedusaClient(event)  const { customer } = await client.store.customer.retrieve({}, {    Cookie: event.node.req.headers.cookie,  });  return customer})

Initializing a cart on the server

First, you need to enable the server option in the module configuration. Then, create a new api endpoint server/api/cart.ts:

import { serverMedusaClient } from '#medusa/server'export default eventHandler(async (event) => {  const client = serverMedusaClient(event)  const cartId = getCookie(event, 'cart_id') || null  if (!cartId) {    const { cart } = await client.store.cart.create({ region_id: 'reg_123' });    setCookie(event, 'cart_id', cart.id)    return { cart }  } else {    const { cart } = await client.store.cart.retrieve(cartId);    return { cart }  }})

In here, we are registering a new eventHandler that will check if the cart_id cookie is set. If not, it will create a new cart on the Medusa platform and set the cart_id cookie. If the cart_id cookie is set, it will retrieve the cart information.

Finally, let's fetch the cart data in our Vue components by using $fetch as shown below:

<script lang="ts" setup>  const { data } = await useFetch('/api/cart')  const cart = data.value.cart</script>