SynfraCore
Synfracore
Start Learning
Navigation

Academies

Platform

RoadmapsLabsCertificationsInterviewPYQsAI AssistantCareer
Start Learning Free Learning Roadmaps

Full-Stack Developer Interview Questions

40+ original questions across HTML/CSS, JavaScript, TypeScript, React, Next.js, Node.js/Express, REST API design, authentication, databases, testing and deployment, and the AI-era skills every full-stack interview now touches.

15 Fresher20 Mid-Level10 Senior
Start mock interview HR round

Fresher

Why does a <button> element behave differently from a <div> with an onClick handler, even if both visually look like a button?
A native <button> comes with built-in behaviors a styled <div> doesn't: it's keyboard-focusable and activatable with Enter or Space by default, it's announced as a button by screen readers, and inside a form it submits that form unless told otherwise. A <div> with a click handler has none of this — it won't receive keyboard focus without an explicit tabindex, pressing Enter on it does nothing unless you wire that up yourself, and a screen reader has no idea it's interactive unless you add ARIA attributes. Using the semantic element gets all of this for free; recreating it on a <div> means manually reimplementing focus handling, keyboard activation, and accessibility semantics that the browser already provides. The practical rule: reach for the semantic element first, and only fall back to a styled generic element plus manual ARIA work when there's a real constraint forcing it.
What interviewers look for
  • names at least two concrete behaviors buttons get for free (keyboard activation, focus, form submission, screen reader semantics)
  • explains that a div needs manual work to replicate any of this
  • doesn't just say 'buttons are more semantic' without specifics
Likely follow-up: How would you make a styled div behave like a button if you truly couldn't use a button element?
A form submits and reloads the whole page even though the site is a single-page React app. What's the likely cause?
A <form> element's default behavior on submission is a full page navigation — a GET or POST request to the current URL (or whatever action points to) followed by a page reload, regardless of any JavaScript running on the page. If the form's submit handler calls event.preventDefault() too late, doesn't call it at all, or the handler is attached to the wrong element, the browser's default form submission still fires alongside or instead of the intended JavaScript handling. The fix is making sure preventDefault() runs synchronously inside the onSubmit handler, before any async work, since an async handler that awaits something first can let the default submission happen before the preventDefault call is ever reached. This is a common bug in React forms where a developer assumes a submit handler automatically stops the browser's native behavior.
What interviewers look for
  • identifies the browser's default form-submission behavior as the cause
  • mentions preventDefault() and that it needs to run early/synchronously
  • notes async handlers can let the default submission race ahead
An element with width: 200px and padding: 20px ends up visually wider than 200px. Why, and how does box-sizing: border-box change that?
By default, CSS uses the content-box box model, where width sets only the size of the content area — padding and border are added on top of that, outside the stated width, so an element with width: 200px, padding: 20px on each side, and a 1px border occupies 242px of total horizontal space (200 + 20 + 20 + 1 + 1). This surprises developers expecting width: 200px to mean 'this element is 200px wide, full stop.' Setting box-sizing: border-box changes what width measures: it now includes padding and border inside that 200px total, so the content area itself shrinks to accommodate them, and the element's rendered width stays exactly 200px regardless of how much padding or border is added. Many CSS resets apply box-sizing: border-box globally for exactly this reason — it makes width-based layouts predictable without having to manually subtract padding and border from every sizing calculation.
What interviewers look for
  • correctly explains the default content-box model adds padding/border outside the stated width
  • correctly explains border-box includes them inside the stated width instead
  • gives the concrete arithmetic or an equivalent concrete example
What's the difference between a dependency listed under dependencies versus devDependencies in package.json, and why does that distinction matter for deployment?
dependencies lists packages the application needs in order to run — a web framework, a database client, anything imported by code that executes in production. devDependencies lists packages only needed during development or the build process — a test runner, a linter, a bundler's plugin — that the running application itself never imports at runtime. The distinction matters at deployment because a production install typically runs with a flag (npm install --production, or NODE_ENV=production affecting some tools' default behavior) that skips installing devDependencies entirely, which keeps the deployed footprint smaller and avoids shipping development-only tooling to production. A common real mistake is putting something the app imports at runtime — a utility library used inside a route handler, for instance — under devDependencies by accident; it works fine locally where both are installed, but the production install skips it, and the app crashes with a missing-module error in production, which is exactly the kind of gap that doesn't show up until deployment.
What interviewers look for
  • correctly distinguishes runtime-needed vs build/dev-only packages
  • explains the production install behavior that skips devDependencies
  • names the concrete real-world failure mode of misclassifying a dependency
What does it mean that JavaScript is single-threaded, and how does fetch manage to not block the page while waiting for a network response?
Single-threaded means JavaScript's main execution thread can only run one piece of code at a time — there's no true parallel execution of two JavaScript functions on that thread. fetch doesn't violate this; the network request is handled outside JavaScript entirely, by the browser's own networking layer, which runs independently. fetch returns a Promise immediately and hands control back to the main thread, which keeps running other code (rendering, handling clicks) uninterrupted. Once the browser's networking layer finishes the request, it queues a callback (the Promise's resolution) onto the event loop's task queue, and JavaScript picks that callback up the next time the main thread is free. This is the core trick behind async JavaScript: the waiting happens outside the single thread, and only the quick 'handle the result' step runs on it, which is why a slow network request doesn't freeze the UI the way a long synchronous loop would.
What interviewers look for
  • explains the browser (not JS) handles the waiting
  • mentions the event loop/task queue picking up the callback later
  • contrasts this with a synchronous blocking operation freezing the UI
Likely follow-up: What would happen to the UI if you ran a very long synchronous for-loop instead?
What's the practical difference between == and === in JavaScript, and why do most style guides ban ==?
=== (strict equality) compares both value and type without converting either operand — 1 === '1' is false because a number and a string are different types. == (loose equality) first performs type coercion if the operands differ in type, then compares — 1 == '1' is true because the string gets coerced to a number first. The coercion rules behind == aren't always intuitive: 0 == false is true, '' == false is true, but [] == false is also true for reasons that take real memorization to predict reliably. Style guides ban == because bugs from unexpected coercion are hard to spot during review and easy to introduce accidentally, while === behaves predictably in every case. The one common exception some teams allow is == null, since it conveniently matches both null and undefined in one comparison — but even that's usually written explicitly as value === null || value === undefined in strict codebases.
What interviewers look for
  • correctly explains type coercion is what == does and === skips
  • gives at least one concrete surprising coercion example
  • explains why === is preferred (predictability), not just 'because it's stricter'
