export async function createCart() {
try {
const res = await fetch(`${MEDUSA_BACKEND_URL}/store/carts`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
next: {
tags: ['cart']
}
});
console.log('Cart creation response', res.body);
const data = await res.json();
if (res.status === 200) {
const cart = data.cart;
const cookieStore = cookies();
cookieStore.set('_medusa_cart_id', cart.id, {
maxAge: 60 * 60 * 24 * 7
});
console.log('Cart created', cart);
revalidateTag('cart');
return cart as Cart;
} else {
throw new Error('Failed to create cart');
}
} catch (error) {
console.log(`Error creating cart: ${error}`);
}
}
export const getCart = cache(async function (cartId: string) {
console.log('Cart ID from the cookie', cartId);
if (!cartId) {
console.log('No cart ID found');
return null;
}
const expand =
'customer,shipping_address,billing_address,items.variant.options,items.variant.prices,payment_sessions,shipping_methods';
const response = await fetch(`${MEDUSA_BACKEND_URL}/store/carts/${cartId}?expand=${expand}`, {
method: 'GET',
next: {
tags: ['cart']
}
});
const data = await response.json();
if (response.status === 200) {
const cart = data.cart;
return cart as Cart;
} else {
console.log('Failed to get cart');
return null;
}
});
export async function getOrSetCart2() {
const cartId = cookies().get('_medusa_cart_id')?.value;
let cart;
if (cartId) {
console.log('Getting cart from cookie', cartId);
cart = await getCart(cartId).then((cart) => cart);
}
if (!cart) {
console.log('Creating new cart');
cart = await createCart();
if (cart) {
revalidateTag('cart');
}
}
return cart as Cart;
}
How to get the cart value in a server component and a client component?