#CodeAlpha

O compartilhamento de falsas informações prejudica a imagem do artista, por favor, enviem template para o e-mail do veículo de comunicação solicitando que seja feita devida correção.

docs.google.com/document/d/1...
PROTECT NAMJOON
cr: cyphereport Send to: To: codealpha@yna.co.kr & ksjin@yna.co.kr Subject / Título: CORRECT INFORMATION ABOUT BTS RM Email structure / Corpo do e-mail: Hello, Yonhap News TV, We have noticed ...
docs.google.com
September 13, 2024 at 8:49 PM
não sei se vocês estão cientes sobre oque está rolando, mas tem um portal de notícias divulgando informações falsas e com erros de digitação sobre o 🐨, irei deixa um template para o portal aqui, peço que enviem para que a correção seja feita o mais rápido possível.

docs.google.com/document/d/1...
PROTECT NAMJOON
cr: cyphereport Send to: To: codealpha@yna.co.kr & ksjin@yna.co.kr Subject / Título: CORRECT INFORMATION ABOUT BTS RM Email structure / Corpo do e-mail: Hello, Yonhap News TV, We have noticed ...
docs.google.com
September 13, 2024 at 9:12 PM
🚨 ATENÇÃO AQUI 🚨

um portal de noticias está divulgando informações falsas e com erros de digitação à respeito do 🐨. pfvr enviem esse template para o portal para que a correção dos erros sejam feitas!!

docs.google.com/document/d/1...
PROTECT NAMJOON
cr: cyphereport Send to: To: codealpha@yna.co.kr & ksjin@yna.co.kr Subject / Título: CORRECT INFORMATION ABOUT BTS RM Email structure / Corpo do e-mail: Hello, Yonhap News TV, We have noticed ...
docs.google.com
September 13, 2024 at 8:14 PM
🚨 ATENÇÃO 🚨

um portal de notícias divulgou informações falsas e com erros de digitação referentes ao 🐨, por favor encaminhem o template de email para o portal para que as correções sejam feitas!!
docs.google.com/document/d/1...
PROTECT NAMJOON
cr: cyphereport Send to: To: codealpha@yna.co.kr & ksjin@yna.co.kr Subject / Título: CORRECT INFORMATION ABOUT BTS RM Email structure / Corpo do e-mail: Hello, Yonhap News TV, We have noticed ...
docs.google.com
September 13, 2024 at 9:05 PM
ENVIEM O TEMPLATE PARA O EMAIL PARA A EMISSORA E ENTREM NAS REPORTS PARA DENUNCIAR. OUTROS MEMBROS ESTÃO SENDO ATACADOS TAMBÉM!!!!

docs.google.com/document/d/1...
PROTECT NAMJOON
cr: cyphereport Send to: To: codealpha@yna.co.kr & ksjin@yna.co.kr Subject / Título: CORRECT INFORMATION ABOUT BTS RM Email structure / Corpo do e-mail: Hello, Yonhap News TV, We have noticed ...
docs.google.com
September 13, 2024 at 11:41 PM
🚨 ATENÇÃO 🚨

um portal de notícias divulgou informações falsas e com erros de digitação referentes ao 🐨, por favor encaminhem o template de email para o portal para que as correções sejam feitas!!

docs.google.com/document/d/1...
PROTECT NAMJOON
cr: cyphereport Send to: To: codealpha@yna.co.kr & ksjin@yna.co.kr Subject / Título: CORRECT INFORMATION ABOUT BTS RM Email structure / Corpo do e-mail: Hello, Yonhap News TV, We have noticed ...
docs.google.com
September 13, 2024 at 9:40 PM
O compartilhamento de falsas informações prejudica a imagem do artista, por favor, enviem template para o e-mail do veículo de comunicação solicitando que seja feita devida correção.

docs.google.com/document/d/1...
PROTECT NAMJOON
cr: cyphereport Send to: To: codealpha@yna.co.kr & ksjin@yna.co.kr Subject / Título: CORRECT INFORMATION ABOUT BTS RM Email structure / Corpo do e-mail: Hello, Yonhap News TV, We have noticed ...
docs.google.com
September 14, 2024 at 1:48 AM
if anyone wants to send them emails, yonhap’s email is codealpha@yna.co.kr
E foi a yonhap de novo mentindo em artigo q gerou isso, pq o local é um café normal q fica na frente da base
September 13, 2024 at 7:09 PM
🚨 > ARMY'S ATENÇÃO AQUI < 🚨