A function defined inside a loop captures the loop variable, but every callback ends up logging the same final value instead of the value at the time it was created. What's happening, and how is it fixed?
This classic bug happens with var, which is function-scoped, not block-scoped — every iteration of the loop shares the same single var binding, so by the time any of the deferred callbacks run, the loop has already finished and the variable holds its final value. All the callbacks close over that same single variable, not a snapshot of its value at each iteration. Switching the loop variable's declaration to let fixes this directly, because let is block-scoped: each iteration gets its own fresh binding, and each callback closes over that iteration's own copy instead of one shared one. Before let existed, the common workaround was wrapping the loop body in an immediately-invoked function expression to manually create a new scope per iteration — let made that pattern unnecessary for this specific case, which is part of why it's the default choice for loop counters now.
What interviewers look for
  • correctly identifies var's function scoping (not block scoping) as the cause
  • explains let creates a new binding per iteration
  • mentions the IIFE workaround or shows awareness it predates let, even briefly
What does TypeScript check, and what doesn't it protect against at runtime?
TypeScript's type checking happens entirely at compile time, before the code ever runs — it catches mismatches between declared types (a function expecting a string being called with a number, a property access on a type that doesn't have that property) by analyzing the code statically. Once compilation succeeds, TypeScript erases all of its type annotations, producing plain JavaScript with zero runtime type information left — there is no TypeScript runtime checking a value's shape while the program executes. This means data crossing a real boundary the compiler can't see into — a JSON response from an API, user input, a value read from localStorage — is only as trustworthy as whatever cast or assertion was applied to it; if an API response is typed as matching an interface but the API returns something different in practice, TypeScript has no way to catch that mismatch, because by the time the code runs, the type information is already gone.
What interviewers look for
  • correctly states types are erased at compile time, nothing left at runtime
  • identifies external data (API responses, user input) as the real risk
  • doesn't claim TypeScript provides any runtime validation by itself
Likely follow-up: What would you add to validate an API response's shape at runtime?
What's the difference between state and props in React, and why can't a component modify props it receives?
Props are values passed down from a parent component to a child — the child receives them as a read-only input, the same way a function receives arguments. State is data a component owns and manages itself, which it can update over time via useState (or a reducer), and changing it triggers that component to re-render. Props are read-only by design because React's data flow is meant to be predictable and traceable: if a child could silently mutate the props object it received, a parent passing that same object to multiple children would have no reliable way to know which child changed it or when, breaking the top-down data flow the whole rendering model depends on. If a component needs to change something it was given, the mechanism is calling a function the parent passed down as a prop (a callback), letting the parent update its own state and re-render with new prop values flowing back down — the child never mutates the prop directly.
What interviewers look for
  • correctly distinguishes props (read-only, parent-owned) from state (owned, mutable)
  • explains why mutating props would break predictable top-down data flow
  • mentions the callback-prop pattern for 'lifting' a change back up
A list of items rendered with .map() throws a console warning about missing key props. Why does React need this, and what's a bad choice for a key?
React uses the key prop to track which rendered element corresponds to which piece of data across re-renders, so it can efficiently figure out what changed — which items were added, removed, or reordered — instead of re-rendering the entire list from scratch every time. Without a stable key, React falls back to matching elements by their position in the array, which breaks badly the moment items are reordered, inserted, or removed from the middle: a component that should've stayed matched to the same data item instead gets matched to whatever's now at that same index, which can show stale state or cause unnecessary re-renders of the wrong elements. Using the array index as the key is a common but fragile choice for exactly this reason — it's stable only if the list never reorders or has items inserted/removed anywhere but the end. A stable, unique identifier from the data (a database id, a UUID) is the correct key, since it stays attached to the same logical item regardless of where that item currently sits in the array.
What interviewers look for
  • explains keys let React match elements to data across re-renders
  • explains why array index breaks on reorder/insert/remove
  • recommends a stable data-derived id instead of index
What is the Node.js event loop, in plain terms, and why does a CPU-heavy synchronous function block every other request on the server?
Node.js runs JavaScript on a single main thread, and the event loop is the mechanism that keeps that thread cycling through pending callbacks — checking for completed I/O operations (a finished file read, a database query result, a network response), running their callbacks, and repeating. This is what lets a Node server handle many concurrent requests on one thread: while one request is waiting on a database query, the thread isn't idle, it's free to process other requests' callbacks in the meantime, since waiting on I/O doesn't occupy the thread the way running JavaScript code does. A CPU-heavy synchronous function — a large in-memory sort, a tight computational loop with no awaits — is a different story entirely: it runs to completion on that one single thread before anything else can run, which means every other pending request, no matter how simple, is stuck waiting behind it. This is why CPU-intensive work on a Node server typically gets offloaded to a worker thread or a separate process, rather than run inline on the main event loop.
What interviewers look for
  • explains the single-thread, non-blocking-I/O model correctly
  • explains why I/O waiting doesn't block but synchronous CPU work does
  • mentions offloading CPU work to worker threads/separate processes as the real fix
What does Express middleware do, and why does the order in which you register it matter?
Express middleware is a function that runs on an incoming request before the final route handler, with access to the request, the response, and a next() function it calls to pass control along to whatever comes next in the chain — if it never calls next() (or sends a response itself), the request stalls there indefinitely. Order matters because Express processes middleware strictly in the order it was registered, and each piece typically depends on something a prior one set up: an authentication-checking middleware has to run before a route handler that assumes the request is already authenticated, a body-parsing middleware has to run before any handler that reads req.body, and an error-handling middleware generally needs to be registered last so it can catch errors from everything before it. Registering authentication after the route it's meant to protect, for example, means the route handler runs unprotected — the auth check never gets a chance to block the request first.
What interviewers look for
  • correctly explains next() and the request/response/next signature
  • explains ordering dependencies with at least one concrete example
  • notes that skipping next() without responding stalls the request
