Course outline · 0% complete

0/29 lessons0%

Course overview →

Validating Requests

lesson 5-3 · ~10 min · 16/29

Never trust the client

Back in lesson 1-1's quiz you learned that frontend checks are decoration: anyone can send your API anything with curl, a command-line program (installed on most systems) that sends whatever HTTP request you type, like curl -X POST localhost:3000/signup -d '{...}'. No browser, no form, none of your frontend checks. So every input gets validated at the edge, the moment it enters your server, before any logic runs.

In Express, JSON bodies first need parsing:

app.use(express.json()); // middleware: parses JSON bodies into req.body

Then a validation step checks req.body against what the endpoint expects, and rejects with a 400 plus the error shape from lesson 4-3 when it fails. Real projects use libraries (zod, joi) for this, but the mechanism is a loop over expected fields, which you can write in ten lines.

Code exercise · javascript

Run this mini schema checker: each schema key names a required field and its expected typeof.

Quiz

GET /posts?page=2 arrives. Your code runs items.slice((req.query.page - 1) * 20). A user sends ?page=banana. What happens without validation?

Code exercise · javascript

Your turn. Write toPositiveInt(value, fallback): convert value with Number(...), and return it only if it is an integer of at least 1 (use Number.isInteger). Everything else, including undefined and "2.5", returns the fallback.