Skip to content

Interview PrepAttacks · Core

Common Attacks ​

1. What are common security vulnerabilities in Node.js and Express applications? ​

The short answer

The most common are broken access control, such as one user reading another user's orders by changing an ID; injection into SQL, NoSQL queries or shell commands; cross-site scripting; weak authentication and session handling; secrets in code or logs; vulnerable or malicious npm dependencies; missing security headers and permissive CORS; leaking stack traces; no rate limiting; server-side request forgery; and Node-specific issues such as prototype pollution and regular expressions that can be made to run for seconds.

VulnerabilityA typical Express mistakeDefence
Broken access controlGET /orders/:id returns any order to any signed-in userCheck ownership on every record (the authorisation middleware question)
InjectionString-built SQL, exec with user inputParameterised queries, execFile (question 6)
Cross-site scriptingRendering user HTML without escapingEscape output, sanitise rich text, CSP (question 3)
Cross-site request forgeryCookie sessions with no protectionSameSite cookies, CSRF tokens (question 4)
Server-side request forgeryFetching any URL a user suppliesAllow-lists, block internal addresses (question 5)
Mass assignmentdb.update(req.body) lets users set roleAccept only known fields (the validation question)
Secrets exposureAPI keys in Git, tokens in logsA secret manager, log redaction (question 30)
Vulnerable dependenciesOld packages, malicious updatesLockfiles, audits, few dependencies
Information leaksStack traces in responsesCentral error handler (the leaks question)
No abuse protectionUnlimited login attemptsRate limits (question 28)
Prototype pollutionDeep-merging user JSON into objectsSafe merging, validation (question 9)
ReDoSA slow regex on user inputSafe patterns, input limits (the high CPU question)

The interviewer's favourite is broken access control, because it is the most common real-world API flaw and no framework fixes it for you: only your code knows who may see which record.

2. What is the OWASP Top 10, and how does it apply to backend APIs? ​

The short answer

The OWASP Top 10 is a widely used list, published by the Open Worldwide Application Security Project, of the most critical security risk categories in web applications, based on data from real assessments. The 2025 edition puts broken access control first, followed by security misconfiguration, software supply chain failures, cryptographic failures and injection. For APIs, OWASP also publishes a separate API Security Top 10, whose first item, broken object-level authorisation, is the same "change the ID, see someone else's data" problem.

#OWASP Top 10, 2025In a Node.js API
A01Broken Access Control, now including SSRFMissing ownership checks; fetching attacker-chosen URLs
A02Security MisconfigurationDebug mode in production, permissive CORS, default credentials
A03Software Supply Chain FailuresMalicious or compromised npm packages, unpinned dependencies
A04Cryptographic FailuresWeak password hashing, no TLS, secrets in plain text
A05InjectionSQL, NoSQL, shell and template injection
A06Insecure DesignNo rate limits on a coupon endpoint; business logic flaws
A07Authentication FailuresWeak sessions, tokens not verified, no MFA for admins
A08Software or Data Integrity FailuresUnsigned webhooks, unverified updates, unsafe deserialisation
A09Security Logging and Alerting FailuresNo audit logs; nobody alerted to an attack
A10Mishandling of Exceptional ConditionsErrors that leak data or fail open instead of closed

The OWASP API Security Top 10, from 2023, adds API-specific items worth knowing by name: broken object-level authorisation, broken authentication, broken object property-level authorisation, which covers mass assignment and over-exposing fields, unrestricted resource consumption, broken function-level authorisation, server-side request forgery and improper inventory management, meaning forgotten old API versions.

How to use it in an interview: treat it as a checklist for a design review, not a list to memorise. For each endpoint, ask who can call it, what it lets them read and change, what it costs to call many times, and what happens when it fails.

3. What is cross-site scripting (XSS), and how can it be prevented? ​

The short answer

Cross-site scripting is when an attacker gets their JavaScript to run in other users' browsers on your site, for example by saving a product review that contains a script, which then runs for everyone who views the page. The script runs with the victim's session, so it can read the page, act as the user or steal tokens stored in JavaScript-readable storage. Prevent it by escaping output for its context, never inserting untrusted HTML, sanitising rich text with a library, using a strict Content Security Policy, and keeping session cookies HttpOnly.

