This is the second stage of my CodeAlpha Full Stack internship — two projects, built in a deliberate order so the patterns from the first carry forward. First was a project management tool (auth + real-time updates with Socket.io). This one is a store: products, cart, orders. Same stack — Express, Prisma, PostgreSQL, JWT — but the interesting part isn't the CRUD, it's the order-placement flow, which is the first genuinely transactional piece of logic in the whole internship.
I'll walk through the schema decisions, the auth changes from project one, and then spend most of the time on the part that actually matters: making sure an order can never be created without correctly and atomically updating stock and clearing the cart.
The schema
model User {
id String @id @default(cuid())
name String
email String @unique
password String
role String @default("USER")
createdAt DateTime @default(now())
orders Order[]
cartItems CartItem[]
}
model Product {
id String @id @default(cuid())
name String
description String
price Float
image String?
stock Int @default(0)
category String
createdAt DateTime @default(now())
cartItems CartItem[]
orderItems OrderItem[]
}
model CartItem {
id String @id @default(cuid())
quantity Int @default(1)
user User @relation(fields: [userId], references: [id])
userId String
product Product @relation(fields: [productId], references: [id])
productId String
@@unique([userId, productId])
}
model Order {
id String @id @default(cuid())
status String @default("PENDING")
total Float
createdAt DateTime @default(now())
user User @relation(fields: [userId], references: [id])
userId String
items OrderItem[]
}
model OrderItem {
id String @id @default(cuid())
quantity Int
price Float
order Order @relation(fields: [orderId], references: [id])
orderId String
product Product @relation(fields: [productId], references: [id])
productId String
}
Two decisions worth explaining, because they're easy to get wrong if you're building this for the first time.
OrderItem.price is a snapshot, not a reference. It would be tempting to skip this field and just read product.price whenever you display an order. Don't. Product prices change over time — if you don't freeze the price at the moment of purchase, every historical order silently reflects today's price instead of what the customer actually paid. OrderItem.price is a receipt. Product.price is a price tag. They're allowed to diverge, and that divergence is the whole point.
CartItem has a compound unique constraint on [userId, productId]. Without it, adding the same product to your cart twice creates two separate rows, and now your entire cart-rendering and total-calculation logic has to merge duplicates. With the constraint in place, Prisma gives you upsert — one call that either creates the row or increments the existing one, and the database itself guarantees you can never end up with two rows for the same user/product pair.
Auth: adding roles to the JWT
The auth pattern here is the same one from the project management tool — register, hash with bcrypt, sign a JWT, verify on protected routes. The one addition is role, which defaults to "USER" and is upgraded to "ADMIN" manually via Prisma Studio (there's no signup flow for creating admins — that's intentional; a store with self-service admin registration is a security bug waiting to happen).
The detail that matters: the JWT payload needs the role baked in, not just the user id.
const accessToken = jwt.sign(
{ id: user.id, role: user.role },
process.env.ACCESS_SECRET,
{ expiresIn: "7d" }
);
Why put role in the token instead of looking it up from the database on every request? Because the entire value of a JWT is that it's self-contained — the server can verify a request is legitimate without touching the database at all. If you only put id in the payload, every admin-check becomes an extra database round-trip. Put role in at sign-time, and your admin middleware becomes a single equality check:
router.post("/", protect, (req, res, next) => {
if (req.user.role !== "ADMIN") {
return res.status(403).json({ message: "Admin access required" });
}
next();
}, createProduct);
One failure mode worth flagging because it's silent: if you forget to include role in the sign call, req.user.role is undefined everywhere downstream. undefined !== "ADMIN" still evaluates to true, so the check works in the sense that it still returns 403 — it just returns 403 to everyone, including actual admins. No error, no crash, just a completely broken feature that looks like it's functioning correctly in every log you'd check.
Cart: upsert and the stock check ordering
router.post("/cart", protect, async (req, res) => {
const { productId, quantity } = req.body;
try {
const product = await prisma.product.findUnique({
where: { id: productId },
});
if (!product) {
return res.status(404).json({ message: "Product not found" });
}
if (product.stock < quantity) {
return res.status(400).json({ message: "Low on stock" });
}
const cartItem = await prisma.cartItem.upsert({
where: {
userId_productId: {
userId: req.user.id,
productId,
},
},
update: {
quantity: { increment: quantity },
},
create: {
userId: req.user.id,
productId,
quantity,
},
});
res.status(201).json({ cartItem });
} catch (error) {
res.status(500).json({ message: "Something went wrong" });
}
});
Two things about this that aren't obvious the first time you write it.
The compound key in where is named userId_productId — Prisma builds this name automatically from the field order exactly as declared in @@unique([userId, productId]). Get the order backwards (productId_userId) and Prisma throws a schema validation error immediately, which is at least a loud failure rather than a silent one.
The stock check has to happen before the upsert, as a completely separate query. It's tempting to think the upsert alone is enough — but upsert doesn't know or care about business rules like stock levels, it only knows how to match-or-create a row. If you skip the manual check, a user's cart can silently hold more units of a product than actually exist. You won't find out until the order transaction rejects it later, at which point the error is far less useful to the person who just spent five minutes filling out a cart that was never going to check out.
Deleting a cart item needs the same ownership discipline as everything else that touches user-scoped data:
router.delete("/cart/:itemId", protect, async (req, res) => {
try {
const del = await prisma.cartItem.deleteMany({
where: { id: req.params.itemId, userId: req.user.id },
});
if (del.count === 0) {
return res.status(404).json({ message: "Cart item not found" });
}
res.status(200).json({ message: "Deleted successfully" });
} catch (error) {
res.status(500).json({ message: "Something went wrong" });
}
});
Note this uses deleteMany, not delete. Prisma's delete only accepts a unique identifier in its where clause — id alone, or a declared compound unique — it does not accept an arbitrary combination like { id, userId } unless that pair is itself declared as a compound unique constraint in the schema. deleteMany accepts any filter, and if the filter matches nothing (because the item belongs to someone else), it just deletes zero rows instead of throwing or, worse, deleting the wrong thing. That distinction — validation error vs. silently-correct no-op — is worth internalizing early, because it comes up constantly once you're writing ownership checks on every mutation.
Orders: the transaction
This is the part of the project that's actually hard, and it's hard for a good reason: placing an order isn't one write, it's four, and they all have to succeed together or not at all.
- Fetch the user's cart with product data
- Validate stock for every item
- Create the order with nested order items
- Decrement stock on every product
- Clear the cart
If step 3 succeeds but step 4 fails, you've got an order in your database for stock that was never actually reserved — a real order for a product you can't fulfill. prisma.$transaction exists specifically to prevent this: it wraps a set of writes in a single all-or-nothing unit, so a thrown error anywhere inside rolls back everything that already happened in that block.
router.post("/orders", protect, async (req, res) => {
try {
const newOrder = await prisma.$transaction(async (tx) => {
const cartItems = await tx.cartItem.findMany({
where: { userId: req.user.id },
include: { product: true },
});
if (cartItems.length === 0) {
throw new Error("Cart is empty");
}
for (const item of cartItems) {
if (item.quantity > item.product.stock) {
throw new Error(`Not enough stock for ${item.product.name}`);
}
}
const totalPrice = cartItems.reduce((sum, item) => {
return sum + item.product.price * item.quantity;
}, 0);
for (const item of cartItems) {
await tx.product.update({
where: { id: item.productId },
data: { stock: { decrement: item.quantity } },
});
}
await tx.cartItem.deleteMany({
where: { userId: req.user.id },
});
const order = await tx.order.create({
data: {
userId: req.user.id,
total: totalPrice,
items: {
create: cartItems.map((item) => ({
productId: item.productId,
quantity: item.quantity,
price: item.product.price,
})),
},
},
});
return order;
});
return res.status(201).json({ order: newOrder });
} catch (error) {
return res.status(400).json({ message: error.message });
}
});
A few details worth calling out explicitly, because they're the kind of thing that's easy to get subtly wrong.
Every call inside the callback uses tx, not prisma. This is the one rule that makes the whole transaction actually work as a unit — if you accidentally call prisma.product.update(...) instead of tx.product.update(...) inside the block, that write happens outside the transaction and won't roll back if a later step fails, defeating the entire purpose.
The price in OrderItem.create comes from item.product.price, fetched server-side — never from the request body. If a client could send its own price for an order item, they could send 0.01 and buy anything for a cent. The price the customer pays has to originate from data the server looked up itself.
Errors thrown inside the transaction should just throw — don't try to send an HTTP response from inside the callback. The outer catch block is the only place that should touch res. If you try to respond from inside the transaction and then let execution continue to an outer response as well, you get ERR_HTTP_HEADERS_SENT, because Node won't let you send two responses to one request.
The nested items.create takes an array, one entry per cart item — not a single object. An order with three different products needs three OrderItem rows. Trying to collapse a multi-product order into a single hardcoded create: {...} object will either throw (if you're missing required fields) or silently create an order that only remembers one of the products the customer actually bought.
Reading orders back out
router.get("/orders", protect, async (req, res) => {
const orders = await prisma.order.findMany({
where: { userId: req.user.id },
include: { items: { include: { product: true } } },
orderBy: { createdAt: "desc" },
});
return res.status(200).json({ orders });
});
router.get("/orders/:id", protect, async (req, res) => {
const order = await prisma.order.findUnique({
where: { id: req.params.id },
include: { items: { include: { product: true } } },
});
if (!order) return res.status(404).json({ message: "Order not found" });
if (order.userId !== req.user.id) {
return res.status(403).json({ message: "Unauthorized" });
}
return res.status(200).json({ order });
});
The single-order route is the one place I'd flag for anyone building this: it's tempting to reach for findMany out of habit since it's what you've been using everywhere else, but you're fetching exactly one order by its own primary key, and findMany returns an array — meaning order.userId would be undefined no matter who's asking, since arrays don't have that property, only the objects inside them do. findUnique gives you the object directly, which is what the ownership check actually needs to work against.
That ownership check itself matters more than it might look — without it, any authenticated user who can guess or intercept an order id can view someone else's order details, including what they bought and how much they paid. It's a two-line check, but it's the difference between a private order history and a data leak.
What's next
Backend for the store is done — schema, auth with roles, cart, and the transactional order flow. Frontend is next: product listing with debounced search, cart UI, and order history, following the same auth patterns already wired up from the first project. Full internship repo (once complete) will be linked from my profile.
Top comments (0)