#Shopping Cart
4 messages · Page 1 of 1 (latest)
Hi @pine crest. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
To create a shopping cart in Astro using Sessions and Actions, with products stored in a content collection (JSON), you can follow these steps based on the official documentation:
1. Store Products in a Content Collection
Assume you have a content collection (e.g., src/content/products.json) with your product data.
[
{ "id": "1", "name": "Astro Figurine", "price": 19.99 },
{ "id": "2", "name": "Astro Mug", "price": 9.99 }
]
2. Define an Action to Add to Cart
Create an action (e.g., src/actions/addToCart.ts) that adds a product to the cart in the session. The session object is available as context.session in actions.
import { defineAction } from 'astro:actions';
import { z } from 'astro:schema';
export const server = {
addToCart: defineAction({
input: z.object({ productId: z.string() }),
handler: async (input, context) => {
const cart = (await context.session?.get('cart')) || [];
cart.push(input.productId);
await context.session?.set('cart', cart);
return cart;
},
}),
};
3. Use the Action in a Page
In your product page (e.g., src/pages/products/[slug].astro), call the action from a form and update the UI with the result:
---
import { actions } from 'astro:actions';
const result = Astro.getActionResult(actions.addToCart);
---
{result && !result.error && (
<p class="success">Added to cart!</p>
)}
<form method="post" action={actions.addToCart}>
<input type="hidden" name="productId" value={Astro.params.slug} />
<button type="submit">Add to Cart</button>
</form>
4. Display Cart Contents
In a cart page or component, retrieve the cart from the session:
---
const cart = await Astro.session?.get('cart');
---
<h1>Your cart</h1>
<ul>
{cart?.map((item) => (
<li>{item}</li>
))}
</ul>
Note:
- You can enhance the cart by storing product objects instead of just IDs, or by looking up product details from your content collection when rendering the cart.
- Make sure your Astro project is configured for sessions (see Sessions Guide).
- This approach does not require any client-side JavaScript for basic cart functionality.
If you need more advanced cart logic (like quantities or removing items), you can expand the action and session data structure accordingly.