attackerposts a reviewserverstores it as isproduct pagereview as raw HTMLvictim's browserruns the script① <script>…②③ page served④ acts as the victim
The attacker's code, the victim's session. ① A script is submitted as content. ② It is stored. ③ It is served to other users as part of a page. ④ Their browsers run it as if your site wrote it.

The three kinds:

KindHow the script arrivesExample
StoredSaved on the server, shown to othersA review, a profile name, a support ticket
ReflectedBounced back from the request/search?q=<script>… echoed into the page
DOM-basedFront-end code writes untrusted data into the pageelement.innerHTML = location.hash

Defences, in order of importance:

  1. Escape output for its context. Template engines and React escape text by default. Values in HTML, attributes, URLs and JavaScript each need their own escaping (the React XSS question).
  2. Never insert raw HTML from users. If rich text is required, sanitise it with a well-maintained library such as DOMPurify, allowing only safe tags.
  3. A strict Content Security Policy that blocks inline scripts, so injected <script> tags do not run even if escaping fails somewhere (question 22).
  4. HttpOnly cookies, so a script cannot read the session cookie.
  5. Validate URLs before putting them in href or src: allow https: only, never javascript:.

Why it matters for APIs too: even a JSON API feeds data to web pages. Stored XSS often starts with an API that accepts and later returns HTML-looking text that a front end then renders unsafely.

4. What is cross-site request forgery (CSRF), and how can it be prevented? ​

The short answer

Cross-site request forgery tricks a signed-in user's browser into sending a request to your site from another site, for example a hidden form on an attacker's page that posts to /account/email. Because the browser attaches the user's cookies automatically, the request arrives authenticated, and your server performs the action. Defend with SameSite=Lax or Strict session cookies, a CSRF token that other sites cannot read, checking the Origin header on state-changing requests, and never changing state on GET. APIs that use bearer tokens in headers, not cookies, are not exposed in the same way.

victim's browserhas shop cookieattacker's pagehidden auto-submit formshop.examplesees a valid cookie② visits③ POST /account/email④ browser adds the cookie automatically① signed in earlieremail changed
Your cookie, someone else's request. ① The user is signed in. ② They visit another site. ③ That site sends a request to yours. ④ The browser adds your cookie on its own, so the request looks legitimate.

Defences:

DefenceHow it helps
SameSite=Lax or Strict on session cookiesThe browser does not send the cookie on cross-site POST requests; see SameSite values
CSRF tokenA secret value in the form or a header, which the attacker's page cannot read
Check Origin or Sec-Fetch-SiteReject state-changing requests from other origins
No state changes on GETLinks and images cannot trigger actions
Re-authentication for sensitive actionsChanging the email or password requires the current password

A token check with the double-submit pattern:

ts
import { randomBytes, timingSafeEqual } from 'node:crypto'

app.use((req, res, next) => {
  if (!req.cookies.csrf) res.cookie('csrf', randomBytes(32).toString('hex'), { sameSite: 'lax', secure: true })   // (1)
  next()
})

function requireCsrf(req: Request, res: Response, next: NextFunction) {
  if (['GET', 'HEAD', 'OPTIONS'].includes(req.method)) return next()
  const cookie = Buffer.from(req.cookies.csrf ?? '')
  const header = Buffer.from(req.get('x-csrf-token') ?? '')
  if (cookie.length === 0 || cookie.length !== header.length || !timingSafeEqual(cookie, header)) {
    return res.status(403).json({ type: 'csrf_failed' })                                                          // (2)
  }
  next()
}
  1. A random token in a readable cookie. Your own front end reads it and sends it back in a header.
  2. Another site can make the browser send the cookie, but cannot read it to put it in the header, so forged requests fail.

5. What is server-side request forgery (SSRF), and how can it be mitigated? ​

The short answer