um portal de noticias está divulgando informações falsas e com erros de digitação à respeito ao 🐨, por favor, enviem template para o e-mail do veículo de comunicação solicitando que seja feita devida correção.

🔗: docs.google.com/document/d/1...
PROTECT NAMJOON
cr: cyphereport Send to: To: codealpha@yna.co.kr & ksjin@yna.co.kr Subject / Título: CORRECT INFORMATION ABOUT BTS RM Email structure / Corpo do e-mail: Hello, Yonhap News TV, We have noticed ...
docs.google.com
September 13, 2024 at 9:16 PM
‼️ARMYs, saiu o modelo abaixo de template que deve ser enviado à HYBE em relação à situação atual envolvendo o 🐨.

mudem de assusto para não virar spam.‼️

docs.google.com/document/d/1...
PROTECT NAMJOON
cr: cyphereport Send to: To: codealpha@yna.co.kr & ksjin@yna.co.kr Subject / Título: CORRECT INFORMATION ABOUT BTS RM Email structure / Corpo do e-mail: Hello, Yonhap News TV, We have noticed ...
docs.google.com
September 14, 2024 at 1:10 PM
A ‘Yonhap News TV’ divulgou que o evento de aniversário do 🐨 ocorreu em uma PX militar (o que é proibido),
Mas sabemos que o evento foi organizado por uma fb em um café próximo.
Enviem o e-mail de template pois prejudica a imagem do artista

docs.google.com/document/d/1...
PROTECT NAMJOON
cr: cyphereport Send to: To: codealpha@yna.co.kr & ksjin@yna.co.kr Subject / Título: CORRECT INFORMATION ABOUT BTS RM Email structure / Corpo do e-mail: Hello, Yonhap News TV, We have noticed ...
docs.google.com
September 13, 2024 at 9:17 PM
🔥 HOT JOB ALERT: CodeAlpha is hiring for Intern! Apply instantly at thenewviews.com! #hiring #CodeAlpha #jobs
August 17, 2026 at 7:37 AM
Building an E-commerce Backend: Auth, Cart, and Transactional Orders with Prisma
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. 1. Fetch the user's cart with product data 2. Validate stock for every item 3. Create the order with nested order items 4. Decrement stock on every product 5. 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.
dev.to
July 8, 2026 at 10:09 PM
January 18, 2026 at 5:45 AM
🚨 > ARMY'S ATENÇÃO AQUI < 🚨

um portal de noticias está divulgando informações falsas e com erros de digitação à respeito ao 🐨, por favor, enviem template para o e-mail do veículo de comunicação solicitando que seja feita devida correção.

🔗 - docs.google.com/document/d/1...
PROTECT NAMJOON
cr: cyphereport Send to: To: codealpha@yna.co.kr & ksjin@yna.co.kr Subject / Título: CORRECT INFORMATION ABOUT BTS RM Email structure / Corpo do e-mail: Hello, Yonhap News TV, We have noticed ...
docs.google.com
September 13, 2024 at 9:56 PM
O yonhap news tv postou um artigo espalhando algumas mentiras referente ao evento de aniversário do nam. Enviem o tamplete abaixo pedindo para eles corrigir o erro‼️

Mudem algumas palavras pra evitar spam!

docs.google.com/document/d/1...
PROTECT NAMJOON
cr: cyphereport Send to: To: codealpha@yna.co.kr & ksjin@yna.co.kr Subject / Título: CORRECT INFORMATION ABOUT BTS RM Email structure / Corpo do e-mail: Hello, Yonhap News TV, We have noticed ...
docs.google.com
September 14, 2024 at 11:22 PM
🚨| ARMYs, enviem o template abaixo para a empresa, é muito importante ‼️
docs.google.com/document/d/1...
PROTECT NAMJOON
cr: cyphereport Send to: To: codealpha@yna.co.kr & ksjin@yna.co.kr Subject / Título: CORRECT INFORMATION ABOUT BTS RM Email structure / Corpo do e-mail: Hello, Yonhap News TV, We have noticed ...
docs.google.com
September 14, 2024 at 2:29 AM
January 18, 2026 at 5:42 AM
🚨ATENÇÃO ARMYS🚨

Um portal de notícias postou um artigo contendo informações falsas e erros ortográficos, no nome do 🐨, encaminhem o templante para que seja corrigido esse erro‼️

