serverMedusaClient


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

Check official documentation of Medusa JS Client to learn more about all 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 like following:

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.products.list()  return { products }})

In here, we are registering a new eventHandler that will create a connetion 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 $fetch like following:

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

Fetching data as authenticated user

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

import { serverMedusaClient } from '#medusa/server'export default eventHandler(async (event) => {  const client = serverMedusaClient(event)  const { customer } = await client.auth.getSession({    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.carts.create();    setCookie(event, 'cart_id', cart.id)    return { cart }  } else {    const { cart } = await client.carts.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 like following:

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