{"success":true,"name":"validate-the-id-before-querying-a-malformed-objectid-should-","description":"An endpoint takes an ID from the URL and passes it straight into a DB query","category":"ai-brimind","path":"ai-brimind/validate-the-id-before-querying-a-malformed-objectid-should-/SKILL.md","file":"SKILL.md","content":"---\nname: validate-the-id-before-querying-a-malformed-objectid-should-\ndescription: \"An endpoint takes an ID from the URL and passes it straight into a DB query\"\n---\n\n# Validate the ID Before Querying: A Malformed ObjectId Should Be a Clean 400, Not a 500 Crash\n\n## When to use\nYou are writing an endpoint like /api/clubs/[id] that takes an identifier from the URL or params and feeds it directly into findById or a query — with nothing checking that the value is even a validly-shaped ID first.\n\n## Example request\nGET /api/clubs/abc123 with a garbage ID → Mongoose throws a CastError trying to convert it to ObjectId, the endpoint answers 500, and your error logs fill with noise that looks like server bugs; a one-line validity check turns this into a clean 400. A valid-SHAPED ObjectId that matches no document → findById returns null, and code that immediately reads result.name crashes on 'cannot read properties of null'; 'not found' is a NORMAL outcome deserving its own 404 branch, not an accident. Bots and scanners probe your API with junk IDs all day → every probe becomes a logged 500 'crash' that drowns real errors; input-shaped rejections keep the error log meaning something. The same applies beyond Mongo: numeric IDs parsed with parseInt → 'abc' becomes NaN and matches nothing or everything weirdly; whatever the ID format, its shape is checked at the border like any other input.\n\n## Instructions\nAct as a developer who knows that the ID in a URL is user input wearing a trench coat — it looks structural, but anyone can type anything there, and bots WILL — so it gets the full border-guard treatment before it touches the database. For every endpoint receiving an identifier, do this: (1) Check the SHAPE first, before any query: for MongoDB, mongoose.Types.ObjectId.isValid(id) (or your validation layer's equivalent) — if it fails, respond immediately with a 400 and a plain message ('invalid id format'), because a malformed ID can never match anything and asking the database is pointless; letting Mongoose discover it via CastError converts a trivial bad request into a fake 500 server error, which lies to the client and pollutes your logs. For numeric or other ID schemes, same idea: parse and verify before use. (2) Then handle the second, separate outcome honestly: a well-formed ID that matches nothing. findById returning null is not an error in your server — it is the world telling you 'no such record' — so branch on it explicitly and return 404 with a consistent body per your error contract, BEFORE any code dereferences the result; the 'cannot read properties of null' crash is always a missing this-branch. (3) Where ownership matters, keep your authorization discipline fused into the same query — find by ID AND owner — so 'not yours' and 'not found' return the same 404 and the API confirms nothing about other people's data. (4) Notice the three distinct answers this creates and keep them distinct everywhere: 400 'that is not even an ID', 404 'no such thing (for you)', 200 'here it is' — three truths that generic 500s were blurring into one lie. (5) Test with thirty seconds of hostility: hit the endpoint with a garbage string, a well-formed-but-nonexistent ID, and a real one, and watch the status codes — then check the server log and confirm the first two produced NO error-level noise. Only mark the endpoint done when junk input cannot generate a 500, 'missing' has its own calm branch, and your error log is reserved for things that are actually your fault.\n\n## Metadata\n- role: developer\n- level: tactical\n- places: vibeCoding\n- origin: ai.brimind.pro skill #224\n","linked_files":[],"origin":"ai.brimind.pro","owner_id":null,"source":"router"}