Node.js Security Best Practices: Harden an Express API with Runnable Examples
Build and test a small Express transfer API that layers authentication, strict Zod validation, authorisation, rate limiting, safe errors and dependency hygiene.
KnowledgeGate Team
Exam prep & CS education

An Express route can return correct JSON yet trust unvalidated data, compare secrets carelessly, accept unlimited requests, or leak failures. The runnable transfer API rejects unsafe requests in layers.
The runnable transfer API authenticates with an environment token, stores balances in memory, and applies a localhost rate limit. Production still needs maintained identity, durable transactions, TLS, and deliberate proxy controls.
1. Node.js security starts with boundaries, not one magic package
Authentication identifies callers; authorisation determines permissions. Validation enforces the expected shape before work begins. Resource controls cap bytes, time, and attempts.
Helmet changes response headers; it does not validate JSON, encrypt traffic, authorise callers, or repair dependencies. The official Node.js security guidance treats HTTP denial of service, timing exposure, malicious modules, and prototype pollution as application concerns. Express guidance also recommends validation, TLS, Helmet, brute-force protection, and dependency review. No checklist guarantees security.
Actor u-101 starts at 5000, recipient u-204 at 300, and a transfer of 1250 ends with balances of 3750 and 1550. Rejections perform no mutation and return a controlled status and code.

