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 ruleP1stack specificStack: typescript
typesmiddlewarecorrectnessapi-routes
Don't type a request as having a field that isn't populated yet
Typing a handler's `req` as carrying an enriched field (e.g. `userId`) before any middleware has set it lies about the runtime shape; only widen the type after the value is actually attached.
PR: hegnar-forum-web · org-mining-hist-2026-06Created: Jun 20, 2026
Bad example
Old codets
| 1 | // req.userId is never set before this point |
| 2 | const handler = async (req: RequestWithUserId, res: NextApiResponse) => { |
| 3 | const { userId } = req; // undefined at runtime |
| 4 | }; |
Explanation (EN)
Objašnjenje (HR)
Good example
New codets
| 1 | const handler = async (req: NextApiRequest, res: NextApiResponse) => { |
| 2 | await attachUserId(req, res, async () => { |
| 3 | const { userId } = req as RequestWithUserId; // only after it's set |
| 4 | }); |
| 5 | }; |
Explanation (EN)
Objašnjenje (HR)