What's the difference between a 401 and a 403 HTTP status code, and why does mixing them up hurt API consumers?
401 Unauthorized means the request lacks valid authentication entirely — the server doesn't know who's asking, usually because a token is missing, expired, or invalid, and the correct client response is to prompt the user to log in again. 403 Forbidden means the server does know who's asking — authentication succeeded — but that identity isn't allowed to perform this specific action, which calls for a completely different client response: telling the user they lack permission, not asking them to log in again, since logging in again with the same account won't change anything. Returning 401 when the real issue is a permissions problem sends a client down the wrong recovery path entirely — it'll likely try to refresh the token or re-prompt for login, which does nothing, when what's needed is surfacing a 'you don't have access to this' message instead. Getting this distinction right in an API's design directly determines whether client error-handling code can react correctly without guessing.
What interviewers look for
  • correctly distinguishes 'who are you' (401) from 'you can't do that' (403)
  • explains the different correct client-side responses to each
  • connects the mix-up to a concrete bad client behavior, not just 'it's confusing'
What's the practical difference between authentication and authorization, and where in a typical request does each one happen?
Authentication answers 'who is this' — verifying an identity, typically by checking credentials (a password, a token, a session) against something the server trusts. Authorization answers a separate question that only makes sense once identity is known: 'is this specific identity allowed to do this specific thing' — checking a role, a permission, or an ownership relationship against the action being requested. In a typical request flow, authentication happens first, usually in middleware near the top of the request-handling chain, establishing who the request is from (or rejecting it outright if that can't be established); authorization happens afterward, often inside or close to the specific route handler, since what's allowed can depend on exactly which resource or action is being requested. A request can pass authentication cleanly (the token is valid, the user is real) and still be rejected by authorization (that real, legitimately-logged-in user just isn't allowed to delete someone else's data) — conflating the two checks into one step is a common source of bugs where a valid-but-unauthorized action gets through.
What interviewers look for
  • correctly distinguishes 'who are you' from 'what can you do'
  • explains the typical ordering (authn before authz) and why
  • gives a concrete example where authn passes but authz should still fail
You use an AI coding assistant to generate a React form component. What should you check before accepting its suggestion, beyond whether it looks correct?
Looking correct and being correct are different checks — an AI assistant can produce code that compiles and renders fine while still getting something subtly wrong: using the array index as a React key on a list that reorders, skipping input validation on a form field, or including a dependency in a useEffect array that isn't really needed and causes an extra re-render. The practical habit is treating generated code the same way you'd treat a pull request from someone whose work you haven't reviewed before — run it, test the specific edge cases that matter for this form (empty input, invalid input, a slow network on submit), and read through the logic rather than just glancing at the result. It's also worth checking whether the suggestion matches the codebase's existing patterns (the same form library, the same validation approach already used elsewhere) rather than introducing a new, inconsistent pattern just because that's what the assistant happened to generate. The assistant is a fast first draft, not a substitute for understanding what the code does.
What interviewers look for
  • names at least one concrete category of subtle bug AI-generated code can have
  • proposes real verification steps (edge cases, reading the logic), not just visual inspection
  • mentions consistency with existing codebase patterns

Mid-Level

Two sibling elements are both set to position: absolute inside a relatively positioned parent, and their layout looks correct until the parent's height collapses to zero. Why?
Absolutely positioned elements are taken out of the normal document flow entirely — they no longer contribute to their parent's height calculation, which is why a parent containing only absolutely positioned children collapses to zero height unless it has an explicit height set or other in-flow content. This surprises developers who assume position: relative on the parent plus position: absolute on children behaves like normal nested boxes; it only establishes a positioning context (so the children's top/left/right/bottom are relative to that parent), it doesn't restore the children's contribution to layout flow. The fix depends on intent: give the parent an explicit height, add a sized in-flow element inside it, or reconsider whether absolute positioning is the right tool — Flexbox or Grid usually handle this kind of layout without taking anything out of flow at all.
What interviewers look for
  • explains that absolutely positioned elements don't contribute to parent height
  • distinguishes 'positioning context' from 'contributes to layout flow'
  • offers a concrete fix, not just a diagnosis
