12. Security Basics
12. Security Basics
Security is not a feature you bolt on at the end. These baseline practices should be in place from the first line of code.
Enforce HTTPS Everywhere
Every request and response must travel over TLS. Redirect any HTTP traffic to HTTPS automatically. Set the Strict-Transport-Security header to tell browsers to never fall back to plain HTTP:
Strict-Transport-Security: max-age=31536000; includeSubDomains
Validate and Sanitise All Inputs
Never trust data that arrives from the client. Validate every field against your expected types, lengths, and formats before your application logic touches it. Reject malformed requests early with a clear 400 Bad Request response. This stops injection attacks, buffer overflows, and malformed data from reaching your database or downstream services.
Wrap Arrays in an Object
Returning a bare JSON array at the top level of a response exposes your API to a class of browser-based attacks known as JSON hijacking. Older browsers allowed scripts on malicious pages to intercept top-level array responses. Wrapping all responses in an object envelope (see topic 6) eliminates this risk entirely.
Apply the Principle of Least Privilege
Every API key, token, or service account should carry only the permissions it actually needs. A read-only analytics consumer should never hold a token that can write or delete data. Review and rotate credentials regularly, and revoke any that are no longer in use.
Set Security Headers
In addition to Strict-Transport-Security, consider including:
X-Content-Type-Options: nosniff— prevents browsers from interpreting files as a different MIME type.X-Frame-Options: DENY— stops your API responses from being embedded in iframes (relevant if you also serve browser-facing pages).Content-Security-Policy— where applicable, restrict the sources of scripts and styles.
Audit and Log
Log every authentication event, permission change, and failed request. These logs are your first line of defence when investigating a breach or an anomaly. Never log full request bodies in production — they may contain sensitive tokens or personal data.