Node.js and Express Interview Questions: 23 With Answers (Route Order)
23 fresher-level Node.js and Express questions with answers you can say aloud, plus a worked example of Express route order with code.
Last updated: 13 October 2026 · By the Asuraa Team
Quick answer: Node.js and Express fresher interviews focus on the event loop, async/await, middleware and route order. Express runs middleware and routes in the order you define them, so put body parsing and auth first, static paths like /users/me before /users/:id, a 404 handler after all routes and the four-argument error handler last, as the expressjs.com guides and FAQ describe for Express 5.
Key takeaways
- Express runs middleware and routes in the order they are registered, and the first handler that sends a response ends the request-response cycle.
- A fixed path such as /users/me must be registered before /users/:id, because the parameter matches any single segment including the word me.
- The Express FAQ states that a 404 is not an error, so it needs its own catch-all middleware placed after every route.
- Error-handling middleware in Express takes four arguments (err, req, res, next) and goes last, and Express 5 forwards rejected promises from async handlers to it automatically.
- The Node.js event loop has six phases, and setImmediate always runs before setTimeout(fn, 0) when both are scheduled inside an I/O callback.
Node.js and Express interviews for freshers in India test three things: whether you understand the event loop, whether you can explain middleware and route order in Express, and whether you can build a small, safe REST API. Below are 23 questions with model answers you can say aloud, plus a worked section on Express route order. For the wider list of subjects, see the interview questions by subject guide.
Which Node.js and Express topics carry the most weight in fresher interviews?
The event loop, async patterns and Express middleware make up most of a fresher round; the rest is REST design and basic security. Use this table to split your revision time.
| Area | Typical questions | What interviewers check |
|---|---|---|
| Node.js runtime | Event loop, blocking vs non-blocking, nextTick vs setImmediate | You know why one thread can serve many requests |
| Async JavaScript | Callbacks, promises, async/await, error handling | You can write and debug async code without nesting |
| Modules and npm | CommonJS vs ES modules, package.json, lock files | You can set up and maintain a project |
| Express core | Middleware, route order, Router, req.params/query/body | You can predict which handler runs for a URL |
| Errors and APIs | 404 handler, error middleware, status codes | Your API fails cleanly and predictably |
| Security | Helmet, input validation, cookies, auth | You know the basics before you ship anything |
If JavaScript fundamentals such as closures and this feel shaky, revise them first with the JavaScript interview questions for freshers.
What Node.js runtime questions are asked most often?
Expect at least three questions on how Node runs your code.
1. What is Node.js, and how can a single thread handle many requests?
Node.js is a JavaScript runtime built on the V8 engine that runs JavaScript outside the browser. Your JavaScript runs on one main thread, but slow operations such as file and network I/O are handed off to the system, and their callbacks run later through the event loop. Because the thread is not blocked waiting for I/O, it can accept other requests in the meantime. This suits I/O-heavy APIs and chat servers.
2. What is the event loop and what are its phases?
The event loop is the mechanism that picks up completed work and runs its callbacks. The Node.js event loop guide lists six phases in order: timers (setTimeout and setInterval callbacks), pending callbacks, idle/prepare (internal), poll (new I/O events), check (setImmediate callbacks) and close callbacks.
3. What is the difference between process.nextTick, setImmediate and setTimeout(fn, 0)?
process.nextTick is not part of the event loop phases; its queue runs as soon as the current operation finishes, before the loop moves on. setImmediate runs in the check phase, right after poll, and setTimeout(fn, 0) runs in the timers phase once its minimum delay has passed. The Node.js guide notes that from the main module the order of setTimeout(0) and setImmediate is not guaranteed, but inside an I/O callback setImmediate always runs first. It also warns that recursive nextTick calls can starve I/O.
const fs = require('fs');
fs.readFile(__filename, () => {
setTimeout(() => console.log('timeout'), 0);
setImmediate(() => console.log('immediate'));
});
// prints: immediate, then timeout
4. What is blocking vs non-blocking code?
Blocking code makes the thread wait until an operation finishes, such as fs.readFileSync, so no other request is served meanwhile. Non-blocking code, such as fs.readFile or fs.promises.readFile, starts the operation and continues; the result arrives through a callback or promise. On request paths, always use the non-blocking version. CPU-heavy work also blocks the loop, so move it to worker_threads or a job queue.
What async JavaScript questions should you prepare?
Expect to convert callback code to async/await and explain how errors flow.
5. What is callback hell and how do promises and async/await fix it?
Callback hell is deeply nested callbacks where each async step depends on the previous one, making code hard to read and error handling repetitive. Promises flatten this into a chain with one .catch(), and async/await lets you write the same logic top to bottom with try/catch.
async function getOrder(id) {
try {
const user = await db.findUser(id);
const orders = await db.findOrders(user.id);
return orders;
} catch (err) {
throw new Error('Could not load orders: ' + err.message);
}
}
6. What is the difference between Promise.all and Promise.allSettled?
Promise.all runs promises in parallel and rejects as soon as any one rejects, so use it when every result is required. Promise.allSettled waits for all of them and returns each result with a status of fulfilled or rejected, so use it when partial success is acceptable, such as sending notifications to many users.
7. What is an EventEmitter?
EventEmitter is a core class in the events module that lets an object emit named events and lets listeners subscribe with on. Streams, HTTP servers and sockets are built on it. An error event with no listener crashes the process.
8. What are streams and why use them?
Streams process data in chunks instead of loading it all into memory. Piping a large file to an HTTP response with a stream keeps memory flat, whereas reading a 2 GB log file fully with readFile can exhaust memory.
What module and npm questions come up?
These are quick questions about project setup.
9. What is the difference between CommonJS and ES modules?
CommonJS uses require() and module.exports and loads modules synchronously; it is the older Node default. ES modules use import and export, are the JavaScript standard, and are enabled in Node with the .mjs extension or "type": "module" in package.json.
10. What goes in package.json, and why commit package-lock.json?
package.json holds project metadata, scripts and dependency ranges, split into dependencies (needed at runtime) and devDependencies (needed only for development and tests, such as nodemon or jest). package-lock.json records the exact installed versions of every package in the tree, so every developer and the server install the same versions.
How does Express decide which route handles a request?
Express checks middleware and routes in the order you register them and runs the first one that matches the method and path; a handler that sends a response ends the cycle, and later matches never run. The Express docs show this directly: in the middleware guide, a second app.get('/user/:id') route is never called because the first one already ended the request-response cycle. Four rules follow from this.
- Routes match in definition order. The first matching handler that responds wins.
- Static paths go before parameterised paths.
/users/:idmatches/users/mewithidset to"me", so/users/memust be registered first. - Middleware goes before the routes that need it. Body parsing, logging and auth only affect routes registered after them.
- The 404 handler goes after all routes, and the error handler goes last. The Express FAQ explains that a 404 is not an error: it simply means no middleware or route responded, so you add a catch-all middleware at the very bottom of the stack.
Here is the wrong order and the fix.
// WRONG: /users/me never reaches its own handler
app.get('/users/:id', (req, res) => res.send(`User ${req.params.id}`));
app.get('/users/me', (req, res) => res.send('Current user')); // unreachable
const express = require('express');
const app = express();
app.use(express.json()); // 1. parse JSON bodies for all routes below
app.use(requestLogger); // 2. log every request
app.use(express.static('public')); // 3. serve files from /public
app.get('/users/me', requireAuth, (req, res) => res.json(req.user)); // static path first
app.get('/users/:id', (req, res) => res.json({ id: req.params.id })); // parameterised after
app.use((req, res) => { // 4. nothing matched: 404
res.status(404).json({ error: 'Not found' });
});
app.use((err, req, res, next) => { // 5. error handler, four arguments, last
console.error(err.stack);
res.status(500).json({ error: 'Something went wrong' });
});
app.listen(3000);
Trace two requests. GET /users/me passes the three middleware, then hits the /users/me route, which responds; /users/:id never runs. GET /orders matches no route and falls through to the 404 handler. If a route throws, Express skips normal middleware and jumps to the four-argument error handler. The routing guide shows next('route') relying on the same fixed order.
What Express questions should you expect beyond route order?
Interviewers next test middleware, error handling and request data.
11. What is middleware in Express?
Middleware is a function with access to req, res and next that runs during the request-response cycle. It can run code, change the request or response, end the cycle, or call next() to pass control on. If it neither responds nor calls next(), the request hangs.
12. What types of middleware does Express have?
The Express guide lists five: application-level (app.use, app.get), router-level (router.use), error-handling (four arguments), built-in (express.json, express.urlencoded, express.static, express.raw, express.text) and third-party packages from npm such as cookie-parser or helmet.
13. Why should /users/me be defined above /users/:id?
Because routes match in definition order and :id matches any single path segment, including the literal word me. If the parameterised route comes first, it captures /users/me and treats me as an ID, usually causing a failed database lookup. Always register fixed paths before parameterised paths that share the same prefix.
14. Where does the 404 handler go, and why does the error handler not catch 404s?
The 404 handler goes after every route and router, as a plain three-argument middleware. The error handler does not catch it because no error occurred; Express simply ran out of matching handlers. The Express FAQ also recommends adding any routes created at runtime to an express.Router() instance so the 404 middleware does not shadow them.
15. How do you write error-handling middleware, and how are async errors handled?
Error middleware takes four arguments, (err, req, res, next), and must keep all four even if next is unused, or Express treats it as normal middleware. The Express error handling guide says that in Express 5, a handler that returns a rejected promise or throws inside an async function automatically calls next(err). In Express 4 you had to call next(err) yourself.
16. What is the difference between next(), next('route') and next('router')?
next() passes control to the next middleware or callback. next('route') skips the remaining callbacks of the current route and moves to the next matching route; it works only in app.METHOD or router.METHOD handlers. next('router') exits the current router entirely and returns control to the app, which is useful for guards such as skipping an admin router when an auth header is missing.
17. What is the difference between req.params, req.query and req.body?
req.params holds named path segments, so /users/34 with route /users/:id gives { id: '34' }. req.query holds the query string, so /search?q=node gives { q: 'node' }. req.body holds the request body and is empty unless body-parsing middleware such as express.json() runs before the route. Validate all three.
18. What are express.Router and app.route?
express.Router() creates a mini-app with its own middleware and routes that you mount with app.use('/api/users', usersRouter), keeping large apps modular. app.route('/book') chains .get(), .post() and .put() on one path so you write the path once. Pass { mergeParams: true } when a router needs the parent's path parameters.
19. Did route path syntax change in Express 5?
Yes. Express 5 uses a newer path-to-regexp, so wildcards must be named, such as /files/*filepath, optional parts use braces, such as /:file{.:ext}, and regex inside string paths like :id(\d+) is no longer allowed, according to the routing guide.
What REST API and security questions are asked?
Expect one design question and one security question in most backend fresher rounds.
20. Which HTTP status codes should a CRUD API return?
Return 200 for a successful read or update, 201 for a successful create, and 204 when a delete succeeds with no body. Return 400 for invalid input, 401 when the user is not authenticated, 403 when authenticated but not allowed, 404 when the resource does not exist, and 500 for unexpected server errors.
21. How do you secure an Express app?
The Express security best practices page recommends using a maintained Express version, TLS, the Helmet package for security headers, disabling x-powered-by, custom 404 and error handlers, secure cookie options (secure, httpOnly), brute-force protection on login routes and npm audit for dependencies. Add input validation and parameterised database queries to prevent injection.
22. Sessions or JWT: how do you authenticate users?
With sessions, the server stores session data and the browser holds only a session ID cookie; logout and revocation are easy, but you need a shared session store when you scale. With JWT, the server signs a token containing claims and the client sends it on each request; it is stateless and suits APIs and mobile apps, but revoking a token before expiry needs extra work.
23. How would you structure a small Express project?
Split it into routes (URL to controller), controllers (request handling), services (business logic) and models or a data layer, with config in environment variables. Register global middleware first, mount routers, then add the 404 and error handlers at the end.
What do most guides on Node.js and Express interview questions get wrong?
Most guides still teach Express 4 behaviour as if it were current. Three corrections matter in 2026. First, Express 5 forwards errors from async handlers automatically, so writing a try/catch in every route just to call next(err) is no longer required. Second, Express 5 path syntax rejects bare * wildcards and inline regex in string paths, so copied Express 4 routes can fail at startup. Third, many guides say a 404 is "caught by the error handler"; the Express FAQ is explicit that a 404 is not an error and needs its own middleware placed after all routes.
How should you revise Node.js and Express in 7 days?
Seven focused days are enough for a fresher round if you code every day instead of only reading.
- Day 1: Event loop phases, nextTick vs setImmediate, blocking vs non-blocking. Run the readFile example above.
- Day 2: Callbacks, promises, async/await, Promise.all vs allSettled. Rewrite one callback chain.
- Day 3: Modules, npm, package-lock, streams and EventEmitter. Stream a large file to a response.
- Day 4: Build an Express CRUD API with Router,
express.json()and correct status codes. - Day 5: Route order drill: add
/users/me,/users/:id, a 404 and an error handler, and break the order on purpose to see what changes. - Day 6: Security: Helmet, CORS, validation, JWT or sessions,
npm audit. - Day 7: Mock interview: answer all 23 questions aloud in under 2 minutes each and explain your project's folder structure.
If you are still building the basics, follow how to learn Node.js for jobs first, and use how to prepare for technical interview questions for the round structure. A deployed project from the web development projects for a fresher resume list gives interviewers something concrete to ask about.
Related guides
- Interview Questions by Subject: Java, Python, SQL, DSA, Cloud, AI
- AWS Interview Questions for Freshers: 22 Questions With Answers
- Selenium and Manual Testing Interview Questions: 23 With Answers
- Statistics Interview Questions for Data Analysts: 23 With Answers
FAQ
What is the correct order of middleware and routes in Express?
Register global middleware such as express.json(), logging and static files first, then authentication, then your routes and routers with fixed paths before parameterised ones, then a 404 middleware, and finally the four-argument error handler. Express checks them in that order and stops at the first handler that sends a response, so anything registered after it never runs for that request.
Why is my Express route /users/me returning the wrong result?
Almost always because /users/:id is registered above it. The :id parameter matches any single path segment, so Express treats 'me' as an ID and the /users/me handler is never reached. Move the fixed path above the parameterised one, restart the server and test both URLs again to confirm the fix.
Why does my Express error handler not catch 404 errors?
Because a 404 is not an error in Express. It only means no middleware or route sent a response. The Express FAQ recommends a separate three-argument middleware at the bottom of the stack that sets status 404. Keep the four-argument error handler after it for real errors such as exceptions and rejected promises.
Do I still need try/catch in async Express routes?
In Express 5, no, not just to forward errors. The official error handling guide says handlers that return a rejected promise or throw inside an async function call next(err) automatically. In Express 4 you had to wrap async handlers or call next(err) yourself. You may still use try/catch when you want to send a specific response.
Is Node.js single-threaded?
Your JavaScript runs on one main thread, but Node hands slow I/O to the operating system and a background thread pool, then runs the callbacks through the event loop. That lets one process serve many concurrent requests. CPU-heavy work still blocks the main thread, so it belongs in worker_threads, a separate service or a job queue.
How many Node.js questions are asked in a fresher backend interview?
It varies by company, but a typical fresher technical round covers five to ten Node or Express questions alongside JavaScript, a database and your project. Expect the event loop, async/await, middleware, route order and one security or REST design question, followed by a short live coding task such as building or fixing an endpoint.
Final thoughts
Most Node.js and Express rounds reward candidates who can predict what the server will do, not those who memorise definitions. Practise the route order example until you can trace any URL in your head, then apply to backend roles on Asuraa jobs with a project that shows it.
Related articles
Remote Software Engineering Internships in India: Where to Look
Where remote SDE internships in India really come from, what they pay, which open-source programmes count, and a 4-week plan to get shortlisted.
Remote Data Science Internships for Freshers: How to Find Real Ones
Real remote data science internships come from startups, consultancies and open-source programmes. Here is where to find them, what they pay and how to prepare in 4 weeks.
Interview Questions by Subject: Java, Python, SQL, DSA, Cloud, AI
Every interview question set in one place, organised by subject and role: core CS, programming languages, web and testing, data and analytics, AI and ML, cloud, DevOps and HR rounds.
Projects and Portfolio Guide for Freshers: Data, Software and AI
Choose the right projects for data analyst, data scientist, ML, web and software roles, build them on real public data or APIs, and present them so recruiters notice.