This lesson gathers commonly asked Node.js interview questions with clear, detailed answers, drawing on the concepts covered across this entire course.
How to Prepare
Node.js interviews typically probe three areas: understanding of the runtime itself (event loop, async model), practical API-building knowledge (Express, REST, databases), and production concerns (security, performance, testing). Strong answers explain the underlying reasoning, not just the correct terminology.
// A typical interview-style question:
// "What's the output of this code, and why?"
console.log('1');
setTimeout(() => console.log('2'), 0);
Promise.resolve().then(() => console.log('3'));
console.log('4');
// Answer: 1, 4, 3, 2
// Synchronous code first, then microtasks (promises), then macrotasks (timers)
Being able to explain *why* the output is 1, 4, 3, 2 (not just state the answer) is what distinguishes a strong interview response.
Question Categories to Expect
Runtime fundamentals - event loop, async model, modules
API building - Express, REST, middleware, validation
Data & security - databases, auth, hashing, common vulnerabilities
Production concerns - testing, performance, deployment
Expect at least one question requiring you to predict console output order.
Expect at least one question about the differences between CommonJS and ES modules.
Expect practical questions about REST API design and error handling.
Expect at least one security-focused question, often about SQL injection or password storage.
Quick-Fire Q&A
Short, direct answers to frequently asked conceptual questions.
Question
Short Answer
Is Node.js single-threaded?
The main JS thread is; libuv's thread pool and OS-level I/O are not
CommonJS vs ES modules?
require/module.exports (sync) vs import/export (static, supports top-level await)
What is middleware?
A function (req, res, next) that runs in the request pipeline
Sync vs async fs methods?
Sync blocks the event loop; async does not
Why hash passwords with bcrypt?
It's slow and automatically salted, resisting brute-force attacks
What does Promise.all() do?
Runs promises concurrently, resolves when all resolve, rejects on first rejection
Conceptual Questions
These questions test whether you understand the mental model behind Node.js, not just its syntax.
"What is the event loop, and what are its phases?" See the Event Loop lesson for a full phase-by-phase breakdown.
"What's the difference between process.nextTick() and setImmediate()?" nextTick runs before microtasks on the current operation; setImmediate runs in the check phase, generally after I/O callbacks.
"What happens if an EventEmitter emits 'error' with no listener?" The process crashes, this is intentional, not a bug.
Practical, Code-Level Questions
These questions often ask you to spot a bug or explain what a specific snippet does.
app.get('/users/:id', async (req, res) => {
const user = await db.users.findById(req.params.id);
res.json(user);
});
// Bug: no try/catch, and no check for a missing user (404 case)
A strong answer identifies both issues: an unhandled rejection risk and a missing not-found check, then shows the corrected version.
Common Mistakes
Memorizing answers without understanding the underlying reasoning well enough to explain follow-up questions.
Giving vague, high-level answers to questions that expect a specific technical detail.
Not practicing explaining concepts like the event loop out loud, in your own words, before an interview.
Skipping practical coding questions in preparation and focusing only on definitions.
Key Takeaways
Node.js interviews test runtime fundamentals, API-building skills, and production awareness.
Explaining *why* an answer is correct matters more than reciting the correct term alone.
Practice predicting async execution order, it's one of the most frequently asked question types.
Review the extended Q&A below for deeper, more detailed explanations.
Pro Tip
Practice explaining the event loop and the difference between CommonJS and ES modules out loud, from memory, without notes. These two topics come up in a huge share of Node.js interviews, and fluency here signals strong fundamentals immediately.
Extended Node.js Interview Q&A
The following questions go deeper than the quick-fire table above, with fuller
explanations for each answer.
1. Is Node.js single-threaded or multi-threaded?
Node.js runs your JavaScript on a single main thread, but the full runtime is not
purely single-threaded. libuv maintains a small internal thread pool
(default size 4) for operations like file system access, and the operating system
itself handles network I/O asynchronously outside of any JavaScript thread. CPU-bound
work can also be offloaded to Worker Threads, which run on genuinely separate threads.
2. What is the difference between process.nextTick() and setImmediate()?
process.nextTick() callbacks run after the current operation completes,
before the event loop continues to the next phase, and before any promise
microtasks. setImmediate() callbacks run in the event loop's "check"
phase, generally right after the current poll phase (I/O callbacks) completes.
nextTick has strictly higher priority.
3. What's the difference between CommonJS and ES modules?
CommonJS uses require()/module.exports, loads modules
synchronously, and provides __dirname/__filename
automatically. ES modules use import/export, are
statically analyzable, support top-level await, and use
import.meta.url instead of __dirname. A project's
package.json"type" field (or file extension) determines
which system a file uses.
4. Why does Express treat a four-parameter middleware function differently?
Express identifies error-handling middleware purely by function arity. A function
with exactly four parameters, (err, req, res, next), is treated as an
error handler and only runs when next(err) is called somewhere earlier
in the pipeline. A three-parameter function is always treated as regular middleware,
even if it's intended to handle errors.
5. How do you prevent SQL injection in a Node.js application?
Always use parameterized queries, ? placeholders in MySQL or
$1, $2 placeholders in PostgreSQL, passing values in a
separate array rather than concatenating them into the query string. The driver
handles escaping safely; manual string interpolation of user input into SQL is the
root cause of SQL injection vulnerabilities.
6. Why shouldn't you hash passwords with SHA-256 alone?
SHA-256 is fast by design, which is exactly the problem for password storage: an
attacker with a leaked password database could attempt billions of guesses per
second against a fast hash. bcrypt and argon2 are
deliberately slow and automatically salt each password, making large-scale
brute-force attacks impractical.
7. What's the difference between authentication and authorization?
Authentication verifies who a user is (login credentials, tokens). Authorization
determines what an already-authenticated user is allowed to do (which resources,
which actions). A request can be authenticated but still fail authorization checks,
for example, a logged-in user trying to access another user's private data.
8. What happens if you don't handle a rejected promise?
It becomes an "unhandled promise rejection." In modern Node.js, this by default
crashes the process (configurable via the --unhandled-rejections flag),
since an uncaught rejection almost always indicates a real bug that shouldn't be
silently ignored.
9. What is backpressure in Node.js streams?
Backpressure happens when a writable stream can't consume data as fast as it's being
written. .write() returns false when the internal buffer
exceeds a threshold, signaling the writer should pause until a 'drain'
event fires. Respecting backpressure prevents unbounded memory growth when piping a
fast source into a slower destination.
10. When would you use Worker Threads instead of async/await?
Async/await solves I/O-bound waiting efficiently on the single main thread. Worker
Threads solve a different problem: genuinely CPU-bound computation (heavy
calculations, image processing) that would otherwise block the main thread
regardless of how it's written. If profiling shows the bottleneck is actual CPU work,
not waiting on I/O, Worker Threads are the right tool.
11. How does the cluster module improve performance?
A single Node.js process uses only one CPU core for its JavaScript execution. The
cluster module forks multiple worker processes, each with its own event
loop, sharing the same listening port, so incoming connections can be distributed
across every available CPU core on the machine.
12. What's the risk of using exec() with user input?
exec() runs its command string through a shell. If any part of that
string comes from unsanitized user input, an attacker can inject additional shell
commands (command injection). spawn()/execFile() with
arguments passed as a separate array avoid this risk entirely, since arguments are
never interpreted by a shell.
13. Why is req.body undefined in an Express POST route?
A request body arrives as a raw stream; Express doesn't parse it automatically. You
must register body-parsing middleware, most commonly express.json() or
express.urlencoded(), before any route that reads
req.body.
14. What is the purpose of connection pooling?
Opening a new database connection per request is slow, each one requires a network
round trip and authentication. A connection pool keeps a set of reusable, already-open
connections ready to hand out per query, dramatically reducing per-request overhead
under load.
15. How would you implement graceful shutdown in a Node.js server?
Listen for the SIGTERM signal, stop accepting new connections with
server.close(), let in-flight requests finish, close database
connections, and then call process.exit(). This prevents dropped
requests during deploys and restarts.
You've reviewed common interview questions and short answers. Continue below for extended explanations, or test yourself with the Node.js Quiz next.