Implementing Security Best Practices
1. Validating User Input
| Library | Use |
|---|---|
zod / valibot | Type-safe schema validation |
joi / ajv | JSON Schema validation |
| Validate at boundary | HTTP, queue, file uploads |
2. Sanitizing Input (preventing XSS)
| Tool | Use |
|---|---|
DOMPurify | Sanitize HTML |
| Output encoding | Escape on render, not on store |
| CSP header | Defense in depth |
3. Preventing SQL Injection
Example: Parameterized query
// SAFE
await pool.query("SELECT * FROM users WHERE id = $1", [id]);
// UNSAFE — string concat
await pool.query(`SELECT * FROM users WHERE id = ${id}`);
4. Using Prepared Statements
| Driver | Approach |
|---|---|
| pg | { text, name, values } with name = prepared |
| mysql2 | connection.execute(sql, params) |
| better-sqlite3 | db.prepare(sql).get(params) |
5. Implementing Authentication
| Mechanism | Use |
|---|---|
| Sessions + cookies | Server-rendered apps |
| JWT | Stateless APIs (rotate / short TTL) |
| OAuth 2 / OIDC | Third-party login |
| Passwords | argon2id (preferred) or bcrypt |
6. Implementing Authorization
| Model | Use |
|---|---|
| RBAC | Roles → permissions |
| ABAC | Attribute-based rules |
| ReBAC (Zanzibar) | Relationship graphs |
| Always check at server | Never trust client |
7. Using HTTPS
| Practice | Detail |
|---|---|
| TLS 1.2+ only | Disable SSLv3 / TLS 1.0 |
| HSTS header | Force HTTPS in browser |
| Auto-renew certs | Let's Encrypt + certbot / acme.sh |
8. Implementing Rate Limiting
| Library | Detail |
|---|---|
express-rate-limit | Per-IP windowed limits |
rate-limiter-flexible | Redis-backed, distributed |
| API gateway | Kong, Envoy, NGINX |
9. Using Helmet for Security Headers
Example
import helmet from "helmet";
app.use(helmet());
// Sets CSP, X-Frame-Options, X-Content-Type-Options, Strict-Transport-Security, etc.
10. Preventing CSRF
| Technique | Detail |
|---|---|
| SameSite cookies | SameSite=Lax (default) or Strict |
| CSRF token | Per-session synchronizer token |
| Custom header check | For JSON APIs |
11. Securing Dependencies (npm audit)
| Command | Use |
|---|---|
npm audit | List vulnerabilities |
npm audit fix | Auto-update where possible |
npm audit signatures | Verify package signatures |
| Dependabot / Renovate | Automated PRs |
| Snyk / Socket | Deeper vuln + supply-chain checks |
12. Using Permission Model (--permission flag)
| Flag | Effect |
|---|---|
--permission v20+ | Enable permission model |
--allow-fs-read=<path> | Whitelist read paths |
--allow-fs-write=<path> | Whitelist write paths |
--allow-child-process | Allow spawning |
--allow-worker | Allow worker_threads |
process.permission.has("fs.read", path) | Check at runtime |