What's the difference between a shallow copy and a deep copy of a nested object, and where does a naive spread ({ ...obj }) fall short?
A shallow copy creates a new top-level object, but any nested objects or arrays inside it still point to the exact same references as the original — mutating a nested property through the copy also changes the original, because both copies share that inner object. { ...obj } only copies top-level properties by value (for primitives) or by reference (for objects/arrays), so it's shallow by definition: copy.nested.value = 5 would mutate original.nested too, since copy.nested and original.nested are the same object in memory. A true deep copy recursively clones every nested level so no references are shared at any depth — structuredClone() is the modern built-in way to do this correctly for most data (it handles circular references and many types JSON.parse(JSON.stringify()) can't, like Date objects, though it still can't clone functions or DOM nodes). Reaching for a deep copy is only necessary when nested mutation needs to be isolated; for flat objects, a shallow copy is simpler and sufficient.
What interviewers look for
  • explains shared references at nested levels as the core issue
  • gives a concrete mutation example showing the shared reference
  • names structuredClone (or at least contrasts it correctly with JSON.stringify's limits)
Several fetch calls need to run concurrently, and the UI should show results as soon as any one of them finishes rather than waiting for all of them. Which Promise combinator fits, and why not Promise.all?
Promise.race resolves or rejects as soon as the first of the given promises settles, which fits a 'show the first result, regardless of which request it came from' requirement — though it's worth noting race settles on the first to finish even if that one rejects, which can surface an error before a slower-but-successful request gets a chance. If the need is 'show every result as it individually arrives, not just the fastest one,' the better fit is often attaching a .then() handler to each promise individually rather than using a combinator meant to collapse several promises into a single outcome. Promise.all is the wrong tool here because it waits for every promise to resolve before resolving itself, and rejects entirely the moment any single one rejects — exactly the 'wait for everything, fail on one failure' behavior this requirement explicitly wants to avoid. Promise.allSettled is the right combinator when the goal is waiting for all of them but tolerating individual failures.
What interviewers look for
  • correctly rules out Promise.all for this specific requirement
  • names Promise.race and its reject-on-first-settle caveat, or proposes individual .then() handlers
  • distinguishes allSettled's use case from race's
Likely follow-up: When would Promise.allSettled be the better choice over individual .then() handlers?
What's the difference between a TypeScript interface and a type alias, and when does the distinction matter in practice?
For most everyday use — describing the shape of an object — interface and type are close to interchangeable, and teams often pick one as a style convention. The real differences show up at the edges: interfaces support declaration merging (defining the same interface name twice in different files augments it into one combined shape, which is how libraries let consumers extend built-in types), while type aliases don't merge and will error on a duplicate name. type aliases, on the other hand, can represent things interfaces fundamentally can't — union types (type Status = 'idle' | 'loading' | 'error'), mapped types, and conditional types all require type. A practical rule many teams use: default to interface for object shapes that might need extension (public APIs, component props), and reach for type whenever a union, intersection, or other non-object-shape construct is needed.
What interviewers look for
  • correctly identifies declaration merging as unique to interfaces
  • correctly identifies unions/mapped/conditional types as requiring type aliases
  • doesn't claim one is strictly 'better' without the nuance
A generic function needs to accept any array and return its first element with the correct type, not any. How would you type it?
A generic type parameter captures the specific element type at the call site: function first<T>(arr: T[]): T | undefined { return arr[0]; }. Calling first([1, 2, 3]) infers T as number, so the return type is correctly number | undefined, not any — TypeScript infers T from the argument without the caller needing to specify it explicitly, though it can be specified manually (first<string>([])) when inference alone wouldn't have enough information. The | undefined in the return type matters: an empty array's first element doesn't exist at that index, and a type ignoring that case would lie about what the function can return, silently allowing a caller to treat undefined as if it were a valid T downstream. This is a common real bug source — a generic helper that looks fully type-safe but quietly drops the empty-input case from its return type.
What interviewers look for
  • correctly writes or describes a generic type parameter, not any
  • explains type inference from the call site
  • catches the undefined-for-empty-array edge case in the return type
A useEffect that fetches data on every keystroke in a search box causes a flood of requests and a results flicker. How would you fix it?
The flood of requests comes from firing a fetch on every single state change with no delay, when the intent is almost always 'fetch once the user has paused typing.' Debouncing the search term — delaying the fetch until a set period has passed without another keystroke, and cancelling the pending delay if a new one arrives first — cuts the request count down to roughly one per pause instead of one per character. The flicker, a separate issue, usually comes from an earlier, slower request's response arriving after a later request's response and overwriting it with stale results; the fix there is tracking which request is the most recent (an incrementing counter or an AbortController tied to each effect run) and discarding any response that isn't from the latest request, or aborting the previous fetch outright when a new one starts. Both fixes commonly live inside the same useEffect, with its cleanup function handling the cancellation/abort when the effect re-runs or the component unmounts.
What interviewers look for
  • identifies debouncing as the fix for request volume
  • separately identifies stale-response race conditions as the flicker's cause
  • mentions AbortController or a request-ordering guard, and the effect cleanup function
Likely follow-up: Why does the cleanup function matter here, beyond just unmounting?
What's prop drilling, and when is lifting state plus passing props down still the right call instead of reaching for Context or a state library?
Prop drilling is passing a value down through several layers of components that don't themselves use it, purely so a deeply nested descendant can access it — each intermediate component has to accept and forward a prop it has no use for. It becomes a real maintenance problem once the chain gets long or the prop needs to reach many different branches of the tree, since adding or renaming that prop means touching every intermediate component along the way. That said, prop drilling through two or three levels is often simpler and more explicit than reaching for Context — Context adds its own overhead (a provider, a consumer hook, and a value that re-renders every consumer when it changes) and can make data flow harder to trace by sight, since a deeply nested component's data source is no longer visible from its own call site. The practical threshold most teams use: reach for Context (or a dedicated state library) when the same value needs to reach many unrelated branches, not just because the chain has gotten slightly longer than ideal.
What interviewers look for
  • correctly defines prop drilling
  • doesn't treat Context as a free upgrade — names its own costs
  • gives a reasonable practical threshold for when each approach fits
What does React.memo do, and why wrapping a component in it sometimes has no effect on performance at all?
React.memo wraps a component so React skips re-rendering it when its props haven't changed between renders, using a shallow comparison by default — it compares each prop by reference (for objects/functions/arrays) or by value (for primitives), not by deep equality. The reason it often does nothing in practice: if a parent re-creates a new object, array, or inline function on every render and passes it as a prop (a common pattern — onClick={() => doThing(id)} creates a brand-new function reference every render), the shallow comparison sees a different reference every time and re-renders anyway, even though the function behaves identically. React.memo only pays off when the props it's comparing are stable across renders — primitives that haven't changed, or objects/functions properly memoized with useMemo/useCallback on the parent side. Wrapping a component in memo without first making sure its props are stable is a common case of adding overhead (the comparison itself isn't free) for no benefit.
What interviewers look for
  • correctly explains the shallow comparison React.memo performs
  • identifies new object/function references on every render as the reason it fails
  • connects this to useMemo/useCallback on the parent as the fix
What's the practical difference between server-side rendering and static generation in Next.js, and when would you choose each?
Static generation renders a page to HTML once, at build time, and serves that same pre-rendered file to every visitor until the next deploy or on-demand revalidation — it's the fastest possible response since there's no per-request rendering work at all, which makes it a strong fit for content that's the same for every visitor and doesn't change on every request, like a marketing page or a blog post. Server-side rendering renders the page fresh on every single request, on the server, which is necessary when the response depends on something only known at request time — a logged-in user's personalized data, a value from a cookie, or content that must always be current to the second. The trade-off is straightforward: static generation is cheaper and faster but can go stale between rebuilds (mitigated with incremental static regeneration, which re-renders a static page in the background after a set interval), while server-side rendering is always fresh but costs real compute on every request and can't be served instantly from a cache the way a static file can.
What interviewers look for
  • correctly explains build-time vs request-time rendering
  • gives a concrete case where SSR is necessary (request-time personalization)
  • mentions ISR as the middle ground, even briefly
