Start learning free

LESSON 28 OF 58 · FULL-STACK: CART AND CHECKOUT

A Cart Before Login

Practice

A visitor who is not logged in has no user id, so their cart can't go in cart_items: every row there needs a user_id. The session can hold it instead. express-session gives each visitor their own req.session object, kept on the server between requests and found again through the session cookie. Whatever you put in it is there on that visitor's next request.

Here is the idea on another route, a list of the products a visitor has looked at:

app.post("/api/viewed", (req, res) => {
  const viewed = req.session.viewed || [];
  viewed.push(req.body.product_id);
  req.session.viewed = viewed;
  res.json(viewed);
});

A guest's cart is an object from a product's id to its quantity, like {"1": 1, "3": 1} for one Mug and one Lamp. Adding checks the stock, as the logged-in route does. When the guest logs in, each line is merged into the user's cart_items: the quantity already saved plus the guest's, but never more than the stock (Math.min(2 + 3, 4) is 4). Then the session's cart is emptied, so the same lines are never merged twice.

The check adds to the cart as a guest on the page, then logs in as Ana (who already has Mug × 2 and Lamp × 1 saved; the Lamp's stock is 1), then as Ben in the same browser:

guest: Add to cart in Mug    →  200  Cart (1)
guest: Add to cart in Lamp   →  200  Cart (2)
guest: Add to cart in Lamp   →  409  Only 1 left
guest: open /cart            →  Mug × 1 $12, Lamp × 1 $29, Total: $41
Ana logs in, opens /cart     →  Mug × 3 $36, Lamp × 1 $29, Total: $65
Ben logs in, opens /cart     →  Your cart is empty

Your task: in server/app.js, finish the guest's POST /api/cart route so it keeps the cart in req.session.cart, with a 409 beyond the stock. Then, in the login route, merge that cart into the user's cart_items and empty it.


Assignment
Follow the Coding Tutorial to keep a guest's cart in the session and merge it into the user's saved cart at login.


Hint
A new visitor's session has no cart yet: start from req.session.cart || {}, and put the object back in req.session.cart after you change it. In the login route, Object.entries gives each [productId, quantity] pair.


STEP 1 OF 12
    Ctrl + Enter to check