2. Build the runnable Express security baseline
Create the project:
mkdir node-security-demo
cd node-security-demo
npm init -y
npm install express helmet express-rate-limit zodSet "type": "module" in package.json, create server.mjs, and add this listing. The limiter precedes JSON parsing. Localhost is only a teaching case; production IP identity needs a configured trusted-proxy topology.
import express from 'express';
import helmet from 'helmet';
import rateLimit from 'express-rate-limit';
import { z } from 'zod';
import { createHash, timingSafeEqual, randomUUID } from 'node:crypto';
import { createServer } from 'node:http';
const expectedToken = process.env.API_TOKEN;
if (!expectedToken) throw new Error('API_TOKEN is required');
const app = express();
app.disable('x-powered-by');
app.use(helmet());
app.use('/api', (req, _res, next) => {
req.id = req.get('x-request-id') || randomUUID();
next();
});
const apiLimiter = rateLimit({
windowMs: 60_000,
limit: 5,
standardHeaders: true,
legacyHeaders: false,
skipSuccessfulRequests: false,
skipFailedRequests: false,
handler: (_req, res) => res.status(429).json({
error: { code: 'RATE_LIMITED' }
})
});
app.use('/api', apiLimiter);
app.use('/api', express.json({ limit: '10kb', strict: true }));
function digest(value) {
return createHash('sha256').update(value).digest();
}
function authenticate(req, res, next) {
const match = req.get('authorization')?.match(/^Bearer ([^\s]+)$/);
const accepted = match && timingSafeEqual(digest(match[1]), digest(expectedToken));
if (!accepted) {
return res.status(401).json({ error: { code: 'UNAUTHENTICATED' } });
}
req.actor = { id: 'u-101' };
next();
}
const transferSchema = z.object({
toUserId: z.string().regex(/^u-\d{3}$/),
amount: z.number().int().min(1).max(2000)
}).strict();
const balances = new Map([['u-101', 5000], ['u-204', 300]]);
let nextTransferId = 1;
app.post('/api/transfers', authenticate, (req, res) => {
const parsed = transferSchema.safeParse(req.body);
if (!parsed.success) {
return res.status(400).json({ error: { code: 'INVALID_BODY' } });
}
const { toUserId, amount } = parsed.data;
if (toUserId === req.actor.id) {
return res.status(403).json({ error: { code: 'SELF_TRANSFER_FORBIDDEN' } });
}
if (!balances.has(toUserId)) {
return res.status(404).json({ error: { code: 'RECIPIENT_NOT_FOUND' } });
}
const fromBalance = balances.get(req.actor.id);
if (amount > fromBalance) {
return res.status(409).json({ error: { code: 'INSUFFICIENT_FUNDS' } });
}
const newFromBalance = fromBalance - amount;
const newToBalance = balances.get(toUserId) + amount;
balances.set(req.actor.id, newFromBalance);
balances.set(toUserId, newToBalance);
const id = `tx-${String(nextTransferId++).padStart(4, '0')}`;
return res.status(201).json({ data: {
id,
fromUserId: req.actor.id,
toUserId,
amount,
fromBalance: newFromBalance,
toBalance: newToBalance
}});
});
app.use((err, req, res, next) => {
if (res.headersSent) return next(err);
let status = 500;
let code = 'INTERNAL_ERROR';
if (err.type === 'entity.too.large') {
status = 413;
code = 'PAYLOAD_TOO_LARGE';
} else if (err.type === 'entity.parse.failed') {
status = 400;
code = 'INVALID_JSON';
}
console.error({ requestId: req.id, errorName: err.name });
return res.status(status).json({ error: { code, requestId: req.id } });
});
const server = createServer(app);
server.headersTimeout = 10_000;
server.requestTimeout = 15_000;
server.keepAliveTimeout = 5_000;
server.timeout = 30_000;
server.listen(3000, '127.0.0.1');Run API_TOKEN='kg-demo-token-7f9c-2026' node server.mjs. This token is a disposable fixture; never commit it.
3. Authenticate, validate and authorise before mutation
The middleware accepts only Authorization: Bearer <token>. It hashes candidate and expected values with SHA-256, then uses timingSafeEqual on fixed-length digests. Replace this single-token mapper with maintained session or token verification in production.
Zod requires {toUserId: string u-NNN, amount: integer 1..2000} and rejects extra keys without exposing validation detail. Self-transfer returns 403 SELF_TRANSFER_FORBIDDEN, an unknown recipient 404 RECIPIENT_NOT_FOUND, and insufficient funds 409 INSUFFICIENT_FUNDS.
For {"toUserId":"u-204","amount":1250}, both writes run synchronously: 5000 - 1250 = 3750 and 300 + 1250 = 1550. The 201 response contains tx-0001, both user IDs, amount, and balances. The injection-shaped body's object ID, string amount, and extra role produce 400 INVALID_BODY before lookup or mutation. A real database needs an atomic conditional update or transaction across concurrent requests and processes.
4. Bound HTTP work and keep failures safe
The server sets a 10,000 ms header timeout, a 15,000 ms request timeout, a 5,000 ms keep-alive timeout, and a 30,000 ms socket timeout. Load-test these values for the real workload instead of treating them as universal.
The final middleware maps oversized bodies to 413 PAYLOAD_TOO_LARGE, broken JSON to 400 INVALID_JSON, and other pre-header failures to 500 INTERNAL_ERROR. It logs only {requestId, errorName} and returns the ID, excluding secrets, bodies, internal details, and stacks. If headers were sent, it calls next(err).
Transport remains an outer boundary. Real credentials require HTTPS at the deployment edge or server. POST, CORS, and Helmet do not encrypt traffic. The Application Layer Protocols: DNS and HTTP Guide explains requests, headers, and responses.
5. Defend the dependency and runtime path
Before adding a package, review its name, maintainer activity, and contents. Commit package-lock.json, use npm ci to reject lockfile disagreement, and run npm audit. Test remediations; a clean audit does not prove a dependency benign.
Keep tokens in secrets or the environment, rotate them after exposure, and redact logs. Grant only needed file, network, and operating-system permissions. Dependencies inherit process authority, so excess authority expands a compromise.
The Node.js Permission Model can restrict file and network access, child processes, workers, native add-ons, WASI, FFI, and the inspector. It is defence in depth for trusted code, not a sandbox.
6. Common Node.js security mistakes and safer replacements
Mistake | What goes wrong | Safer replacement |
|---|---|---|
| Attacker keys enable mass assignment or prototype-pollution paths | Strict schema and a new allowlisted object |
| Shell metacharacters become commands | Avoid the shell; allowlist values and use |
Hard-code or log the Bearer token | Exposes a reusable secret | Inject the secret and redact it |
Return | Reveals internal detail | Safe public code plus request ID |
Treat CORS | Browser origin policy does not authorise operations | Authorise server-side and configure required origins |
Set | Spoofed client-derived IP data can weaken IP limits | Trust the known proxy path and test resolved client IP |
Database checks add another layer. Mongoose Schemas and Models shows model validation, which cannot replace request validation or per-operation authorisation.
7. Prove the contract with adversarial requests and exercises
On a fresh server, send these sequentially within one 60,000 ms window:
Request | Input | Expected result | Balances afterward |
|---|---|---|---|
1 | No |
|
|
2 | Valid token, injection-shaped body |
|
|
3 | Valid token, transfer |
|
|
4 | Valid token, self-transfer |
|
|
5 | Valid token, self-transfer |
|
|
6 | Any |
|
|
Both skip flags are false, so rejected requests count. Only request 3 mutates state.
Restart the server for a fresh limiter window. Then assert broken JSON gives 400 INVALID_JSON, more than 10kb gives 413 PAYLOAD_TOO_LARGE, and success includes X-Content-Type-Options: nosniff but not X-Powered-By. Replace demo authentication with a maintained adapter that produces req.actor.id while keeping other tests. Use these as code-review checks on any route that moves money.

8. Node.js security best practices: the short version and next step
Use HTTPS. Authenticate, then authorise. Accept a strict body shape. Cap bytes, time, and attempts. Compare secrets carefully. Return controlled errors. Lock and audit dependencies. The accepted transfer changes 5000/300 to 3750/1550; every rejection preserves state.
Continue with the Node.js, Express.js & MongoDB Course, or browse the Skill Development Courses catalogue. Run the trace, then review one route boundary by boundary. Web Development provides the wider map. No checklist or package secures an application by itself.
Keep learning
Node.js Routing and Controllers Tutorial: Build a Runnable Express API
Build a small Express users API from scratch, separate routes from controllers, and test successful and failed requests against predictable responses.
Express Basics in Node.js: Build Your First JSON API
Build a small Express books API and learn how requests move through JSON parsing, middleware, routes, validation, and predictable error responses.
Sessions and Cookies in Node.js: A Runnable Express Login Tutorial
Build the complete localhost flow, then trace what the browser sends, what Express stores, and why logout makes the dashboard anonymous again.
JWT Authentication in Node.js and Express: Access Tokens, Refresh Tokens, and the Security Pitfalls That Leak Accounts
Trace a complete Express login, protected request, expiry, and refresh cycle. Then fix the token mistakes that make an apparently working system unsafe.