An Express route handler that reads a file with the synchronous fs.readFileSync works fine in testing but causes noticeable latency spikes for other requests under real traffic. Why?
fs.readFileSync blocks the entire event loop for the duration of the disk read — on a single developer's machine testing one request at a time, that block is short and essentially invisible. Under real concurrent traffic, every other in-flight request's processing is paused for that same duration, because the single thread can't do anything else while a synchronous call is running. The fix is using the asynchronous, Promise-based or callback-based version (fs.promises.readFile or fs.readFile), which hands the disk I/O off to Node's underlying thread pool and only resumes JavaScript execution via a callback once the read completes — freeing the main thread to keep handling other requests' callbacks in the meantime. This is a common gap between local testing and production behavior because blocking behavior only becomes visible under concurrency; a single request in isolation can't reveal that it was starving others of the event loop.
What interviewers look for
  • correctly explains readFileSync blocks the single event loop thread
  • explains why this is invisible in solo testing but visible under concurrency
  • names the async alternative and that it uses the thread pool for the I/O
How would you structure centralized error handling in an Express app so routes don't each need their own try/catch boilerplate?
Express supports error-handling middleware — a middleware function with four parameters (err, req, res, next) instead of three — which Express routes any error to automatically if it's passed to next(err), or thrown inside a synchronous handler. The practical structure most apps use: a thin async wrapper around each route handler that catches a rejected Promise and forwards it to next(err), so individual route handlers can just await their async work without a try/catch around every single one, and a single error-handling middleware registered last in the chain decides how to format and log the response based on the error's type (a validation error vs. a database error vs. an unexpected exception each warrant a different status code and message). This keeps route handlers focused on their logic, puts error formatting and logging in exactly one place, and avoids the common bug where an unhandled Promise rejection inside an async route handler silently never reaches Express's error handling at all, since Express's older built-in handling doesn't automatically catch async errors without that wrapper.
What interviewers look for
  • correctly describes the four-parameter error-middleware signature
  • proposes an async-wrapper pattern or equivalent instead of per-route try/catch
  • mentions the real gap: unhandled async rejections not reaching error middleware without a wrapper
An endpoint that deletes a resource is called twice in a row by a flaky client retry — once successfully, once after the resource is already gone. What should the second call return, and why does idempotency matter here?
A well-designed DELETE endpoint should be idempotent — calling it multiple times with the same input should leave the system in the same end state as calling it once, which for deletion means 'the resource doesn't exist' is the correct end state whether this is the first delete call or the fifth. The practical choice is returning a success status (204 No Content, or sometimes 200) for the second call too, rather than a 404, because the client's goal — 'make sure this resource is deleted' — has already been achieved; treating the retry as an error forces the client to distinguish 'already deleted by my own earlier call' from 'never existed,' which is rarely useful information and complicates retry logic unnecessarily. This matters beyond this one endpoint because network retries are common and expected — a client that times out waiting for a response has no way to know whether its request succeeded before the timeout, so it reasonably retries, and an API that isn't idempotent under retries can produce confusing or incorrect behavior exactly when things are already going wrong at the network level.
What interviewers look for
  • correctly defines idempotency (same end state regardless of call count)
  • recommends treating a repeat delete as success, not a 404, with reasoning
  • connects this to why retries happen in the first place (timeouts, flaky networks)
Should a 'search users' endpoint be a GET with query parameters or a POST with a JSON body? What drives the decision?
GET with query parameters is the more RESTful default for a search — it's cacheable, bookmarkable, and matches the semantic meaning of GET as a safe, read-only operation that doesn't change server state. The practical limit is query string length and complexity: most browsers and intermediary infrastructure (proxies, load balancers, CDNs) impose a maximum URL length, and a search with many filters, nested criteria, or a large list of ids to match against can realistically exceed that limit or become unreadable as a flat query string. In that case, a POST-based search endpoint (sometimes modeled as a 'search' action rather than a strict resource) becomes the pragmatic choice, even though it sacrifices caching and bookmarkability, because a JSON body has no comparable length constraint and can represent nested, structured search criteria naturally. The decision isn't really about strict REST purity versus pragmatism in the abstract — it's about whether the search criteria fit comfortably in a URL, which most simple searches do and some complex ones don't.
What interviewers look for
  • correctly identifies GET as the RESTful default and why (cacheable, safe, bookmarkable)
  • names the real constraint driving a switch to POST (query-string length/complexity limits)
  • doesn't treat this as a pure dogma question — grounds it in the trade-off
What does it mean that a JWT is 'stateless,' and what real problem does that create for logging a user out before their token naturally expires?
A JWT is self-contained — once issued, the server validates it purely by checking its signature against a known secret or key, with no database lookup or server-side session record needed, which is exactly what 'stateless' means here and why JWTs scale well across multiple servers with no shared session store required. The real problem this creates: there's no server-side record of issued tokens to delete, so a 'logout' that only deletes the token from the client's storage leaves the token itself still cryptographically valid until its expiry time — anyone who captured that token before logout (a stolen token, a browser extension with access to storage) can keep using it normally, since the server has no way to know it was supposed to be revoked. Common mitigations include keeping token lifetimes short and relying on a refresh-token mechanism (where the longer-lived refresh token can be revoked server-side, since issuing a new refresh token does require a database check), or maintaining a server-side denylist of explicitly revoked token ids — which reintroduces some server-side state to solve this one problem, somewhat undercutting the pure statelessness JWTs are chosen for in the first place.
What interviewers look for
  • correctly explains statelessness means no server-side session record
  • correctly identifies the revocation problem this creates
  • names at least one real mitigation (short expiry + refresh tokens, or a denylist)
Likely follow-up: Why might a short-lived access token plus a longer-lived, revocable refresh token be a better trade-off than one long-lived token?
Where should a JWT be stored in the browser — localStorage, a cookie, or memory — and what's the real security trade-off between them?
Storing a token in localStorage is readable by any JavaScript running on the page, which means an XSS vulnerability anywhere in the app — even in a dependency, not just first-party code — can read and exfiltrate every stored token directly; localStorage is also not automatically sent with requests, so it requires manually attaching the token to every outgoing request's headers. A cookie marked HttpOnly can't be read by JavaScript at all, which closes off the XSS-token-theft path directly, but cookies are automatically attached to matching requests by the browser, which opens a different risk — CSRF, where a malicious site can trigger a request that rides along with the cookie — mitigated with SameSite cookie attributes and, for extra safety, a separate CSRF token. Storing a token only in memory (a JavaScript variable, never persisted) avoids both storage-based risks entirely but means the token is lost on every page refresh, requiring a refresh-token flow (often via an HttpOnly cookie) to silently re-establish it. There's no single universally correct answer — it's a real trade-off between XSS exposure, CSRF exposure, and UX continuity across refreshes, and most production setups combine an HttpOnly refresh-token cookie with a short-lived in-memory access token to get the better side of each trade-off.
What interviewers look for
  • correctly explains the XSS risk of localStorage
  • correctly explains the CSRF risk introduced by cookies, and SameSite as a mitigation
  • names the common hybrid pattern (HttpOnly refresh cookie + in-memory access token) as the practical answer