• Alterem algumas palavras para evitar spam!

📎 docs.google.com/document/d/1...
PROTECT NAMJOON
cr: cyphereport Send to: To: codealpha@yna.co.kr & ksjin@yna.co.kr Subject / Título: CORRECT INFORMATION ABOUT BTS RM Email structure / Corpo do e-mail: Hello, Yonhap News TV, We have noticed ...
docs.google.com
September 13, 2024 at 9:50 PM
Building the Backend for a Project Management Tool — Express, Prisma, and the Mistakes I Made Along the Way
I'm currently completing a Full Stack Development internship with CodeAlpha, and the first project is a collaborative project management tool. Think stripped-down Trello/Asana users create projects, invite members, organize tasks across boards, assign them, comment on them, and get real-time updates via Socket.io. Before touching the frontend, I spent considerable time getting the backend right. This post documents exactly what I built, the patterns I now understand at a deeper level, and the specific mistakes I caught while writing every line myself. # The Stack Express.js — HTTP server and routing Prisma — ORM for database queries PostgreSQL via Supabase — relational database JWT + bcryptjs — authentication Socket.io — real-time updates (coming in the next post) ## The Schema First Everything downstream depends on the schema being right, so this is where the thinking happened. A few decisions worth explaining: ### ProjectMember as a junction table Users and Projects have a many-to-many relationship a user can be in many projects, a project can have many users. `ProjectMember` is the junction table that sits between them, and it carries extra data: the user's role (OWNER or MEMBER). prisma model ProjectMember { id String @id @default(cuid()) role String @default("MEMBER") user User @relation(fields: [userId], references: [id]) userId String project Project @relation(fields: [projectId], references: [id]) projectId String @@unique([userId, projectId]) } The `@@unique([userId, projectId])` at the bottom is a model-level constraint — it means a user can only appear once per project. It also creates a named composite key `userId_projectId` that Prisma exposes for lookups, which comes in useful when checking membership: js const checkMember = await prisma.projectMember.findUnique({ where: { userId_projectId: { userId: req.user.id, projectId: id, }, }, }) ### Tasks belong to Boards, not Projects This is the key architectural decision for Kanban. Each board represents a column — To Do, In Progress, Done. Moving a task between columns is just updating its boardId. No status enum on the task, no column type field — the board it belongs to is its status. Clean and simple. Board ordering prisma model Board { id String @id @default(cuid()) name String order Int ... } The order field controls column ordering. When you query boards, you sort by order: 'asc' and columns always render in the right sequence. ### The Shared Prisma Client Ai's first instinct was to instantiate `PrismaClient` in every route file. That's wrong. Each instantiation opens a new connection pool — in development with hot reloading, this causes connection exhaustion fast. The correct pattern(i don dey correct Ai sef) is one shared instance across the entire app: js // server/src/lib/prisma.js import { PrismaClient } from '@prisma/client' const prisma = new PrismaClient() export default prisma Every route file imports from here. One instance, one connection pool. This is a pattern worth internalizing early because it applies beyond Prisma — any stateful singleton (database connections, logger instances, cache clients) should be initialized once and shared. ### Auth Middleware The protect middleware guards every protected route. It reads the Authorization header, extracts the Bearer token, verifies it against the JWT secret, and attaches the decoded payload to req.user so downstream handlers can access the user's id. js export function protect(req, res, next) { const token = req.headers.authorization?.split(' ')[1] if (!token) return res.status(401).json({ message: 'Not authorized' }) try { const payload = jwt.verify(token, process.env.JWT_SECRET) req.user = payload next() } catch { return res.status(401).json({ message: 'Invalid token' }) } } The optional chaining on `req.headers.authorization?.split(' ')[1]` matters. If the header doesn't exist at all, calling `.split()` on undefined throws a TypeError. Optional chaining short-circuits and returns undefined, which the null check then handles cleanly. To apply it across an entire router instead of adding it to each individual route: js const router = Router() router.use(protect) // applies to every route below this line ### Why No Refresh Tokens The standard auth pattern for production apps uses short-lived access tokens (15 minutes) paired with long-lived refresh tokens. When the access token expires, the client silently exchanges the refresh token for a new one without prompting the user to log in again. Implementing this properly requires: Storing refresh tokens in the database A /refresh endpoint Token rotation on every use Storing the refresh token in an httpOnly cookie Revocation logic for logout For an internship project, that's meaningful infrastructure overhead with no real benefit. Instead, I set expiresIn: '7d' on the access token. The user stays logged in for a week, the token expires, they log in again. Simple, works fine at this scope. The tradeoff is a stolen access token has a longer damage window — but for a portfolio project management app, that's not a real concern. In production systems, refresh tokens are absolutely worth implementing correctly. Here, they're over-engineering. ## Project Creation with `$transaction` Creating a project is not a single write. It's three: Create the Project record Create a ProjectMember record making the creator an OWNER Create three default Board records — To Do, In Progress, Done If the project creates successfully but the membership write fails, you have a project with no owner. If boards fail, you have a project with no columns. Either scenario is corrupted data. `prisma.$transaction` wraps all three writes atomically — either all succeed together, or if any one fails, everything rolls back like nothing happened: js const newProject = await prisma.$transaction(async (tx) => { const project = await tx.project.create({ data: { name, description } }) await tx.projectMember.create({ data: { userId: req.user.id, projectId: project.id, role: 'OWNER' } }) await tx.board.createMany({ data: [ { projectId: project.id, name: 'To Do', order: 0 }, { projectId: project.id, name: 'In Progress', order: 1 }, { projectId: project.id, name: 'Done', order: 2 }, ] }) return project }) Inside the transaction callback, you use `tx` instead of `prisma`. The `tx` is a transactional client — every operation through it participates in the same atomic unit. Note that createMany takes `{ data: [...] }` as an object with a data key, not a plain array. ## Prisma Relations Always Return Arrays This one caught me during the task delete route, and it's worth highlighting because it will catch you too. When you include a relation that's defined as RelationModel[] in your schema, Prisma always returns an array — even when you filter it down to a single record with a where clause inside the include. I needed to check if the requesting user was a project owner. I included memberships filtered to the current user: js include: { project: { include: { memberships: { where: { userId: req.user.id } } } } } Then tried to access the role like this: `jsfindTask.board.project.memberships.role // undefined` That returns undefined because memberships is an array. The `[]` in `ProjectMember[]` in your schema is the tell. You always need to index into it first: js const membership = findTask.board.project.memberships[0] if (!membership || membership.role !== 'OWNER') { return res.status(403).json({ message: 'Not authorized' }) } The alternative is using findFirst with a where clause instead of filtering inside include — that returns a single object directly. Either approach works, just be consistent. ### Authorization Logic — Getting the Conditions Right The task delete route was the most logic-heavy. Two types of users can delete a task — the creator or a project OWNER. Everyone else gets blocked. The condition that tripped me up was the operator choice between && and ||. The correct condition in plain English: "block if the user is NOT the creator AND they are also NOT an owner." Both conditions must be true to block. js if ( findTask.createdById !== req.user.id && (!membership || membership.role !== 'OWNER') ) { return res.status(403).json({ message: 'Not authorized' }) } Using || instead of && would block creators who aren't owners, which is wrong. Think it through before writing authorization conditions — they're the easiest place to introduce subtle bugs that only surface in edge cases. ## Route Ordering Matters In the notifications router, I have two PATCH routes: PATCH /read-all PATCH /:id/read Express matches routes top to bottom. If `/:id` is declared first, Express will match the string "read-all" as the id parameter and hit the wrong handler entirely. The fix is straightforward — always declare specific routes before parameterized ones. This applies across your entire Express app too. `GET /api/posts/feed` must come before `GET /api/posts/:id` or "feed" gets treated as an id. The Full Route Map POST /api/auth/register POST /api/auth/login GET /api/projects POST /api/projects GET /api/projects/:id POST /api/projects/:id/members DELETE /api/projects/:id POST /api/boards/:boardId/tasks PATCH /api/tasks/:id DELETE /api/tasks/:id GET /api/tasks/:taskId/comments POST /api/tasks/:taskId/comments GET /api/notifications PATCH /api/notifications/read-all PATCH /api/notifications/:id/read All routes tested in Postman — register, login, create project, fetch projects, all working. ### What's Next Socket.io integration for real-time task and comment updates. After that, the full frontend — five pages, drag-and-drop with @dnd-kit, and the ProjectBoard component which carries most of the complexity. The backend patterns here — the shared Prisma client, transactions, relation arrays, authorization logic — carry directly into the next two projects in this internship. Get them right once and they become instinct.
dev.to
June 20, 2026 at 5:42 PM