Interview Q&A / Node.js
Node.js interview questions
The event loop on the server, streams, modules and building APIs with Express.
Prefer rapid revision? Practise Node.js short interview answers →
- What is the difference between route parameters and query strings in Express?
Route parameters are part of the path, like /users/42, and identify a specific resource, read from req.params. Query strings follow a question mark, like ?page=2, and filter or tweak a request, read from req.query.
BeginnerQuick answer1 min read - Which HTTP status codes should a REST API return for create, validation errors, missing login and forbidden access?
201 Created for a successful create, 400 for bad input (or 422 for failed validation), 401 when the user is not authenticated, 403 when authenticated but not allowed, 404 for a missing resource, and 500 for server faults.
BeginnerQuick answer1 min read - Why does req.body come out undefined in Express, and what does express.json do?
Express does not read request bodies by itself. express.json() is middleware that parses JSON bodies with a JSON content type and places the result on req.body. Without it, req.body is undefined.
BeginnerQuick answer1 min read - Why does the order of middleware and routes matter in Express?
Express runs middleware and routes in the order they are registered, and a response ends the chain. A parser placed after a route never runs for it, and a catch-all placed early swallows later routes.
BeginnerQuick answer1 min read - Why should you hash passwords with bcrypt instead of SHA-256 or storing them in plain text?
Plain text leaks everything in a breach. SHA-256 is designed to be fast, so attackers can test billions of guesses per second. bcrypt is deliberately slow, adds a unique salt, and its cost can be raised over time.
BeginnerQuick answer1 min read - Why use path.join instead of joining file paths with plus signs?
path.join uses the correct separator for the operating system, normalises extra slashes and dot segments, and avoids missing or doubled slashes, so paths work on Windows, Linux and macOS.
BeginnerQuick answer1 min read - Write an Express middleware that checks a JWT and protects a route.
Read the Bearer token from the Authorization header, verify it with jwt.verify, attach the claims to req.user and call next. On a missing or invalid token, respond 401 without calling next.
BeginnerQuick answerCoding1 min read - How can CommonJS code load an ES module?
Use dynamic import(), which works in CommonJS and returns a promise. Plain require of an ES module was not allowed historically; newer Node versions added limited support, so dynamic import is the safe choice.
IntermediateQuick answer1 min read - How do you read a very large file line by line in Node.js?
Create a read stream and pass it to readline.createInterface, then loop with for await. Only a small chunk sits in memory at a time, unlike readFile, which loads the whole file.
IntermediateQuick answer1 min read - How do you send a large file to the browser without loading it all in memory?
Create a read stream of the file and pipe it into the HTTP response. Set the Content-Type and, if known, Content-Length headers first, and handle stream errors before any bytes are sent.
IntermediateQuick answer1 min read - How do you version a REST API, and why would you?
Versioning lets you change the API without breaking existing clients. The common way is a URL prefix such as /api/v1. Other options are a custom header or media type. Avoid breaking changes inside a version.
IntermediateQuick answer1 min read - How do you write a JSON file in Node.js without risking a half-written file?
Write the data to a temporary file in the same folder, then rename it over the target. Rename is atomic on the same filesystem, so readers see either the old file or the complete new one.
IntermediateQuick answer1 min read - How does bcrypt store the salt and what does the cost factor mean?
The 60-character bcrypt hash contains the algorithm version, the cost, the 22-character salt and the hash itself, so you store one string. The cost is a power of two: each +1 doubles the work.
IntermediateQuick answer1 min read - How does Express know a middleware is an error handler?
By its arity: an error-handling middleware takes four arguments (err, req, res, next). It must be registered after the routes, and errors reach it through next(err) or a thrown error in synchronous code.
IntermediateQuick answer1 min read - How should a REST API return error responses consistently?
Use one JSON shape for every error with the right HTTP status, a stable machine-readable code, a human message, and optional field details. Never leak stack traces or database errors to clients.
IntermediateQuick answer1 min read - How would you design pagination for an API endpoint that returns thousands of records?
Return a slice per request using limit and page (offset) or, for large changing data, a cursor of the last item seen. Cap the maximum limit and return total or next-page information in the response.
IntermediateQuick answer1 min read - Predict the output: setTimeout, a promise, process.nextTick and plain logs together
Synchronous code runs first, then process.nextTick callbacks, then promise callbacks (microtasks), then timers. So the order is sync, nextTick, promise, setTimeout.
IntermediateQuick answer1 min read - Should you use await inside a for loop or Promise.all for independent tasks?
For independent tasks use Promise.all with map so they run concurrently. await inside a loop runs them one by one, which is right only when each step depends on the last or order and rate limits matter.
IntermediateQuick answer1 min read - What are peerDependencies in package.json?
peerDependencies declare packages your library needs but expects the host application to install, so only one shared copy exists. Plugins and UI libraries use them, for example a React component library requiring react.
IntermediateQuick answer1 min read - What are the main phases of the Node.js event loop?
Timers, pending callbacks, idle/prepare, poll, check, and close callbacks. Timers run setTimeout callbacks, poll collects I/O, check runs setImmediate, and microtasks are drained between steps.
IntermediateQuick answer1 min read - What does idempotent mean for HTTP methods, and which methods are idempotent?
An idempotent request has the same effect on the server whether it is sent once or many times. GET, PUT, DELETE, HEAD and OPTIONS are idempotent; POST is not, and PATCH may not be.
IntermediateQuick answer1 min read - What is a circular dependency in Node.js and what happens when it occurs?
A circular dependency is when module A requires B and B requires A. In CommonJS, the second module receives A's partially filled exports at that moment, so values defined later are undefined. Fix it by restructuring.
IntermediateQuick answer1 min read - What is a refresh token and why use it alongside a short-lived access token?
The access token is short-lived (minutes) and sent on every request. The refresh token is long-lived, stored safely and used only to get a new access token. A stolen access token then expires quickly, and refresh tokens can be revoked.
IntermediateQuick answer1 min read - What is backpressure in Node.js streams?
Backpressure is when a writable cannot consume data as fast as a readable produces it. The writable signals this, and the reader should pause, otherwise memory fills up with unwritten data.
IntermediateQuick answer1 min read - What is CORS and how do you enable it safely in an Express API?
CORS is a browser rule that blocks a page from reading responses from a different origin unless the server allows it with headers. In Express, use the cors package with an allow-list of origins, not a wildcard for private APIs.
IntermediateQuick answer1 min read - What is the difference between session-based authentication and JWT authentication?
Sessions store user state on the server and give the browser only a session id cookie. JWTs carry signed user claims in the token itself, so the server stores nothing, but revoking a token before it expires is harder.
IntermediateQuick answer1 min read - What is the difference between stream.pipe and stream.pipeline?
pipe connects streams but does not forward errors or clean up, so a failure can leave streams open. pipeline connects several streams, destroys all of them on error, and reports the result in one callback or promise.
IntermediateQuick answer1 min read - What is top-level await and where can you use it in Node.js?
It lets you use await directly at the top of a file without wrapping it in an async function. It works only in ES modules, and it delays anything that imports that module until the promise settles.
IntermediateQuick answer1 min read - Where should a browser app store a JWT: localStorage or an httpOnly cookie?
An httpOnly, Secure, SameSite cookie keeps the token out of reach of JavaScript, so an XSS bug cannot steal it, but you must then handle CSRF. localStorage is simple but readable by any script on the page.
IntermediateQuick answer1 min read - Write a Transform stream that converts incoming text to uppercase.
Extend stream.Transform (or pass a transform function), call this.push with the changed chunk, and call the callback when done. Then pipe a readable into it and into a writable.
IntermediateQuick answerCoding1 min read