惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Google DeepMind News
Google DeepMind News
博客园_首页
H
Help Net Security
T
Tailwind CSS Blog
S
SegmentFault 最新的问题
GbyAI
GbyAI
Scott Helme
Scott Helme
D
Docker
Hacker News: Ask HN
Hacker News: Ask HN
P
Privacy & Cybersecurity Law Blog
Jina AI
Jina AI
雷峰网
雷峰网
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Spread Privacy
Spread Privacy
G
GRAHAM CLULEY
C
Cisco Blogs
The Hacker News
The Hacker News
F
Full Disclosure
Y
Y Combinator Blog
Blog — PlanetScale
Blog — PlanetScale
Recent Announcements
Recent Announcements
G
Google Developers Blog
量子位
K
Kaspersky official blog
Cisco Talos Blog
Cisco Talos Blog
The Cloudflare Blog
A
About on SuperTechFans
C
Cybersecurity and Infrastructure Security Agency CISA
Last Week in AI
Last Week in AI
博客园 - 三生石上(FineUI控件)
Microsoft Security Blog
Microsoft Security Blog
Martin Fowler
Martin Fowler
T
Tenable Blog
P
Palo Alto Networks Blog
H
Heimdal Security Blog
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
W
WeLiveSecurity
Schneier on Security
Schneier on Security
The Register - Security
The Register - Security
F
Fortinet All Blogs
Stack Overflow Blog
Stack Overflow Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
T
The Blog of Author Tim Ferriss
N
News and Events Feed by Topic
Hugging Face - Blog
Hugging Face - Blog
小众软件
小众软件
V
V2EX
爱范儿
爱范儿

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Building the Backend for a Project Management Tool — Express, Prisma, and the Mistakes I Made Along the Way
Chinwuba · 2026-06-21 · via DEV Community

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.