Server-side request forgery is when an attacker makes your server send a request to a destination they choose, usually by supplying a URL your code fetches, such as an avatar URL, a webhook address or a "preview this link" feature. Because the request comes from inside your network, it can reach internal services, admin panels, databases and the cloud metadata service, which hands out credentials. Mitigate it with allow-lists of destinations, blocking private and link-local addresses after resolving the name, disabling redirects, network-level egress rules, and requiring the metadata service's session tokens.

attacker"preview this URL"your networkAPI serverfetches the URLmetadata service169.254.169.254internal admin, databases①②③ secrets returned
Your server as the attacker's messenger. ① The attacker supplies an internal URL. ② Your server fetches it, from inside the network, where firewalls trust it. ③ Whatever it gets back, such as cloud credentials, goes to the attacker.
ts
import { lookup } from 'node:dns/promises'
import ipaddr from 'ipaddr.js'

const ALLOWED_HOSTS = new Set(['images.partner.example', 'cdn.shop.example'])

async function safeFetchImage(raw: string) {
  const url = new URL(raw)
  if (url.protocol !== 'https:') throw new HttpError(400, 'bad_url', 'Only https URLs are allowed')     // (1)
  if (!ALLOWED_HOSTS.has(url.hostname)) throw new HttpError(400, 'bad_url', 'Host not allowed')          // (2)

  const { address } = await lookup(url.hostname)
  if (ipaddr.parse(address).range() !== 'unicast') throw new HttpError(400, 'bad_url', 'Address not allowed')   // (3)

  return fetch(url, { redirect: 'error', signal: AbortSignal.timeout(5000) })                             // (4)
}
  1. Only HTTPS: no file:, gopher: or plain internal HTTP.
  2. An allow-list of hosts is the strongest control when you know where images come from.
  3. Block private, loopback and link-local addresses, checked on the resolved address, because a harmless-looking name can point to 10.0.0.5.
  4. No redirects: otherwise a public URL can redirect to an internal one. Also limit time and response size.

Defence in depth outside the code: run the service with network egress rules that only allow the destinations it needs, and require IMDSv2 session tokens on AWS so a simple forged GET cannot read the metadata service (the managed identity question). A name that resolves to a public address when checked and to a private one when fetched, called DNS rebinding, is defeated by connecting to the exact address you checked.

6. What are SQL injection and NoSQL injection, and how can they be prevented? ​

The short answer

Injection happens when untrusted input is mixed into a query or command as code instead of data, so the attacker can change what it does. In SQL injection, input such as ' OR '1'='1 changes a WHERE clause; in NoSQL injection, a JSON object such as { "$ne": null } sent where a string was expected changes a MongoDB filter. Prevent both by never building queries from strings, using parameterised queries or a query builder, validating types so an object cannot arrive where a string is expected, and running with least-privilege database accounts.

SQL injection:

ts
// Vulnerable: input becomes part of the SQL text
const rows = await db.query(`SELECT * FROM users WHERE email = '${req.body.email}'`)
// email = "' OR '1'='1" returns every user

// Safe: the value is sent separately and never interpreted as SQL
const rows2 = await db.query('SELECT id, email FROM users WHERE email = $1', [req.body.email])

NoSQL injection, in MongoDB:

ts
// Vulnerable: if password is { "$ne": null }, the filter matches any user with a password
const user = await users.findOne({ email: req.body.email, password: req.body.password })

// Safe: enforce types first, and never compare raw passwords in a query
const { email, password } = z.object({ email: z.string().email(), password: z.string().max(200) }).parse(req.body)
const found = await users.findOne({ email })
const ok = found && (await verifyPassword(found.passwordHash, password))
DefenceStops
Parameterised queries, prepared statements, ORMs used normallySQL injection
Schema validation of typesNoSQL operator injection, such as $ne and $gt
Allow-lists for sort fields and column namesInjection through identifiers, which cannot be parameterised (the filtering question)
Least-privilege database userLimits damage: no DROP, no access to other schemas
No raw query helpers with string interpolationAccidental unsafe queries in ORMs

Other injection targets follow the same rule: shell commands (the child processes question), LDAP filters, template engines and regular expressions built from user input.

7. What is clickjacking, and how can it be prevented? ​

The short answer

