useMedusaClient


This composable 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 Products

Here is an example of a fetch using the list method:

<script lang="ts" setup>  const client = useMedusaClient();  const { products } = await client.products.list();</script>

Fetching Collections

Here is an example of a fetch using the list method:

<script lang="ts" setup>  const client = useMedusaClient();  const { collections } = await client.collections.list();</script>

Authenticating

Authenticating users with authenticate method:

<script lang="ts" setup>  const client = useMedusaClient();  await client.auth.authenticate({ email: 'test@test.test', password: 'test1234' });</script>

This will create a new cookie called connect.sid that will have a httpOnly flag set to true (which means that it is not accessible from the frontend JS code).

You can now fetch the data about currently logged in user like following:

<script lang="ts" setup>  const client = useMedusaClient();  const { customer } = await client.auth.getSession()</script>

Initializing a cart

You must initialize a cart the first time a user visits your storefront. Once the cart is created in the Medusa backend, you can save the cart_id either on localStorage or in a cookie, so you can retrieve the cart's information by using the cart_id.

To save the cart_id in localStorage you can use the following code:

<script lang="ts" setup>  const client = useMedusaClient();    const initCart = async () => {    const cartId = localStorage.getItem('cart_id') || null        if (!cartId) {      const { cart } = await client.carts.create();      localStorage.setItem('cart_id', cart.id)            // save the NEW cart to the store or the state    } else {      const { cart } = await client.carts.retrieve(cartId)            // save the EXISTING cart to the store or the state    }  }    initCart();</script>

To save the cart_id in a cookie you can leverage the useCookie composable that nuxt provides:

<script lang="ts" setup>  const client = useMedusaClient();  const cartId = useCookie('cart_id', { maxAge: 60 * 60 * 24 * 365 });    if (!cartId.value) {    const { cart } = await client.carts.create();    cartId.value = cart.id    // save the NEW cart to the store or the state  } else {    const { cart } = await client.carts.retrieve(cartId.value);    // save the EXISTING cart to the store or the state  }</script>

In both cases, first you check if the cart_id is already saved in the localStorage or cookie. If it is not, you create a new cart and save its id to the localStorage or cookie. If it is, you retrieve the cart from the Medusa backend and save it to the store or the state.