An endpoint that lists a user's orders along with each order's items runs one query per order to fetch items, and the page gets noticeably slower as a user accumulates more orders. What's happening, and how is it fixed?
This is the classic N+1 query problem: one query fetches the list of N orders, and then a separate query runs per order to fetch that order's items, for a total of N+1 queries instead of a small, fixed number — the latency scales directly with how many orders the user has, which is exactly the slowdown pattern described. The standard fix is batching the items fetch into a single query using a WHERE order_id IN (...) with all the order ids collected up front, then grouping the results back onto their respective orders in application code, turning N+1 round trips into 2. An ORM-level fix, if one is in use, is enabling eager loading (a JOIN or an ORM's built-in include/with mechanism) so the ORM itself issues the batched query instead of lazily triggering a new query per related record as application code iterates over the list. Either approach trades a small amount of extra complexity (joining or grouping data in code) for a query count that stays constant regardless of how many orders a user has.
What interviewers look for
  • correctly names the N+1 pattern
  • explains why latency scales with record count
  • proposes a concrete fix: batched IN query or ORM eager loading
A query filtering on a column runs fine in development with a small dataset but takes seconds in production with millions of rows. What's the first thing you'd check, and what does an index do here?
The first thing to check is the query's execution plan (EXPLAIN in PostgreSQL/MySQL), which shows whether the database is doing a sequential scan — reading every single row in the table to find matches — or using an index to jump directly to relevant rows. A small development dataset makes a sequential scan fast enough to be invisible, since scanning a few hundred rows takes microseconds; the same sequential scan against millions of rows is slow, which is exactly why this kind of performance bug often doesn't show up until production data volume reveals it. An index on the filtered column is essentially a separate, ordered data structure (commonly a B-tree) that lets the database locate matching rows directly instead of checking every row one by one, turning an operation that scales with total table size into one that scales closer to the size of the result set. The trade-off worth knowing: indexes speed up reads on that column but add overhead to every write (insert/update/delete) that touches it, since the index itself has to be kept up to date — so indexing every column isn't free and isn't automatically the right call everywhere.
What interviewers look for
  • proposes checking the execution plan / EXPLAIN as the first diagnostic step
  • correctly explains why dev-scale data hides the problem
  • explains what an index does structurally, and names the write-overhead trade-off
What's the practical difference between a unit test, an integration test, and an end-to-end test for a full-stack feature, and why do most teams want more of the first than the last?
A unit test checks one isolated piece of logic — a single function, a single component's rendering logic — in isolation from everything around it, usually with dependencies mocked out, which makes unit tests fast to run and precise about pinpointing exactly what broke. An integration test checks that several real pieces work correctly together — an API route really talking to a real (often test) database, for example — catching issues unit tests miss, like a mismatch between what one layer produces and what the next layer expects, at the cost of being slower and needing more setup. An end-to-end test drives the whole system the way a real user would, typically through a real browser hitting a real running app, which is the most realistic check but also the slowest, most brittle (small UI changes can break tests unrelated to what changed), and most expensive to maintain at scale. The common 'testing pyramid' guidance — many unit tests, fewer integration tests, very few end-to-end tests — exists because that shape gives the fastest feedback and the most precise failure signal for the least total test-suite runtime, reserving the slow, broad end-to-end tests for the handful of critical user journeys that need that level of realism.
What interviewers look for
  • correctly distinguishes the three levels by isolation/realism and speed trade-offs
  • explains the testing pyramid shape and why, not just naming it
  • gives at least one concrete example per level
A teammate pastes a full-stack feature's error message and stack trace into a public AI chat tool to get a quick fix. What is the real risk here, beyond generic 'security' concerns?
A stack trace or error message from a real application frequently contains more than the error itself — file paths that reveal internal project structure, variable names that hint at business logic, sometimes a fragment of a database query with a real table or column name, or occasionally an accidentally-logged value that was meant to stay internal (a token, a partial user record). Pasting that into a public tool with no data-handling agreement in place means that information leaves the organization's control with no way to know how it's retained, who else might see it in aggregate, or whether it's used to improve a model others later interact with. The practical fix isn't avoiding AI tools for debugging — it's redacting or replacing anything specific to the real system (real table/column names, real file paths, any literal data values) with clearly fake placeholders before pasting, which almost never changes whether the AI tool can still help diagnose the error, since the error's shape and the surrounding code's logic are what matters for a fix, not the specific internal names involved.
What interviewers look for
  • identifies concrete leak risks beyond a vague 'security' concern (paths, logic, data values)
  • explains the control-loss problem once pasted into a public tool
  • proposes redaction as the practical fix, not avoidance of AI tools entirely
An AI assistant suggests adding a new npm dependency to solve a small formatting problem that could be solved in five lines of plain JavaScript. What's the real cost of accepting that suggestion?
Every added dependency becomes part of the app's attack surface and long-term maintenance burden — it needs security patches tracked indefinitely, it can introduce its own transitive dependencies with their own vulnerabilities, and it adds to bundle size even if the functionality used from it is small. AI assistants tend to reach for a well-known package readily, since that's a common solved pattern in their training data, without necessarily weighing whether the problem is really small enough to not need one — they're optimizing for 'a working answer,' not for 'the leanest dependency footprint for this specific codebase.' The practical judgment call: if the problem needs five lines of well-understood logic with no edge cases worth a battle-tested library's handling, writing it directly avoids the ongoing cost of a dependency that provides little real benefit over the simple version. If the problem has real edge cases a library has already solved carefully (date parsing, deep object comparison), the dependency is usually worth it — the judgment is evaluating the AI's suggestion against the real problem size, not accepting it by default because it was offered.
What interviewers look for
  • names concrete costs of a new dependency (attack surface, transitive deps, bundle size, ongoing maintenance)
  • explains why an assistant might over-suggest a dependency for a small problem
  • gives a reasonable judgment criterion for when a dependency IS worth it

