Bird
Raised Fist0
Node.jsframework~20 mins

Common Node.js security vulnerabilities in Node.js - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Node.js Security Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
🧠 Conceptual
intermediate
2:00remaining
What is the main risk of using unsanitized user input in Node.js?

Consider a Node.js app that directly uses user input in database queries without cleaning it. What is the main security risk?

ACross-Site Scripting (XSS) attack
BMan-in-the-Middle (MitM) attack
CSQL Injection attack
DDenial of Service (DoS) attack
Attempts:
2 left
💡 Hint

Think about attacks that manipulate database commands.

❓ component_behavior
intermediate
2:00remaining
What happens if you use eval() on user input in Node.js?

Given a Node.js server that runs eval(userInput), what is the likely security consequence?

AIt can lead to remote code execution vulnerabilities
BIt safely executes user code without risks
CIt prevents injection attacks automatically
DIt only runs code in a sandboxed environment
Attempts:
2 left
💡 Hint

Consider what eval() does with arbitrary code strings.

📝 Syntax
advanced
2:00remaining
Which code snippet properly prevents prototype pollution in Node.js?

Prototype pollution happens when attackers modify object prototypes. Which snippet blocks this?

Aobj['__proto__'] = value; // directly assign
Bdelete obj['constructor']; obj[key] = value;
CObject.assign(obj, userInput); // blindly assign
Dif (key === '__proto__') throw new Error('Pollution attempt'); obj[key] = value;
Attempts:
2 left
💡 Hint

Check which option blocks dangerous keys before assignment.

🔧 Debug
advanced
2:00remaining
Why does this Node.js code cause a denial of service (DoS)?

Examine the code below:

const http = require('http');
http.createServer((req, res) => {
  while(true) {}
  res.end('Hello');
}).listen(3000);

What is the problem?

Node.js
const http = require('http');
http.createServer((req, res) => {
  while(true) {}
  res.end('Hello');
}).listen(3000);
AThe server leaks memory causing slowdowns
BThe infinite loop blocks the event loop causing DoS
CThe server crashes due to missing response headers
DThe server responds with wrong content type
Attempts:
2 left
💡 Hint

Think about what an infinite loop does in Node.js single-threaded model.

❓ state_output
expert
2:00remaining
What is the output of this Express.js middleware chain with a missing next() call?

Consider this Express.js code:

const express = require('express');
const app = express();

app.use((req, res, next) => {
  console.log('First middleware');
  // missing next()
});

app.use((req, res, next) => {
  console.log('Second middleware');
  res.send('Done');
});

app.listen(3000);

What happens when a request is made?

Node.js
const express = require('express');
const app = express();

app.use((req, res, next) => {
  console.log('First middleware');
  // missing next()
});

app.use((req, res, next) => {
  console.log('Second middleware');
  res.send('Done');
});

app.listen(3000);
AOnly 'First middleware' logs; request hangs without response
B'First middleware' and 'Second middleware' both log; response sent
COnly 'Second middleware' logs; response sent immediately
DServer crashes with an error about missing next()
Attempts:
2 left
💡 Hint

Think about what happens if next() is not called in middleware.

Practice

(1/5)
1. Which of the following is a common security vulnerability in Node.js applications?
easy
A. Memory Leak
B. SQL Injection
C. Slow Network
D. Syntax Error

Solution

  1. Step 1: Understand common vulnerabilities

    SQL Injection is a well-known security risk where attackers inject malicious SQL code.
  2. Step 2: Identify relevant options

    Memory leaks and slow networks are performance issues, syntax errors are coding mistakes, not security vulnerabilities.
  3. Final Answer:

    SQL Injection -> Option B
  4. Quick Check:

    Common Node.js security risk = SQL Injection [OK]
Hint: Security risks often involve data injection or unauthorized access [OK]
Common Mistakes:
  • Confusing performance issues with security vulnerabilities
  • Thinking syntax errors are security problems
  • Ignoring injection attacks
