Production: security, testing and deployment · Lesson 17 of 18
API security fundamentals
Prevent injection and configure CORS, rate limits and headers without false confidence.
Security is layered: validation, per-resource authorization, parameterized queries, output encoding, TLS, dependency updates, sound secret handling, logging and monitoring. No single middleware makes an application secure. Begin with a threat model: who attacks, and what matters?
Untrusted input
Validate + authorize
Parameterized data layer
Rate limit + logs
Safe response
const allowedSort = new Set(["created_at", "title"])
function safeSort(input) {
return allowedSort.has(input) ? input : "created_at"
}
function corsOrigin(origin, allowed) {
return allowed.includes(origin) ? origin : null
}
console.log(safeSort("title"), safeSort("title; DROP TABLE tasks"))
console.log(corsOrigin("https://app.example", ["https://app.example"]) !== null)SQL values must use driver placeholders, never string concatenation. Column names often cannot be parameterized, so allowlist them. CORS is a browser policy, not authentication; non-browser clients ignore it. Rate-limit by identity or IP with correct proxy configuration and a deliberate burst policy.
Quick question
Does CORS prevent curl from calling an API?
Exercise
Write allowRole(role) accepting only student and admin, otherwise guest. Print admin guest.
Expected output: admin guest
function allowRole(role) {
}
console.log(allowRole("admin"), allowRole("admin' OR 1=1"))Learn more from
Played 0 of 2 games
Sign in to save your progress and earn XP.