Rules Hub
Coding Rules Library
← Back to all rules
Rule priority, scope & exceptions
Use this to align rules with the senior-level structure (P0/P1/P2, scope, exceptions/tradeoffs).
backend ruleP0universalStack: node
validationapierror-handling
Validate request payloads before side effects
Validation prevents bad data from reaching the database and gives clients clear errors.
Created: Mar 26, 2026
Bad example
Old codets
| 1 | app.post("/users", async (req, res) => { |
| 2 | const user = await db.user.create({ data: req.body }); |
| 3 | res.json(user); |
| 4 | }); |
Explanation (EN)
The handler trusts the request body shape. Malformed payloads can cause runtime errors or corrupt data.
Objašnjenje (HR)
Handler vjeruje formatu tijela. Losi payloadi mogu uzrokovati greske ili lose podatke.
Good example
New codets
| 1 | const UserSchema = z.object({ name: z.string(), email: z.string().email() }); |
| 2 |
|
| 3 | app.post("/users", async (req, res) => { |
| 4 | const parsed = UserSchema.safeParse(req.body); |
| 5 | if (!parsed.success) return res.status(400).json({ errors: parsed.error.issues }); |
| 6 | const user = await db.user.create({ data: parsed.data }); |
| 7 | res.json(user); |
| 8 | }); |
Explanation (EN)
The handler validates before any side effects. Clients get structured 400 errors and the database stays clean.
Objašnjenje (HR)
Validacija ide prije side effecta. Klijenti dobiju jasne 400 greske, a baza ostaje cista.