Senior

A component library needs to support both light and dark themes, plus per-brand color overrides for several client deployments, without a JavaScript rebuild for each. How would you structure the CSS?
CSS custom properties (variables) defined at a high-level scope — typically :root or a theme wrapper element — solve this cleanly: define semantic tokens like --color-surface and --color-text-primary rather than raw hex values, and every component references those tokens instead of hardcoded colors. Theme switching becomes a matter of redefining the token values on a different selector ([data-theme='dark'], or a brand-specific class), which the browser re-resolves instantly with no JavaScript rebuild or CSS recompilation needed. Per-brand overrides layer on top the same way: a brand wrapper redefines a small subset of tokens, and every component underneath picks up the change automatically since they never reference raw colors directly. The key discipline is naming tokens by role (surface, primary action, danger) rather than by value (blue-500), since a brand override changing what 'primary action' looks like shouldn't require touching component code at all.
What interviewers look for
  • proposes CSS custom properties as the mechanism, not a JS-based theme switcher
  • distinguishes semantic/role-based tokens from raw color values
  • explains why no rebuild is needed — the browser re-resolves variables live
Likely follow-up: How would you handle a component that needs a color value JavaScript also needs to read (e.g. for a canvas chart)?
A web app's main bundle includes a large charting library that's only used on one rarely-visited admin page. How would you address the resulting bundle size?
Dynamic imports (import() instead of a static top-level import) let a bundler split that charting library into its own separate chunk that only loads when the code path requiring it executes, rather than being bundled into the main entry point every visitor downloads. In a React app this usually pairs with React.lazy and Suspense so the admin page's component (and everything it imports) loads on demand, with a loading fallback shown while that chunk fetches. The measurable win is for the common case: visitors who never touch the admin page never download the charting library at all, shrinking the main bundle and improving the metrics that matter for first-time visitors (first contentful paint, time to interactive). The trade-off is a brief loading state the first time someone does visit that page — acceptable for a rarely-visited admin screen, much less acceptable for something on the critical path every visitor hits, where the cost should be paid once in the main bundle instead of as a visible delay.
What interviewers look for
  • names dynamic import/code splitting as the mechanism
  • connects it to a concrete bundler/framework pattern (React.lazy + Suspense or equivalent)
  • discusses the trade-off (loading state) and when NOT to split
A large dashboard re-renders its entire component tree whenever any single widget's data updates, even widgets with no relationship to the changed data. How would you diagnose and fix this at scale?
The root cause in most large trees like this is state held too high — a single state object at the top of the tree that every widget reads from, so any update to any part of it re-renders every consumer, since React re-renders a component whenever the state or context value it reads from changes, regardless of whether the specific slice that component cares about changed at all. The fix usually combines a few techniques: splitting that one large state object into smaller, independently-updatable pieces scoped closer to where they're really used; using a selector-based state library (or useSyncExternalStore with manual selectors) so a component only re-renders when the specific slice it subscribes to changes, not the whole store; and memoizing widget components with React.memo once their props are stable, so even an unrelated parent re-render doesn't cascade down unnecessarily. Profiling with React's own DevTools Profiler first, rather than guessing, is what tells you whether the bottleneck is re-render count, render cost per component, or something else like unnecessarily large payloads being passed as props.
What interviewers look for
  • identifies over-centralized state as the likely root cause, not just 'React is slow'
  • proposes concrete fixes: state splitting, selector-based subscriptions, targeted memoization
  • mentions profiling before optimizing, not just applying fixes blindly
A Next.js app's client-side JavaScript bundle is large because several Server Components accidentally import a library only needed on the client. How does the Server/Client Component boundary control what ships to the browser?
Server Components render entirely on the server and send only their resulting HTML (plus the data needed to hydrate any client-side interactivity) to the browser — none of their own JavaScript, or any library they import that isn't also used by a Client Component, ships in the client bundle at all. The boundary is drawn by the 'use client' directive: a module without it is a Server Component by default, and the moment that module (or anything it imports) gets imported by a Client Component, that whole import chain has to ship to the browser, because the browser needs to execute it there. The accidental-bundle-bloat bug usually happens when a server-only utility (a database client, a large server-side parsing library) gets imported into a shared module that a Client Component also imports — even though the Client Component never calls that specific function, bundlers can't always tree-shake it out, so the whole module ships. The fix is keeping server-only code in modules that only Server Components import, never shared with anything crossing the client boundary.
What interviewers look for
  • correctly explains Server Components ship no JS by default, only rendered output
  • correctly explains the 'use client' boundary and import-chain propagation
  • diagnoses the bug pattern: a shared module pulling server-only code into a client-imported chain
Likely follow-up: How would you verify which libraries are ending up in the client bundle?
An API route handler reads cookies() to check auth, but the page importing it fails to build statically. Why, and is that a real problem?
Reading cookies() (or headers(), or any other request-bound API) ties that code to a specific incoming request — there's no single cookie value to bake into a page rendered once at build time, since every visitor's cookies differ. Next.js correctly treats any route or page that calls a request-bound API as dynamic rather than static, rendering it fresh per request instead of once at build time — this isn't a bug, it's the framework correctly recognizing the code's real data dependency and opting that route out of static generation on its own. Whether it's 'a problem' depends entirely on intent: if that route needs per-request, per-user data (an authenticated dashboard, a personalized API response), dynamic rendering is exactly correct and the right outcome. It only becomes a real problem if a route that was supposed to be publicly cacheable and identical for every visitor accidentally imports something that touches a request-bound API — in that case, the fix is isolating the request-bound logic to only the code path that needs auth, keeping the rest of the route statically renderable.
What interviewers look for
  • correctly explains why cookies()/headers() force dynamic rendering
  • frames this as correct framework behavior, not a bug, when intentional
  • identifies the real failure mode: an unintended import pulling a static route into dynamic rendering
