Node.js Security in 2026: A Practical Checklist for Real Apps

Secure a Node.js app in 2026 by auditing dependencies first, committing lockfiles, and running npm ci in CI. Keep Node on the current LTS, validate and sanitize all input, set strict security headers, and never trust client data. Most real breaches come from outdated transitive packages, not clever code.
Part of the complete web development guide.
On this page
- Start with your dependencies, because that is where you will actually get hit
- Pin your CI to a known-good install
- Validate input at the boundary, not in fifty places
- Secrets, sessions, and the stuff people get wrong
- Cookies and CSRF
- Password hashing
- Rate limiting and the boring infrastructure wins
- What I actually do on client work
- FAQ
- Do I need a WAF if I already validate input?
- Is npm audit enough to catch supply chain problems?
- How often should I update Node itself?
Most Node.js security advice on the internet is either a list of scary acronyms or a sales page for some scanning product. Neither helps you ship safer code on Monday morning. What follows is the stuff I actually check on real apps, in the order that matters, with code you can paste and adapt.
Node 22 is the LTS most teams are running now, and Node 24 is the current line. Both ship with a lot of security-relevant behavior that older tutorials get wrong, so some of what you read from 2019 is not just outdated, it is actively misleading.
Start with your dependencies, because that is where you will actually get hit
Almost every real-world Node breach I have seen traces back to a transitive dependency, not clever application code. You pulled in a package for slugifying strings and it dragged in eleven more packages, and one of those has not been touched since 2021.
Run the audit and actually read the output:
npm audit --omit=dev
# or if you use pnpm
pnpm audit --prod
Two things matter here. First, --omit=dev keeps the noise down; a vulnerability in your test runner is not a production incident. Second, do not blindly run npm audit fix --force. That flag will happily install a major version bump of a package and break your app at 2am. Read the advisory, check whether the vulnerable code path is even reachable from your usage, then upgrade deliberately.
Lockfiles are non-negotiable. Commit package-lock.json or pnpm-lock.yaml, and in CI use npm ci instead of npm install. npm ci installs exactly what the lockfile says and fails if the lockfile and package.json disagree, which is the behavior you want on a build server.
Pin your CI to a known-good install
# .github/workflows/ci.yml (excerpt)
- run: npm ci --ignore-scripts
- run: npm audit --omit=dev --audit-level=high
The --ignore-scripts flag is worth knowing about. Postinstall scripts are how several notable supply chain attacks executed their payload. If a dependency genuinely needs a postinstall step (native modules usually do), exempt it explicitly rather than turning scripts back on globally.
Validate input at the boundary, not in fifty places
The single biggest source of bugs that turn into vulnerabilities is trusting data that came from outside your process: request bodies, query strings, headers, webhook payloads, files. Validate once, at the edge, and then work with typed, trusted objects internally.
Zod is still the pragmatic default in 2026, and it plays well with TypeScript because the parsed type is inferred from the schema.
import { z } from "zod";
const SignupSchema = z.object({
email: z.string().email().max(254),
password: z.string().min(12).max(200),
age: z.coerce.number().int().min(13).max(120),
});
app.post("/signup", async (req, res) => {
const parsed = SignupSchema.safeParse(req.body);
if (!parsed.success) {
return res.status(400).json({ error: "Invalid input" });
}
const { email, password, age } = parsed.data;
// proceed with known-good values
});
Note the .max() calls. Unbounded strings are a denial-of-service vector. A 50MB email field will happily consume memory while your regex chokes on it. Cap everything.
And no, you do not need a separate sanitizer for SQL if you are using parameterized queries, which you should be:
// pg (node-postgres)
await pool.query("SELECT id FROM users WHERE email = $1", [email]);
// better-sqlite3
db.prepare("SELECT id FROM users WHERE email = ?").get(email);
String concatenation into SQL is a bug no matter how confident you are that the input is clean. There is no exception to this.
Secrets, sessions, and the stuff people get wrong
Secrets do not belong in your repo, and they do not belong in a .env file that ships in your Docker image. Use your platform’s secret store (AWS Secrets Manager, GCP Secret Manager, Fly secrets, Railway variables, whatever you are on) and read them at boot.
// Fail loudly if a required secret is missing at startup.
const required = ["DATABASE_URL", "SESSION_SECRET", "STRIPE_KEY"];
for (const key of required) {
if (!process.env[key]) {
throw new Error(`Missing required env var: ${key}`);
}
}
Failing at boot beats failing at 3am on the one code path that needed the key.
Cookies and CSRF
If you use cookie-based sessions, set the flags correctly. This is not optional:
app.use(session({
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: false,
cookie: {
httpOnly: true,
secure: true, // requires HTTPS
sameSite: "lax", // "strict" if you don't need cross-site nav
maxAge: 1000 * 60 * 60 * 24 * 7,
},
}));
sameSite: "lax" blocks most CSRF vectors for free. If your app does state-changing POSTs from a different origin, add a token check on top. Do not rely on a custom header alone, because that only helps if you are also enforcing CORS correctly, and CORS is not a security boundary in the way people assume.
Password hashing
Use argon2id. If your environment makes argon2 painful, bcrypt at cost 12 or higher is still acceptable. Never SHA-256, never MD5, and never a homegrown scheme.
import argon2 from "argon2";
const hash = await argon2.hash(password, { type: argon2.argon2id });
const ok = await argon2.verify(hash, password);
Rate limiting and the boring infrastructure wins
Rate limiting is the difference between a credential stuffing attempt being annoying and being a full account takeover event. Put it in front of anything that authenticates.
import rateLimit from "express-rate-limit";
const loginLimiter = rateLimit({
windowMs: 15 * 60 * 1000,
max: 10,
standardHeaders: true,
legacyHeaders: false,
});
app.post("/login", loginLimiter, loginHandler);
In-memory limiting is fine on a single instance. Once you scale horizontally, move the store to Redis, otherwise each instance has its own counter and the effective limit multiplies by your instance count. That is a mistake I have made.
Beyond that, keep your runtime patched. Node’s security releases land on a predictable schedule and the project publishes them clearly. If you are on a version that stopped receiving security updates, that is the whole ballgame. Subscribe to the Node release notes or follow the security working group; it takes five minutes a month and it is the highest-return security habit you can build.
What I actually do on client work
When I take over an existing codebase for custom web development, the audit is roughly this order: lockfile present and CI using npm ci, dependency audit clean at the high and critical level, input validation at every boundary, secrets out of the repo, cookie flags correct, password hashing modern, rate limiting on auth endpoints, and the Node version still supported. That list catches the overwhelming majority of real problems. The exotic stuff matters, but it matters after the basics are handled.
If you are based on Long Island and running a Node app that has not had this kind of pass, it is usually a half day of work, not a project. Worth doing before something forces the issue.
FAQ
Do I need a WAF if I already validate input?
They solve different problems. A WAF blocks known-bad traffic patterns at the edge before they reach your app, which helps with volumetric attacks and bot traffic. Input validation protects your application logic from malformed data. A WAF is not a substitute for validating what your code receives.
Is npm audit enough to catch supply chain problems?
No. It catches known CVEs in published versions, which is valuable but reactive. Add lockfile discipline, npm ci in CI, and consider a tool like Socket or Snyk if you have a large dependency tree. The goal is to know what changed before it ships, not after.
How often should I update Node itself?
Track the LTS line and apply security patches within days, not months. Major version upgrades are worth doing annually when the new LTS is stable. Running an unsupported Node version is the one item on this list I would call genuinely urgent.


