useMedusaClient
This composable uses @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 Products
Here is an example of a fetch using the list
method:
<script lang="ts" setup> const client = useMedusaClient(); const { products } = await client.store.product.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.store.collection.list();</script>
Authenticating
Authenticating users with authenticate
method:
<script lang="ts" setup> const client = useMedusaClient(); await client.auth.login('customer', 'emailpass', { 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 data about the currently logged in user as shown below:
<script lang="ts" setup> const client = useMedusaClient(); const { customer } = await client.store.customer.retrieve()</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 in localStorage
or in a cookie
, so that you can be able to 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.store.cart.create({ region_id: 'reg_123' }); localStorage.setItem('cart_id', cart.id) // save the NEW cart to the store or the state } else { const { cart } = await client.store.cart.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 provided by Nuxt as shown below:
<script lang="ts" setup> const client = useMedusaClient(); const cartId = useCookie('cart_id', { maxAge: 60 * 60 * 24 * 365 }); if (!cartId.value) { const { cart } = await client.store.cart.create({ region_id: 'reg_123' }); cartId.value = cart.id // save the NEW cart to the store or the state } else { const { cart } = await client.store.cart.retrieve(cartId.value); // save the EXISTING cart to the store or the state }</script>
In both cases, you first check if the cart_id
is already saved in localStorage
or cookie
. If it is not saved, you create a new cart and save its id
in localStorage
or cookie
. If it is saved, you retrieve the cart from the Medusa backend and save it to the store or the state.