Appearance
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.
| Vulnerability | A typical Express mistake | Defence |
|---|---|---|
| Broken access control | GET /orders/:id returns any order to any signed-in user | Check ownership on every record (the authorisation middleware question) |
| Injection | String-built SQL, exec with user input | Parameterised queries, execFile (question 6) |
| Cross-site scripting | Rendering user HTML without escaping | Escape output, sanitise rich text, CSP (question 3) |
| Cross-site request forgery | Cookie sessions with no protection | SameSite cookies, CSRF tokens (question 4) |
| Server-side request forgery | Fetching any URL a user supplies | Allow-lists, block internal addresses (question 5) |
| Mass assignment | db.update(req.body) lets users set role | Accept only known fields (the validation question) |
| Secrets exposure | API keys in Git, tokens in logs | A secret manager, log redaction (question 30) |
| Vulnerable dependencies | Old packages, malicious updates | Lockfiles, audits, few dependencies |
| Information leaks | Stack traces in responses | Central error handler (the leaks question) |
| No abuse protection | Unlimited login attempts | Rate limits (question 28) |
| Prototype pollution | Deep-merging user JSON into objects | Safe merging, validation (question 9) |
| ReDoS | A slow regex on user input | Safe 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, 2025 | In a Node.js API |
|---|---|---|
| A01 | Broken Access Control, now including SSRF | Missing ownership checks; fetching attacker-chosen URLs |
| A02 | Security Misconfiguration | Debug mode in production, permissive CORS, default credentials |
| A03 | Software Supply Chain Failures | Malicious or compromised npm packages, unpinned dependencies |
| A04 | Cryptographic Failures | Weak password hashing, no TLS, secrets in plain text |
| A05 | Injection | SQL, NoSQL, shell and template injection |
| A06 | Insecure Design | No rate limits on a coupon endpoint; business logic flaws |
| A07 | Authentication Failures | Weak sessions, tokens not verified, no MFA for admins |
| A08 | Software or Data Integrity Failures | Unsigned webhooks, unverified updates, unsafe deserialisation |
| A09 | Security Logging and Alerting Failures | No audit logs; nobody alerted to an attack |
| A10 | Mishandling of Exceptional Conditions | Errors 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.
The three kinds:
| Kind | How the script arrives | Example |
|---|---|---|
| Stored | Saved on the server, shown to others | A review, a profile name, a support ticket |
| Reflected | Bounced back from the request | /search?q=<script>… echoed into the page |
| DOM-based | Front-end code writes untrusted data into the page | element.innerHTML = location.hash |
Defences, in order of importance:
- 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).
- 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.
- A strict Content Security Policy that blocks inline scripts, so injected
<script>tags do not run even if escaping fails somewhere (question 22). HttpOnlycookies, so a script cannot read the session cookie.- Validate URLs before putting them in
hreforsrc: allowhttps:only, neverjavascript:.
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.
Defences:
| Defence | How it helps |
|---|---|
SameSite=Lax or Strict on session cookies | The browser does not send the cookie on cross-site POST requests; see SameSite values |
| CSRF token | A secret value in the form or a header, which the attacker's page cannot read |
Check Origin or Sec-Fetch-Site | Reject state-changing requests from other origins |
No state changes on GET | Links and images cannot trigger actions |
| Re-authentication for sensitive actions | Changing 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()
}- A random token in a readable cookie. Your own front end reads it and sends it back in a header.
- 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.
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)
}- Only HTTPS: no
file:,gopher:or plain internal HTTP. - An allow-list of hosts is the strongest control when you know where images come from.
- Block private, loopback and link-local addresses, checked on the resolved address, because a harmless-looking name can point to
10.0.0.5. - 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))| Defence | Stops |
|---|---|
| Parameterised queries, prepared statements, ORMs used normally | SQL injection |
| Schema validation of types | NoSQL operator injection, such as $ne and $gt |
| Allow-lists for sort fields and column names | Injection through identifiers, which cannot be parameterised (the filtering question) |
| Least-privilege database user | Limits damage: no DROP, no access to other schemas |
| No raw query helpers with string interpolation | Accidental 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)
}))- The modern control: no site may put your pages in a frame.
X-Frame-Options: DENYfor 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.
Defences:
| Defence | Why |
|---|---|
| Keep proxies and servers patched | Most fixes are in parsers that now reject ambiguous requests |
Reject requests with both Content-Length and Transfer-Encoding | Removes the ambiguity |
| Use HTTP/2 end to end where possible | HTTP/2 frames have explicit lengths |
| Do not rely only on the proxy for authorisation | A 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) truetarget['__proto__']is the object's prototype,Object.prototype, so the merge writesisAdminonto it.- Every object now has
isAdmin: true, including users who were never admins. A check likeif (user.isAdmin)passes for everyone.
Defences:
| Defence | How |
|---|---|
| Validate input against a strict schema | Unknown keys such as __proto__ are rejected (the validation question) |
| Skip dangerous keys in any merge | Ignore __proto__, constructor and prototype |
Use Map, or Object.create(null) | No prototype to pollute (the Map question) |
Object.freeze(Object.prototype) at start-up | Makes pollution impossible, if your dependencies tolerate it |
Run with --disable-proto=delete | Removes the __proto__ accessor in Node.js |
| Patch dependencies | Several popular merge and query-string libraries had this bug |