Clickjacking is when an attacker loads your site inside an invisible frame on their own page and tricks users into clicking it, for example placing your "Delete account" or "Confirm payment" button exactly under a fake "Play video" button. The user thinks they are clicking the attacker's page, but the click goes to your site, with their session. Prevent it by telling browsers not to frame your pages, with the Content Security Policy directive frame-ancestors 'none', or 'self', and the older X-Frame-Options: DENY header for legacy browsers.

ts
app.use(helmet({
  contentSecurityPolicy: { directives: { frameAncestors: ["'none'"] } },    // (1)
  frameguard: { action: 'deny' },                                           // (2)
}))
  1. The modern control: no site may put your pages in a frame.
  2. X-Frame-Options: DENY for older browsers.

When you do need framing, for example an embeddable checkout widget, allow only specific partner origins: frame-ancestors https://partner.example, and still require a deliberate confirmation step for sensitive actions inside the frame.

8. What is HTTP request smuggling? ​

The short answer

HTTP request smuggling exploits disagreements between a front-end proxy, such as a load balancer, and the back-end server about where one request ends and the next begins, usually because they interpret the Content-Length and Transfer-Encoding: chunked headers differently. An attacker sends one ambiguous request that the proxy sees as one request and the back end sees as two, so the hidden second request is processed as part of the next user's connection. That can bypass security checks done at the proxy, poison caches or capture other users' requests.

attackerone odd requestproxysees 1 requestback end: request Aleftover: request Bjoins next user'sthe two servers disagree about where the first request ends
One request to the proxy, two to the server. Ambiguous length headers make the proxy and the back end split the byte stream differently. The leftover bytes become a hidden request processed with someone else's connection.

Defences:

DefenceWhy
Keep proxies and servers patchedMost fixes are in parsers that now reject ambiguous requests
Reject requests with both Content-Length and Transfer-EncodingRemoves the ambiguity
Use HTTP/2 end to end where possibleHTTP/2 frames have explicit lengths
Do not rely only on the proxy for authorisationA smuggled request bypasses checks done only there (question 42)

Node.js's HTTP parser, llhttp, is strict by default and rejects most malformed requests. Avoid turning on lenient parsing options.

9. What is prototype pollution? ​

The short answer

Prototype pollution is a JavaScript-specific attack where untrusted input with keys like __proto__ or constructor.prototype is merged into an object, which changes Object.prototype, the object every plain object inherits from. Suddenly every object in the process has a property the attacker chose, such as isAdmin: true, which can bypass checks, crash the app or, combined with other code, run commands. Prevent it by not deep-merging untrusted JSON, validating input with strict schemas, using Map or Object.create(null) for dictionaries, and keeping libraries patched.

ts
function deepMerge(target: any, source: any) {                 // a naive merge
  for (const key in source) {
    if (typeof source[key] === 'object') {
      target[key] ??= {}
      deepMerge(target[key], source[key])
    } else {
      target[key] = source[key]
    }
  }
  return target
}

const settings = deepMerge({}, JSON.parse('{"__proto__": {"isAdmin": true}}'))   // (1)
const user = {}
console.log((user as any).isAdmin)                                             // (2) true
  1. target['__proto__'] is the object's prototype, Object.prototype, so the merge writes isAdmin onto it.
  2. Every object now has isAdmin: true, including users who were never admins. A check like if (user.isAdmin) passes for everyone.

Defences:

DefenceHow
Validate input against a strict schemaUnknown keys such as __proto__ are rejected (the validation question)
Skip dangerous keys in any mergeIgnore __proto__, constructor and prototype
Use Map, or Object.create(null)No prototype to pollute (the Map question)
Object.freeze(Object.prototype) at start-upMakes pollution impossible, if your dependencies tolerate it
Run with --disable-proto=deleteRemoves the __proto__ accessor in Node.js
Patch dependenciesSeveral popular merge and query-string libraries had this bug

Combine chapters into one PDF

Pick the chapters you want. They print in the order you pick them.

Interview Prep
Web & API Security
Attacks
Browser rules
Abuse
Secrets
Architecture
Other topics
Nothing picked yet