Secure Coding Practices Every Developer Should Know
Essential security practices: input validation, authentication, encryption, and common vulnerabilities to avoid.

During a code review I once saw a file download endpoint built like this: path.join("uploads", req.query.file). It worked in every test. A colleague then requested ?file=../../.env and read our configuration file in about thirty seconds. Nobody on the team was careless. We simply had never been shown the failing version next to the fixed one.
That is the format of this post. Instead of a list of principles, here are the code-level habits that prevent the vulnerabilities I see most often, each as a before-and-after pattern you can recognize in review. The examples are TypeScript on Node, but the ideas carry to any stack. For the web-layer threats (access control, SQL injection, XSS, CSRF), start with web security fundamentals most teams get wrong; this post covers the rest of the checklist.
Quick takeaways
- Validate every external input against a schema at the boundary, and reject unknown fields instead of ignoring them.
- Hash passwords with argon2id, generate tokens with a cryptographic random source, and compare secrets in constant time.
- Resolve file paths against a fixed root and check the result. Never concatenate user input into a path.
- Allow-list the destinations your server may fetch, to prevent server-side request forgery (SSRF).
- Redact secrets at the logger level, and fail CI when dependencies have known high-severity vulnerabilities.
How should I validate input at the boundary?
Never trust user input: not request bodies, not query strings, not headers, not webhook payloads, not files. Check type, length and format in one place, as early as possible, and reject anything unexpected. A schema library makes this the default instead of a discipline:
import { z } from "zod";
const CreateUser = z
.object({
email: z.string().trim().toLowerCase().email().max(254),
displayName: z.string().trim().min(1).max(80),
age: z.number().int().min(13).max(120).optional(),
})
.strict(); // unknown fields are an error, not silently dropped
app.post("/users", (req, res) => {
const parsed = CreateUser.safeParse(req.body);
if (!parsed.success) {
return res.status(400).json({ errors: parsed.error.flatten().fieldErrors });
}
// parsed.data is typed and safe to use from here on
});
Validation is not the same as escaping. Parameterized queries stop SQL injection; output encoding stops XSS. Validation narrows what reaches those layers, but it never replaces them.
How do I store passwords and generate tokens correctly?
Never store plaintext or fast hashes such as plain SHA-256. Use a slow, memory-hard algorithm designed for passwords. The argon2 library stores the salt inside the encoded hash, so there is no separate salt column to get wrong:
import argon2 from "argon2";
import { randomBytes, timingSafeEqual } from "node:crypto";
export const hashPassword = (plain: string) =>
argon2.hash(plain, { type: argon2.argon2id });
export const verifyPassword = (hash: string, plain: string) =>
argon2.verify(hash, plain);
// Session IDs, reset tokens, API keys: always from a CSPRNG, never Math.random()
export const newToken = () => randomBytes(32).toString("base64url");
export function safeEqual(a: string, b: string): boolean {
const left = Buffer.from(a);
const right = Buffer.from(b);
return left.length === right.length && timingSafeEqual(left, right);
}
Use safeEqual for anything secret that you compare directly, such as webhook signatures or API keys; a normal === can leak information through timing. Session handling, expiry and token trade-offs are covered in authentication patterns: session, JWT and OAuth. For sensitive operations, add multi-factor authentication.
How do I stop path traversal in file handling?
Resolve the path against a fixed root and verify that the result is still inside it. This also defeats absolute paths, because path.resolve discards the root when the second argument is absolute:
import path from "node:path";
const UPLOAD_ROOT = path.resolve("/var/app/uploads");
export function resolveUpload(name: string): string {
const target = path.resolve(UPLOAD_ROOT, name);
if (!target.startsWith(UPLOAD_ROOT + path.sep)) {
throw new Error("path escapes upload root");
}
return target;
}
The better design is to avoid user-controlled file names entirely: store uploads under a generated ID and keep the original name as metadata.
How do I prevent SSRF when my server fetches URLs?
Any feature that fetches a user-supplied URL (webhooks, link previews, image imports) can be pointed at your cloud metadata endpoint or an internal service. Prefer an allow-list of destinations, force HTTPS, and refuse redirects:
const ALLOWED_HOSTS = new Set(["api.github.com", "hooks.slack.com"]);
export async function fetchAllowed(rawUrl: string): Promise<Response> {
const url = new URL(rawUrl);
if (url.protocol !== "https:" || !ALLOWED_HOSTS.has(url.hostname)) {
throw new Error("destination not allowed");
}
return fetch(url, { redirect: "error", signal: AbortSignal.timeout(5000) });
}
If users genuinely need arbitrary destinations, resolve the hostname yourself and block private, loopback and link-local address ranges, then connect to the IP you checked. Checking a hostname once and fetching it later leaves a gap for DNS rebinding.
What should never end up in logs?
Passwords, tokens, session cookies, full card numbers and personal data. Developers rarely log these on purpose; they appear when someone logs a whole request object during debugging. Redact at the logger so the mistake is harmless:
import pino from "pino";
export const logger = pino({
redact: {
paths: ["req.headers.authorization", "req.headers.cookie", "*.password", "*.token"],
censor: "[redacted]",
},
});
The same care applies to error messages returned to clients: send a generic message and an error ID, and keep the stack trace in your logs. Error handling patterns explains how to separate the two.
How do I keep dependencies from becoming the weak spot?
Most of your code is other people's code, so scanning belongs in CI, where it cannot be forgotten:
- name: Audit production dependencies
run: npm audit --omit=dev --audit-level=high
Pair it with automated update pull requests so fixes arrive in small steps. Commit your lockfile and install from it in CI.
Which classic vulnerabilities map to which habit?
The OWASP Top 10 changes between editions, but the habits behind it are stable:
- Injection: parameterized queries plus boundary validation.
- Broken authentication and sensitive data exposure: argon2id, TLS in transit, strong encryption at rest, and managed keys.
- Broken access control: check permissions on every request on the server; never rely on client-side checks, and give each service only the privileges it needs.
- Security misconfiguration: secure defaults, no debug mode in production, and secrets outside the repository.
- Vulnerable components and insufficient logging: dependency scanning in CI and structured logs you can actually search after an incident.
What should I do this week?
Add two things to your next code review checklist: "where does external input enter, and what validates it?" and "does anything user-controlled reach a path, a URL or a query?" Then pick one endpoint, put the Zod schema in front of it, and add the npm audit step to your pipeline. Both changes take under an hour, and the review habit is the one that scales; see code review practices that catch bugs without killing velocity for how to fit it in.
Uğur Kaval
AI/ML Engineer & Full Stack Developer specializing in building innovative solutions with modern technologies. Passionate about automation, machine learning, and web development.


