Node.js Security Checklist for 2026: What Actually Matters

Lock your dependencies first. Commit package-lock.json, run npm ci in CI, and scan for behavior, not just CVEs. Most Node breaches trace back to a compromised package, not clever app code. Then handle secrets, input validation, and auth. Boring, repeatable checks catch almost everything.
Part of the complete web development guide.
On this page
- Start with your dependencies, because that is where you will lose
- Stop concatenating SQL, and stop trusting object keys
- Secrets, sessions, and the config mistakes I see most
- Headers, CORS, and the stuff that is five minutes of work
- Errors, logs, and what you leak when things break
- A short checklist you can actually run
- FAQ
- Is npm audit enough to keep my dependencies safe?
- Do I need all of this for a small business site?
- What is the single highest-impact fix if I only have an afternoon?
Most Node.js security advice you find online is either a decade old or written by someone who has never had to rotate a leaked API key at 11pm. The fundamentals have not changed much, but the attack surface has. Here is what I actually look at when I audit a Node app in 2026, in the order that tends to matter.
I have been building and fixing Node services for a long time, much of it for small businesses and agencies around Long Island. The problems are almost never exotic. They are boring, repeatable mistakes that a checklist catches.
Start with your dependencies, because that is where you will lose
Roughly every serious Node breach story I have read in the last few years traces back to a package, not to clever application code. The npm ecosystem is enormous, transitive dependencies are invisible, and a single compromised maintainer account can poison thousands of projects. This is not paranoia. It has happened repeatedly.
What actually helps:
- Commit your lockfile (
package-lock.json) and usenpm ciin CI, notnpm install.npm installcan quietly resolve to a different version than what you tested. - Run
npm audit, but do not treat a clean report as proof of safety. It only knows about published advisories. - Add a supply chain scanner that watches for behavior, not just CVE IDs. Socket and similar tools flag packages that suddenly add install scripts or phone home.
- Turn off install scripts globally where you can. Most packages do not need them.
# Only run lifecycle scripts for packages you explicitly trust
npm config set ignore-scripts true
# Then allow the handful that genuinely need to build
npm rebuild bcrypt sharp
The 2025 debug and chalk compromise is the clearest recent lesson: a maintainer’s npm token got phished, malicious versions shipped, and millions of installs pulled them down within hours. If your pipeline auto-deploys on every dependency bump with no human review, you are one phished token away from shipping someone else’s payload.
Stop concatenating SQL, and stop trusting object keys
Injection in Node usually shows up in two places: raw SQL string building and NoSQL query objects. Both are avoidable.
// Bad: string interpolation into a query
const rows = await db.query(
`SELECT * FROM users WHERE email = '${email}'`
);
// Good: parameterized query
const rows = await db.query(
'SELECT * FROM users WHERE email = $1',
[email]
);
The MongoDB version is sneakier. If you pass a request body straight into a query, an attacker can send an object instead of a string and change the meaning of the query:
// Attacker sends: { "email": { "$ne": null }, "password": "x" }
app.post('/login', async (req, res) => {
const user = await User.findOne(req.body); // auth bypass
});
// Fix: pick the fields you expect, and validate types
import { z } from 'zod';
const LoginSchema = z.object({
email: z.string().email(),
password: z.string().min(1).max(200),
});
app.post('/login', async (req, res) => {
const { email, password } = LoginSchema.parse(req.body);
const user = await User.findOne({ email });
// ...
});
Validate at the boundary, every time. Zod, Valibot, or plain JSON Schema all work. The tool matters less than the habit of never letting raw input reach your data layer.
Secrets, sessions, and the config mistakes I see most
This is the category where I find the most damage in small codebases, and it has nothing to do with clever exploits. It is just configuration.
- Secrets in the repo. If a key was ever committed, consider it burned. Rotate it. Deleting the commit does not help; it lives in forks and caches. Use
gitleaksor GitHub secret scanning in CI to catch this before it merges. - Secrets in the frontend bundle. Anything prefixed
VITE_orNEXT_PUBLIC_is public. I have seen live Stripe secret keys shipped inside aNEXT_PUBLIC_variable. That is a full account takeover waiting to happen. - Cookies without flags. Session cookies need
HttpOnly,Secure, andSameSite=Laxat minimum. WithoutHttpOnly, any XSS turns into session theft. - No rate limiting. Login, password reset, and any endpoint that sends email or SMS need a limiter. Otherwise you are a free abuse platform.
import rateLimit from 'express-rate-limit';
const loginLimiter = rateLimit({
windowMs: 15 * 60 * 1000,
max: 10,
standardHeaders: true,
legacyHeaders: false,
});
app.post('/login', loginLimiter, loginHandler);
If you are running a Next.js app, note that middleware-based rate limiting only works per instance. On serverless, use a shared store (Upstash Redis, for example) or the limiter resets every cold start.
Headers, CORS, and the stuff that is five minutes of work
These are cheap wins that close entire classes of bugs. Set them once and forget them.
import helmet from 'helmet';
app.use(helmet({
contentSecurityPolicy: {
directives: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'"],
objectSrc: ["'none'"],
frameAncestors: ["'none'"],
},
},
crossOriginResourcePolicy: { policy: 'same-origin' },
}));
Then fix CORS properly. I still see origin: true with credentials: true, which reflects any origin and hands your users’ cookies to whoever asks. Be explicit:
app.use(cors({
origin: ['https://yourdomain.com'],
credentials: true,
}));
A frame-ancestors policy also kills clickjacking, which matters more than people think for anything with a payment or admin flow. If you are building that kind of app for a business, it is the sort of thing that should be in the foundation, not bolted on later. That is a big part of how I approach custom web development for clients: security defaults baked in from the first commit, because retrofitting them costs five times as much.
Errors, logs, and what you leak when things break
Stack traces in production responses are an information gift. So are verbose framework error pages. Turn both off.
app.use((err, req, res, next) => {
console.error(err); // full detail to your logs
res.status(500).json({ error: 'Internal server error' }); // nothing to the client
});
Two more things people forget. First, log sanitization: if you log full request bodies, you are now storing passwords and tokens in plaintext in your log aggregator. Redact them. Second, keep Node itself patched. Node 18 is end of life. In 2026 you should be on Node 22 LTS or 24 LTS. Older runtimes stop getting security patches, and that is a free vulnerability you opted into.
A short checklist you can actually run
npm ciin CI, lockfile committed, install scripts disabled by default.- Dependency scanning plus a behavior-based supply chain tool.
- Every input validated at the boundary with a schema.
- Parameterized queries and typed query objects, always.
- Secrets in a manager, never in the repo or the client bundle. Rotate anything that leaked.
- Cookies with
HttpOnly,Secure,SameSite. - Rate limiting on auth and anything that costs money or sends messages.
- Helmet, a real CSP, and explicit CORS origins.
- Generic error responses, redacted logs, current Node LTS.
None of this is glamorous. But the apps that get breached are almost never breached by something clever. They are breached because someone skipped item four on that list.
FAQ
Is npm audit enough to keep my dependencies safe?
No. It only catches known advisories tied to published CVEs, and it misses malicious packages that have no advisory yet. Pair it with a supply chain scanner that looks at package behavior, and pin versions with a committed lockfile.
Do I need all of this for a small business site?
Scale down, not out. A brochure site with no login mostly needs patched dependencies, security headers, and a current Node version. The moment you add logins, payments, or user data, the full checklist applies.
What is the single highest-impact fix if I only have an afternoon?
Find every hardcoded secret in your codebase and your client bundle, move them to environment variables or a secrets manager, and rotate anything that was ever committed. That one afternoon closes the failure mode that has caused the most real-world damage I have seen.