A Node.js API server's memory usage climbs steadily over days of uptime and is only resolved by a restart. How would you investigate whether this is a genuine memory leak?
The first step is distinguishing a real leak from normal behavior: Node's garbage collector doesn't run constantly, so memory usage that climbs and then periodically drops back down (a sawtooth pattern) is often just normal GC timing, not a leak — a genuine leak shows memory climbing without ever meaningfully coming back down, even after GC has had a clear opportunity to run. Taking heap snapshots at different points in time (via --inspect and Chrome DevTools, or a tool like clinic.js) and comparing object counts between them reveals what's accumulating — commonly an event listener registered on every request but never removed, a cache with no eviction policy that grows unbounded, or closures holding references to large objects longer than intended. Once the accumulating object type is identified, tracing where it's created and why it isn't being released (a missing removeListener call, a Map never pruned, a timer never cleared) usually points directly at the fix, which is almost always closing a cleanup step that was assumed to happen automatically but doesn't.
What interviewers look for
  • distinguishes real leaks from normal GC sawtooth behavior
  • names a concrete diagnostic tool/technique (heap snapshots, clinic.js, --inspect)
  • gives at least one realistic concrete leak source (listeners, unbounded cache, closures)
An API needs to support a breaking change to a response shape for a subset of consumers without breaking everyone else immediately. How would you version it, and what are the trade-offs between the common approaches?
URL-path versioning (/v2/users) is the most visible and cache-friendly approach — the version is explicit in every request, CDNs and proxies can cache different versions independently without any special configuration, and consumers can see at a glance which version they're calling, but it does mean maintaining distinctly separate route definitions (or at least separate response-shaping logic) per version going forward. Header-based versioning (an Accept header specifying a version, or a custom header) keeps URLs clean and stable, which fits REST's resource-identity philosophy better — a resource's address arguably shouldn't need to shift just because the shape of its response changed — but it's noticeably less discoverable (consumers have to know to set the header) and harder to test casually in a browser or a quick curl command. In practice, most teams pick URL-path versioning for its operational simplicity and discoverability despite the philosophical argument against it, and reserve breaking versions for rare, well-communicated major bumps — with a clear deprecation timeline and monitoring on old-version traffic so a version can eventually be retired once its usage drops to near zero.
What interviewers look for
  • correctly contrasts URL-path vs header-based versioning with real trade-offs
  • doesn't present one as objectively correct without the nuance
  • mentions deprecation timeline/traffic monitoring as part of the real lifecycle
A full-stack app's checkout flow needs to deduct inventory and create an order record together — if either step fails, neither should persist. How do you guarantee that, and what happens if the database call spans two separate services?
Within a single relational database, wrapping both operations in a transaction is the direct answer: the database guarantees atomicity, meaning either both the inventory deduction and the order creation commit together, or neither does — if anything fails partway through, the transaction rolls back and the database is left exactly as it was before the transaction started, with no partial state visible to any other query. This relies on the database's own transactional guarantees and works cleanly as long as both operations hit the same database connection within the same transaction boundary. The harder version of this problem shows up the moment inventory and orders live in two separate services with their own separate databases — a single ACID transaction can't span both, since each database only guarantees atomicity within itself. That case typically needs a different pattern entirely: a saga (a sequence of local transactions with compensating actions to undo earlier steps if a later one fails) or an outbox pattern (writing the intended follow-up action to the same local transaction as an auditable record, then processing it reliably afterward) — both accept that true cross-service atomicity isn't available and instead design for eventual consistency with a defined recovery path if a step fails partway through.
What interviewers look for
  • correctly explains database transactions and atomicity for the single-database case
  • correctly recognizes that a single ACID transaction can't span two separate service databases
  • names a real distributed pattern (saga or outbox) for the cross-service case, not just 'use a transaction'
A full-stack app's deploy pipeline runs the frontend build and backend deploy as two separate, independently-timed steps, and a recent incident happened because the frontend shipped before the backend's matching API change was live. How would you prevent this class of incident?
The underlying issue is a deploy ordering assumption that isn't enforced anywhere — the pipeline assumes the backend will be ready by the time the frontend goes live, but nothing in the pipeline itself guarantees that ordering, so a slow backend deploy or a failed-and-retried one can easily land after the frontend that depends on it. The most robust fix is designing the API change itself to be backward-compatible during the rollout window — the backend accepts and correctly handles both the old and new request/response shapes for a transition period, so deploy order doesn't matter for a brief overlap — which is the standard practice for any change that isn't a true atomic cutover. Where that's not practical, an explicit pipeline dependency (the frontend deploy step only starts after the backend deploy step reports healthy, verified via a real health check, not just 'the deploy command exited successfully') closes the ordering gap directly. Feature-flagging the frontend's use of the new API behind a flag that's only enabled after the backend is confirmed live adds a second layer of safety, letting the rollout be controlled independently of deploy timing entirely.
What interviewers look for
  • correctly identifies the unenforced ordering assumption as the root cause
  • proposes backward-compatible API rollout as the robust general fix
  • proposes at least one additional concrete safeguard (pipeline dependency with real health checks, feature flags)
Your team is considering letting an AI coding agent open pull requests directly against the main repository for small fixes, with human review before merge. What would you want in place before approving that workflow?
Human review before merge is necessary but not sufficient on its own — review quality degrades under volume and repetition, and an agent that opens many small, plausible-looking PRs can gradually erode how carefully each one gets read in practice, which defeats the purpose of having a human gate at all. What's needed first is scoping what the agent is allowed to touch: a defined set of file paths or change types it can propose (formatting fixes, dependency bumps, well-covered bug fixes) excluding anything touching auth, payments, data migrations, or other high-blast-radius code, enforced by CI checks or branch protection rather than trusted to the agent's own judgment. Strong, fast-running automated checks (tests, type checking, linting) catching obvious problems before a human ever needs to look matters more here than with human-authored PRs, since the volume can be higher and the failure mode (a plausible-but-wrong change slipping through tired review) is specific to this workflow. Logging and attribution — knowing definitively which commits came from the agent, under what prompt or task, and being able to revert a batch of agent-authored changes cleanly if something goes wrong — closes the loop that makes the whole arrangement auditable, not just reviewed.
What interviewers look for
  • doesn't treat 'human review' alone as sufficient — explains why review quality degrades under volume
  • proposes concrete scoping of what the agent can touch, enforced mechanically
  • mentions strong automated checks and auditability/attribution as real requirements
Asked something we don’t cover? Tell us