#How to add metadata to a cart item when creating Medusa cart using useCreateCart() hook.
6 messages · Page 1 of 1 (latest)
@merry coral Did you find a solution for this?
if you can check it in the node modules at the backend that the team hide the cart service. You can see setMetadata in the cart service
this is what I did to use metadata in createCart or updateCart
this is I modify in backend folder at the api route.ts
import { CartService, MedusaRequest, MedusaResponse } from '@medusajs/medusa';
export async function POST(
req: MedusaRequest,
res: MedusaResponse
): Promise<void> {
const cartId = req.query.cartId;
const key = req.query.key as string;
const value = req.query.value as string | number;
const cartService = req.scope.resolve<CartService>('cartService');
try {
const cart = await cartService.retrieve(cartId as string);
if (!cart) {
res.status(404).json({ error: 'Cart not found' });
return;
}
await cartService.setMetadata(cart?.id, key, value);
res.json({
message: 'Update cart metadata successfully',
});
} catch (error) {
res.status(500).json({ error: error.message });
}
}
and for the storefront
export async function updateCartMetadata(
cartId?: string,
key?: string,
value?: string | number
) {
if (!cartId) throw new Error('cant find product');
try {
await fetch(
`${BACKEND_URL}/store/cart/metadata?cartId=${cartId}&key=${key}&value=${value}`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
}
);
} catch (error: any) {
throw error;
}
}
if you know Nextjs 13>, it can be used in the server side
@tall meteor I'm trying to do the same for TaxRate but setMetadata doesn't exist in the taxRateService
I dont see setMetadata in the TaxRate service, so you cant set the metadata for it. If you want to create setMetadata for TaxRate maybe you must modify in the service, models in backend (I didnt do it, I see the docs have the instruction).
If you want to see more details.
Just dig into backend/node_modules/@medusajs/medusa/dist/services/file.d.ts
Thank you @tall meteor