Full Stack with Node.js Interview Questions for Freshers
40 questions with answers for candidates with Freshers — 30 easy, 10 medium.
What interviewers expect: freshers
Freshers are tested on JavaScript fundamentals, the event loop, promises and async/await, basic Express routing and middleware, REST concepts and simple MongoDB or SQL queries. Expect a coding round with array or string problems and a small API task. Interviewers also discuss your projects in detail, so be ready to explain how authentication, database schema and error handling work in them.
This set is weighted towards Asynchronous JavaScript (6), REST API Design (6), Databases: MongoDB, SQL and Redis (6), Node.js Core and Event Loop (6).
JavaScript and async basics Express CRUD APIs MongoDB and SQL basics Project explanation
Solved at this levelStart practicing
3 QUESTIONS FREESign up to unlock the full question bank and track your progress.Unlock every question and answer, then continue practising company-wise and package-wise.
✓ 3 questions free • Unlock the rest in seconds
01
What is the difference between var, let and const?
var is function-scoped, hoisted and initialised as undefined, and can be redeclared. let and const are block-scoped and are in a temporal dead zone until declared, so accessing them early throws an error. const prevents reassignment of the binding but not mutation of an object's contents. Modern Node code uses const by default and let when reassignment is needed.
02
What is the output order of this code: console.log('A'); setTimeout(() => console.log('B'), 0); Promise.resolve().then(() => console.log('C')); console.log('D');
The output is A, D, C, B. Synchronous code runs first, printing A and D. Then the microtask queue is drained before the event loop moves to timers, so the promise callback prints C. Finally the timers phase runs the setTimeout callback and prints B. Microtasks always run before the next macrotask such as timers or I/O callbacks.
03
Write a simple request logging middleware that records response time.
function requestLogger(req, res, next) {
const start = process.hrtime.bigint();
res.on('finish', () => {
const ms = Number(process.hrtime.bigint() - start) / 1e6;
console.log(`${req.method} ${req.originalUrl} ${res.statusCode} ${ms.toFixed(1)}ms`);
});
next();
}
app.use(requestLogger);
// In production use pino-http or morgan with structured logs.
04
Convert this callback-based function to async/await: fs.readFile(path, 'utf8', (err, data) => {...}).
Use plural nouns for resources and let methods express the action: GET /users, POST /users, GET /users/42, PATCH /users/42. Nest only for clear ownership, like GET /users/42/orders, and avoid deep nesting. Use lowercase kebab-case, query parameters for filtering, sorting and pagination, and version the API, for example /api/v1. Avoid verbs like /getUsers.
06
Users report seeing stale prices after an update because of caching. How do you solve it?
Invalidate or update the cache key in the same code path that updates the price, preferably after the database commit. Use reasonable TTLs as a safety net, and version keys if needed. If several services update prices, publish a price-changed event and have consumers delete the cache. For CDN-cached responses, purge the relevant URLs or use short max-age with stale-while-revalidate.
07
Why is using async callbacks inside forEach a common bug?
Array.forEach ignores the promise returned by an async callback, so it does not wait for any iteration and errors are not caught by the outer function. Code after the loop runs before the work is done. Use for...of with await for sequential processing, or map the items to promises and await Promise.all for parallel processing.
08
What is package-lock.json and why should it be committed?
package-lock.json records the exact resolved version and integrity hash of every installed package, including nested ones. Committing it makes installs reproducible across developer machines and CI, so a minor update in a transitive dependency cannot silently break production. In CI use npm ci, which installs strictly from the lock file and fails if it is out of sync with package.json.
09
Explain the main HTTP methods and which are idempotent.
GET reads a resource, POST creates or triggers an action, PUT replaces a resource fully, PATCH updates part of it and DELETE removes it. GET, PUT, DELETE, HEAD and OPTIONS are idempotent, meaning repeating the request has the same effect as doing it once. POST and usually PATCH are not, which is why payment APIs use idempotency keys for POST.
10
Which HTTP status codes should a REST API commonly return?
200 OK for successful reads and updates, 201 Created with a Location header for new resources, 204 No Content for deletes. 400 for invalid input, 401 when not authenticated, 403 when authenticated but not allowed, 404 not found, 409 conflict such as a duplicate email, 422 for validation errors in some APIs, 429 rate limited, 500 server error and 503 unavailable.
11
Tell me about a time you had to balance speed of delivery with technical quality.
Situation: sales needed a partner API in one week for a client launch. Task: deliver fast without creating a mess. Action: I agreed with my manager to ship the core endpoints with validation, auth and tests, and to defer caching and admin tooling, logging them as tickets with dates. Result: the partner went live on time, and we completed the deferred work in the next sprint as planned.
Streams process data in chunks instead of loading everything into memory. There are four types: Readable (fs.createReadStream, HTTP request), Writable (fs.createWriteStream, HTTP response), Duplex (TCP socket, both read and write) and Transform (zlib gzip, modifies data as it passes). Streams keep memory flat when serving large files, uploading media or processing big CSV logs.
13
What is package.json and what is the difference between dependencies and devDependencies?
package.json describes a project: name, version, scripts, entry point and dependencies. dependencies are packages needed at runtime, such as express or mongoose. devDependencies are only for development and build, such as jest, eslint or nodemon. Running npm ci --omit=dev in production installs only runtime packages, which keeps Docker images smaller and reduces attack surface.
14
How do you use a message queue to process background jobs in Node.js?
PUT replaces the entire resource with the representation sent, so missing fields may be reset; it is idempotent. PATCH applies a partial update, sending only changed fields, such as { "phone": "..." }. PATCH is more efficient for large objects. With JSON Merge Patch, repeated identical PATCH requests are effectively idempotent, but operations like increment are not.
16
Write a parameterised query with node-postgres to fetch a user's recent orders.
app.use mounts middleware for all HTTP methods and matches any path that starts with the given prefix, for example app.use('/api', router). app.get registers a handler only for GET requests on an exact route pattern. Use app.use for cross-cutting concerns like parsing and auth, and method-specific functions such as get, post, put and delete for endpoints.
EventEmitter from the events module implements the publish-subscribe pattern. Objects register listeners with on or once and trigger them with emit. Streams, HTTP servers and sockets all extend it. Always handle the 'error' event, because an emitted error without a listener crashes the process. Watch for memory leaks when listeners are added repeatedly; Node warns after 10 listeners by default.
19
How do you manage secrets such as database passwords and API keys in a Node.js app?
Never commit secrets to Git. Load them from environment variables, using a .env file only for local development and keeping it in .gitignore. In production, use a secrets manager such as AWS Secrets Manager, Azure Key Vault, HashiCorp Vault or Kubernetes secrets with encryption. Rotate keys regularly, scan repos with tools like gitleaks and validate required variables at startup.
PM2 is a process manager for Node.js on virtual machines. It keeps apps running and restarts them on crashes, runs cluster mode across CPU cores, supports zero-downtime reloads, log management and startup scripts. In Docker or Kubernetes you usually do not need PM2, because the orchestrator restarts containers and you scale with replicas, so you run node directly.
helmet is middleware that sets secure HTTP response headers. It adds Content-Security-Policy, Strict-Transport-Security, X-Content-Type-Options nosniff, frame protection and removes X-Powered-By, reducing risks like clickjacking, MIME sniffing and some XSS attacks. It is one line, app.use(helmet()), but CSP usually needs tuning so your frontend scripts and assets still load.
22
What is a REST API and what are its key constraints?
REST is an architectural style where resources are identified by URLs and manipulated through standard HTTP methods. Key constraints: client-server separation, statelessness so each request carries all needed information, cacheable responses, uniform interface, layered system and optionally code on demand. In practice it means resource-based URLs, correct methods and status codes, and JSON representations.
23
How do you implement rate limiting on a login endpoint?
Use the OpenAPI 3 specification, written by hand in YAML or generated from code or validation schemas, and serve it with Swagger UI or Redoc. Document each endpoint's parameters, request and response schemas, status codes, auth and examples. Keep it in the repo, validate it in CI and generate client SDKs or contract tests from it so docs never drift from the code.
25
What is the difference between SQL and NoSQL databases?
SQL databases such as PostgreSQL and MySQL store data in tables with fixed schemas, support joins and strong ACID transactions, and suit relational data like orders and payments. NoSQL databases such as MongoDB, Redis or Cassandra use documents, key-value or wide-column models with flexible schemas and easier horizontal scaling. The choice depends on data relationships, consistency needs and query patterns.
26
How do you run async tasks in parallel versus in sequence?
// Sequential: each waits for the previous one
for (const id of ids) {
const user = await getUser(id);
results.push(user);
}
// Parallel: start all, then wait together
const users = await Promise.all(ids.map((id) => getUser(id)));
// Use sequential only when steps depend on each other
// or when you must limit load on a downstream service.
Start Node with --inspect or --inspect-brk and attach Chrome DevTools at chrome://inspect or the VS Code debugger to set breakpoints, step through code and inspect variables. Use structured logs with request IDs to trace issues in deployed environments. For async issues, check stack traces with async context, and for performance use --cpu-prof or clinic.js flame graphs.
Mongoose is an ODM for MongoDB in Node.js. It adds schemas with types, validation, defaults, middleware hooks such as pre save, virtuals, population of references and a convenient query API. This brings structure to schemaless MongoDB collections and reduces bugs. For very high-performance or simple cases, some teams use the native MongoDB driver directly to avoid the overhead.
A JSON Web Token is a compact, signed token used to carry claims between parties. It has three Base64URL parts separated by dots: header (algorithm and type), payload (claims like sub, role, exp) and signature. The signature proves the token was issued by the server and not modified. The payload is only encoded, not encrypted, so never put secrets in it.
Never store plain text or use fast hashes like MD5 or SHA-256 alone. Use a slow, salted password hashing algorithm such as bcrypt with a cost factor around 10 to 12, or Argon2id, which is the current recommendation. The library generates a unique salt per password. On login, compare using the library's compare function, which is timing-safe.
31
What is the difference between unit, integration and end-to-end tests for a Node.js API?
Unit tests check a single function or service in isolation with dependencies mocked; they are fast and numerous. Integration tests check several parts together, such as a route, service and a real test database. End-to-end tests run the full system like a user would, often through HTTP against a deployed environment. A healthy test pyramid has many unit tests and fewer E2E tests.
32
What is the difference between authentication and authorisation?
Authentication verifies who the user is, for example by checking a password, OTP or OAuth login. Authorisation decides what that verified user is allowed to do, such as whether they can delete an order or view admin reports. In an API, authentication failures return 401 and authorisation failures return 403. Both must be enforced on the server, never only in the frontend.
33
What is database normalisation and when would you denormalise?
Normalisation organises tables to remove duplicate data and update anomalies, typically up to third normal form, for example keeping customers and orders in separate tables linked by foreign keys. You denormalise for read performance, such as storing a product name on an order line or a precomputed order count on a user, when joins become expensive. Denormalised data must be kept in sync.
34
Create a basic HTTP server in Node.js without any framework.
Middleware is a function with the signature (req, res, next) that runs during the request-response cycle. It can read or modify req and res, end the response, or call next() to pass control to the next middleware. Typical uses are parsing JSON, logging, authentication, CORS and rate limiting. Order matters, because middleware runs in the sequence it is registered.
36
What are health check endpoints and what is the difference between liveness and readiness?
Health endpoints let orchestrators check the app. Liveness answers whether the process is alive; if it fails, the container is restarted, so keep it simple. Readiness answers whether the instance can serve traffic, checking database and cache connections; if it fails, the load balancer stops sending requests but does not restart it. During shutdown, fail readiness first.
37
What is Node.js and why is it used for backend development?
Node.js is a JavaScript runtime built on the V8 engine that runs JavaScript outside the browser. It uses a single-threaded event loop with non-blocking I/O, so one process can handle thousands of concurrent connections cheaply. It is popular for APIs, real-time apps and microservices because teams can use one language across frontend and backend and reuse a huge npm ecosystem.
38
After adding a new middleware, all routes return 404 or hang. How do you debug it?
A hang usually means the middleware never calls next() or sends a response on some path. A 404 often means it was mounted with a wrong path or registered after routes. I check order of app.use calls, add logging at the start and end of the middleware, verify every branch calls next or responds, and check async code passes errors to next.
39
Define a Mongoose schema for a user with validation and an index.
Promise.all resolves with all results when every promise fulfils, and rejects as soon as one rejects. Promise.allSettled waits for all and returns each status and value or reason, useful when partial failure is fine. Promise.race settles with the first promise to settle, often used for timeouts. Promise.any resolves with the first fulfilled promise and rejects only if all reject.
Frequently asked questions
What is asked in Full Stack with Node.js interviews for Freshers?
Freshers are tested on JavaScript fundamentals, the event loop, promises and async/await, basic Express routing and middleware, REST concepts and simple MongoDB or SQL queries. Expect a coding round with array or string problems and a small API task. Interviewers also discuss your projects in detail, so be ready to explain how authentication, database schema and error handling work in them.
How many questions should I practise before a Full Stack with Node.js interview?
Work through all 40 questions here, then the company-wise sets for the employers you are targeting. Quality matters more than count: be able to explain why each answer is right.
Which topics matter most for Freshers?
Focus first on JavaScript and async basics, Express CRUD APIs, MongoDB and SQL basics, Project explanation.