$npx -y skills add tranhieutt/software_development_department --skill backend-patternsApplies production backend patterns: middleware, error handling, auth, database integration, and API design. Use when working with backend service files or when the user mentions Express, Fastify, NestJS, backend patterns, or service architecture.
| 1 | # Backend Patterns |
| 2 | |
| 3 | ## Critical rules (non-obvious) |
| 4 | |
| 5 | - **Always handle async errors in Express**: unhandled promise rejections crash the process; use `express-async-errors` or wrap every async handler |
| 6 | - **Never trust `req.body` size**: set `limit` on body-parser; default 100kb is too large for some, too small for others |
| 7 | - **`process.env` access at import time**: if accessed before `dotenv.config()`, value is undefined; call config() first in entry file |
| 8 | - **Connection pool misconfiguration**: default pool size (10) will exhaust under load; set `pool.max` based on `(num_cores * 2) + effective_spindle_count` |
| 9 | - **`res.json()` after `res.send()`**: causes "Cannot set headers after they are sent" — always `return` after sending response |
| 10 | |
| 11 | ## Express: production setup |
| 12 | |
| 13 | ```typescript |
| 14 | import express from "express"; |
| 15 | import "express-async-errors"; // patches async error handling globally |
| 16 | import helmet from "helmet"; |
| 17 | import { rateLimit } from "express-rate-limit"; |
| 18 | |
| 19 | const app = express(); |
| 20 | |
| 21 | app.use(helmet()); |
| 22 | app.use(express.json({ limit: "10kb" })); |
| 23 | app.use(rateLimit({ windowMs: 15 * 60 * 1000, max: 100 })); |
| 24 | |
| 25 | // Routes |
| 26 | app.use("/api/v1/users", userRouter); |
| 27 | app.use("/api/v1/products", productRouter); |
| 28 | |
| 29 | // 404 handler — must come after all routes |
| 30 | app.use((req, res) => res.status(404).json({ error: "Not found" })); |
| 31 | |
| 32 | // Global error handler — must have 4 params |
| 33 | app.use((err: Error, req: Request, res: Response, next: NextFunction) => { |
| 34 | const status = err instanceof AppError ? err.statusCode : 500; |
| 35 | res.status(status).json({ error: err.message }); |
| 36 | }); |
| 37 | ``` |
| 38 | |
| 39 | ## Repository pattern |
| 40 | |
| 41 | ```typescript |
| 42 | interface IUserRepository { |
| 43 | findById(id: string): Promise<User | null>; |
| 44 | findByEmail(email: string): Promise<User | null>; |
| 45 | save(user: User): Promise<User>; |
| 46 | delete(id: string): Promise<void>; |
| 47 | } |
| 48 | |
| 49 | class PgUserRepository implements IUserRepository { |
| 50 | constructor(private readonly db: Pool) {} |
| 51 | |
| 52 | async findById(id: string) { |
| 53 | const { rows } = await this.db.query( |
| 54 | "SELECT * FROM users WHERE id = $1 AND deleted_at IS NULL", [id] |
| 55 | ); |
| 56 | return rows[0] ?? null; |
| 57 | } |
| 58 | } |
| 59 | ``` |
| 60 | |
| 61 | ## Service layer with error types |
| 62 | |
| 63 | ```typescript |
| 64 | class AppError extends Error { |
| 65 | constructor(public message: string, public statusCode: number) { super(message); } |
| 66 | } |
| 67 | class NotFoundError extends AppError { constructor(msg: string) { super(msg, 404); } } |
| 68 | class ForbiddenError extends AppError { constructor(msg: string) { super(msg, 403); } } |
| 69 | |
| 70 | class UserService { |
| 71 | async getUser(id: string, requesterId: string): Promise<User> { |
| 72 | const user = await this.repo.findById(id); |
| 73 | if (!user) throw new NotFoundError(`User ${id} not found`); |
| 74 | if (user.id !== requesterId && !isAdmin(requesterId)) throw new ForbiddenError("Access denied"); |
| 75 | return user; |
| 76 | } |
| 77 | } |
| 78 | ``` |
| 79 | |
| 80 | ## JWT middleware |
| 81 | |
| 82 | ```typescript |
| 83 | import jwt from "jsonwebtoken"; |
| 84 | |
| 85 | export function authenticate(req: Request, res: Response, next: NextFunction) { |
| 86 | const token = req.headers.authorization?.split(" ")[1]; |
| 87 | if (!token) return res.status(401).json({ error: "No token" }); |
| 88 | try { |
| 89 | req.user = jwt.verify(token, process.env.JWT_SECRET!) as JWTPayload; |
| 90 | next(); |
| 91 | } catch { |
| 92 | res.status(401).json({ error: "Invalid token" }); |
| 93 | } |
| 94 | } |
| 95 | ``` |
| 96 | |
| 97 | ## Database connection with retry |
| 98 | |
| 99 | ```typescript |
| 100 | import { Pool } from "pg"; |
| 101 | |
| 102 | const pool = new Pool({ |
| 103 | connectionString: process.env.DATABASE_URL, |
| 104 | max: 20, // pool size |
| 105 | idleTimeoutMillis: 30_000, |
| 106 | connectionTimeoutMillis: 2_000, |
| 107 | }); |
| 108 | |
| 109 | // Test connection on startup |
| 110 | async function connectWithRetry(retries = 5, delay = 2000) { |
| 111 | for (let i = 0; i < retries; i++) { |
| 112 | try { |
| 113 | await pool.query("SELECT 1"); |
| 114 | console.log("DB connected"); |
| 115 | return; |
| 116 | } catch (err) { |
| 117 | if (i === retries - 1) throw err; |
| 118 | await new Promise(r => setTimeout(r, delay * (i + 1))); // exponential backoff |
| 119 | } |
| 120 | } |
| 121 | } |
| 122 | ``` |
| 123 | |
| 124 | ## Graceful shutdown |
| 125 | |
| 126 | ```typescript |
| 127 | const server = app.listen(PORT); |
| 128 | |
| 129 | async function shutdown(signal: string) { |
| 130 | console.log(`${signal} received. Shutting down gracefully.`); |
| 131 | server.close(async () => { |
| 132 | await pool.end(); // drain DB connections |
| 133 | process.exit(0); |
| 134 | }); |
| 135 | setTimeout(() => process.exit(1), 10_000); // force exit after 10s |
| 136 | } |
| 137 | |
| 138 | process.on("SIGTERM", () => shutdown("SIGTERM")); |
| 139 | process.on("SIGINT", () => shutdown("SIGINT")); |
| 140 | ``` |
| 141 | |
| 142 | ## Common pitfalls |
| 143 | |
| 144 | | Pitfall | Fix | |
| 145 | |---|---| |
| 146 | | Async handler without try/catch | Use `express-async |