Node.js is widely used for building web applications, APIs, and microservices, but like any other platform, it comes with security risks. Cyberattacks targeting Node.js applications can lead to data breaches, server takeovers, and financial loss
 
Understanding common vulnerabilities in Node.js and how to mitigate them is critical for developers.

1. SQL Injection (SQLi) 

What is it? 
SQL Injection occurs when user input is directly embedded in database queries without proper sanitization. Attackers can manipulate queries to gain unauthorized access, modify records, or even delete databases. 

Example of SQL Injection Vulnerability


 

app.get('/user/:id', async (req, res) => {
    const userId = req.params.id;
    const user = await db.query(`SELECT * FROM users WHERE id = '${userId}'`);
    res.json(user);
});

If an attacker inputs 1' OR '1'='1, the query becomes:

 

SELECT * FROM users WHERE id = '1' OR '1'='1'

This fetches all users, exposing sensitive data. 

How to Fix It? 

Use Parameterized Queries (Prepared Statements)

 

app.get('/user/:id', async (req, res) => {
    const userId = req.params.id;
    const user = await db.query('SELECT * FROM users WHERE id = ?', [userId]);
    res.json(user);
});

Use ORM Libraries (like Sequelize, TypeORM, or Mongoose for MongoDB) 

2. Cross-Site Scripting (XSS) 

What is it? 
XSS occurs when attackers inject malicious scripts into web applications, which then execute in a user’s browser, stealing cookies, hijacking sessions, or defacing websites. 

Example of XSS Vulnerability


 

app.get('/search', (req, res) => {
    const query = req.query.q;
    res.send(`Results for ${query}`);
});

If a user inputs , it executes in the browser. 

How to Fix It? 

Escape User Input using libraries like DOMPurify or xss-filters
Use Content Security Policy (CSP) to block unauthorized scripts. 
Use templating engines like Handlebars, Pug, or EJS that automatically escape HTML. 

3. NoSQL Injection 

What is it? 
Similar to SQL Injection, but for NoSQL databases like MongoDB. Attackers inject malicious JavaScript objects to manipulate database queries. 

Example of NoSQL Injection Vulnerability


 

app.post('/login', async (req, res) => {
    const user = await db.collection('users').findOne({ username: req.body.username, password: req.body.password });
    if (user) res.send('Logged in');
});

If an attacker sends:

 

{ "username": { "$ne": null }, "password": { "$ne": null } }

It bypasses authentication. 

How to Fix It? 

Use input validation (Joi, express-validator
Use Mongoose’s strict query mode 
Always hash passwords using bcrypt 
 

4. Insecure Deserialization 

What is it? 
If an application deserializes untrusted user data, attackers can execute remote code, escalate privileges, or crash servers

Example of Insecure Deserialization Vulnerability


 

app.post('/deserialize', (req, res) => {
    const obj = JSON.parse(req.body.data);
    execute(obj.action);
});

If an attacker sends:

 

{ "action": "rm -rf /" }

It could execute destructive commands on the server. 

How to Fix It? 

Use Secure Parsers like json5 
Validate Input Before Deserialization 
Use Object.freeze() to make objects immutable 

5. Directory Traversal Attack 

What is it? 
An attacker can read arbitrary files on the server by exploiting poorly handled file paths. 

Example of Directory Traversal Vulnerability


 

app.get('/file', (req, res) => {
    res.sendFile(__dirname + '/uploads/' + req.query.filename);
});

If an attacker requests:

 

/file?filename=../../etc/passwd

They can read sensitive system files

How to Fix It? 

Use path.join() to normalize file paths 
Whitelist allowed filenames 
Run the server with restricted permissions 

6. Cross-Site Request Forgery (CSRF) 

What is it? 
An attacker tricks users into performing unauthorized actions on a site where they are logged in. 

Example of CSRF Attack 

A victim clicks on:

 

src="http://example.com/delete-account" />

If logged in, their account is deleted

How to Fix It? 

Use CSRF tokens (csurf package) 
Require re-authentication for critical actions 
Use SameSite cookies 

7. Denial of Service (DoS) via Unhandled Errors 

What is it? 
Attackers can crash your server by sending unexpected input that isn’t handled properly. 

Example of Unhandled Error Vulnerability


 

app.get('/crash', (req, res) => {
    JSON.parse(req.query.input);
    res.send('OK');
});

If an attacker sends {input: "{"}, it crashes the app. 

How to Fix It? 

Wrap API routes in try-catch blocks 
Use process managers like pm2 
Set memory and request rate limits (express-rate-limit

8. Using Outdated Dependencies 

What is it? 
Many Node.js applications use third-party packages. If these are outdated, attackers can exploit known vulnerabilities. 

How to Fix It? 

Use npm audit to check for vulnerabilities 
Upgrade dependencies regularly 
Use security scanners like Snyk 

Final Thoughts 

Security in Node.js is not optional—it’s a must. Attackers are always looking for loopholes, and one small mistake can expose your entire application

You may also like:

  1. 10 Common Mistakes with Synchronous Code in Node.js
  2. Why 85% of Developers Use Express.js Wrongly
  3. Implementing Zero-Downtime Deployments in Node.js
  4. 10 Common Memory Management Mistakes in Node.js
  5. 5 Key Differences Between ^ and ~ in package.json
  6. Scaling Node.js for Robust Multi-Tenant Architectures
  7. 6 Common Mistakes in Domain-Driven Design (DDD) with Express.js
  8. 10 Performance Enhancements in Node.js Using V8
  9. Can Node.js Handle Millions of Users?
  10. Express.js Secrets That Senior Developers Don’t Share

Read more blogs from Here

Share your experiences in the comments, and let’s discuss how to tackle them!

Follow me on Linkedin