2. Which syntax correctly prevents Cross-Site Scripting (XSS) in a Node.js Express app when rendering user input in a template?
easy
A. res.send(`
${escape(userInput)}
`);
B. res.render('page', { data: userInput });
C. res.send(`
${userInput}
`);
D. res.send(userInput);

Solution

  1. Step 1: Identify safe rendering method

    Escaping user input before inserting into HTML prevents XSS attacks.
  2. Step 2: Compare options

    Only res.send(`
    ${escape(userInput)}`); uses an escape function to sanitize input before sending.
  3. Final Answer:

    res.send(`
    ${escape(userInput)}
    `);
    -> Option A
  4. Quick Check:

    Escape user input to prevent XSS = res.send(`
    ${escape(userInput)}
    `); [OK]
Hint: Always escape user input before rendering in HTML [OK]
Common Mistakes:
  • Sending raw user input directly in HTML
  • Assuming template rendering auto-escapes input
  • Not using escape functions
3. What will be the output of this Node.js code snippet vulnerable to prototype pollution?
const obj = {};
const payload = JSON.parse('{"__proto__": {"polluted": "yes"}}');
Object.assign(obj, payload);
console.log({}.polluted);
medium
A. Throws an error
B. undefined
C. null
D. "yes"

Solution

  1. Step 1: Understand prototype pollution

    Assigning __proto__ property modifies the prototype of all objects.
  2. Step 2: Analyze code behavior

    Object.assign merges payload into obj, changing Object prototype to include polluted property.
  3. Step 3: Check console.log output

    Accessing {}.polluted reads from prototype, outputs "yes".
  4. Final Answer:

    "yes" -> Option D
  5. Quick Check:

    Prototype pollution sets property globally = "yes" [OK]
Hint: Prototype pollution changes all objects' properties unexpectedly [OK]
Common Mistakes:
  • Expecting undefined instead of polluted value
  • Not recognizing __proto__ effect
  • Assuming error thrown on prototype pollution
4. Identify the security flaw in this Express middleware code:
app.use((req, res, next) => {
  const token = req.headers['authorization'];
  if (token) {
    req.user = jwt.verify(token, 'secret');
  }
  next();
});
medium
A. Not checking token expiration
B. Using synchronous jwt.verify instead of async
C. Missing error handling for invalid token
D. Not sanitizing user input

Solution

  1. Step 1: Review token verification

    jwt.verify can throw if token is invalid, but no try-catch is used.
  2. Step 2: Identify missing error handling

    Without try-catch, invalid tokens cause app crash or unhandled exceptions.
  3. Final Answer:

    Missing error handling for invalid token -> Option C
  4. Quick Check:

    Always catch errors from jwt.verify [OK]
Hint: Wrap jwt.verify in try-catch to handle invalid tokens [OK]
Common Mistakes:
  • Ignoring exceptions from jwt.verify
  • Assuming synchronous call is insecure
  • Confusing input sanitization with token validation
5. You want to secure a Node.js app against outdated package vulnerabilities. Which approach is best to keep dependencies safe?
hard
A. Run 'npm audit' regularly and update vulnerable packages
B. Ignore warnings and only update major versions yearly
C. Manually edit package-lock.json to remove vulnerabilities
D. Use only packages without any dependencies

Solution

  1. Step 1: Understand package vulnerability management

    npm audit scans for known vulnerabilities in dependencies.
  2. Step 2: Choose best practice

    Regularly running npm audit and updating packages fixes security issues promptly.
  3. Step 3: Evaluate other options

    Ignoring warnings risks attacks, manual edits are error-prone, and avoiding dependencies is impractical.
  4. Final Answer:

    Run 'npm audit' regularly and update vulnerable packages -> Option A
  5. Quick Check:

    Use npm audit and update often = Run 'npm audit' regularly and update vulnerable packages [OK]
Hint: Use npm audit and update packages regularly [OK]
Common Mistakes:
  • Ignoring audit warnings
  • Editing lock files manually
  • Avoiding dependencies completely
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard