Full Stack with Node.js Interview Questions for 1 Year Experience
40 questions with answers for candidates with 1 year of experience — 19 easy, 19 medium, 2 hard.
What interviewers expect: 1 year experience
With one year of experience, interviews check that you have written production code. Expect questions on middleware, error handling, validation, JWT authentication, pagination, indexes and debugging real bugs. You may get a machine coding task to build a small API in an hour with clean structure and tests. Show that you understand why you wrote code a certain way, not only what it does.
This set is weighted towards Node.js Core and Event Loop (7), Asynchronous JavaScript (7), Deployment, Scaling and Performance (7), Authentication and Security (6).
Error handling and validation JWT authentication Database indexes Writing tests
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 purpose of the util.promisify function?
util.promisify converts a function that follows the Node callback convention, where the last argument is (err, result) => {}, into one that returns a promise. This lets you use async and await with older APIs. For example, const sleep = util.promisify(setTimeout) or promisify(fs.readFile). Many core modules now offer promise versions directly, such as fs/promises and dns/promises.
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
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.
04
Convert this callback-based function to async/await: fs.readFile(path, 'utf8', (err, data) => {...}).
Synchronous file calls block the event loop for the whole read, so under load every request queues behind disk I/O and latency spikes. In a route, use fs.promises.readFile with await, or stream the file with fs.createReadStream and pipe it to the response. Sync calls are acceptable only at startup, for example reading a config file once before the server listens.
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.
REST exposes multiple endpoints with fixed response shapes, uses HTTP caching easily and is simple to reason about. GraphQL exposes one endpoint where clients query exactly the fields they need, reducing over-fetching and multiple round trips, which helps mobile apps. GraphQL adds complexity: N+1 query risks needing DataLoader, harder caching, query cost limits and schema governance.
A callback is a function passed to another function to run when an asynchronous task finishes, following Node's error-first convention (err, data). Callback hell is deeply nested callbacks where each async step depends on the previous one, making code hard to read, handle errors in and maintain. Promises and async/await flatten the nesting and centralise error handling with catch or try/catch.
10
How do access tokens and refresh tokens work together?
The access token is short-lived, around 5 to 15 minutes, and sent with each API request. The refresh token is long-lived, stored securely in an HttpOnly cookie, and used only at a refresh endpoint to get a new access token. Rotate refresh tokens on every use and store their hashes server-side, so a stolen or reused token can be detected and the session revoked.
11
Compare session-based authentication with JWT-based authentication.
Sessions store state on the server, often in Redis, and the client holds only a session ID cookie; logout and revocation are easy. JWTs are stateless, so any service can verify them without a lookup, which suits microservices and mobile apps, but revoking a token before expiry needs a denylist or short lifetimes. Many systems combine short-lived JWT access tokens with server-stored refresh tokens.
12
Write a simple custom EventEmitter usage for an order service.
Situation: our search API p95 latency jumped from 200 ms to 2 seconds after a release. Task: as on-call engineer I had to find the cause fast. Action: I checked APM traces, saw a new synchronous JSON transform blocking the event loop, moved it to a cached precomputed field and added an event loop lag alert. Result: latency returned to normal within a day and we added a performance check to code review.
16
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.
17
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.
18
How do you handle async errors in Express 4 routes?
const asyncHandler = (fn) => (req, res, next) =>
Promise.resolve(fn(req, res, next)).catch(next);
router.get('/:id', asyncHandler(async (req, res) => {
const user = await User.findById(req.params.id);
if (!user) throw new AppError('Not found', 404);
res.json(user);
}));
// Without this, a rejected promise is never sent to the error handler.
// Express 5 does this automatically.
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.
20
What are async iterators and when would you use for await...of?
An async iterator returns promises from its next() method, and for await...of consumes them one by one. In Node, readable streams, readline interfaces and many database cursors are async iterable. It is ideal for processing paginated API results or large query cursors item by item with natural backpressure, since the next chunk is not pulled until the current one is handled.
21
Create a basic HTTP server in Node.js without any framework.
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.
23
Why do you want to work as a Node.js backend developer?
I enjoy building the systems behind products: APIs, data models and integrations. Node.js lets me use JavaScript across the stack and ship features quickly, and I like solving problems around performance and reliability. In my projects I built a REST API with authentication, MongoDB and Docker deployment, and I want to grow by working on real traffic and learning system design from experienced engineers.
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.
26
How do you handle a breaking API change request from a product manager close to a release?
I would first understand why it is needed and who consumes the API. Then I explain the impact on existing clients, propose a non-breaking path such as adding a new field or a v2 endpoint, and estimate effort and risk. Result in a past case: we shipped the additive change on time and scheduled removal of the old field for the next quarter.
27
Explain OAuth 2.0 and the Authorization Code flow with PKCE.
OAuth 2.0 lets an app access resources on a user's behalf without seeing their password, for example social login with an existing account. In Authorization Code with PKCE, the app creates a code verifier and sends its hash to the authorisation server. The user logs in and consents, the app receives a code and exchanges it plus the verifier for tokens. PKCE stops intercepted codes being reused.
28
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.
29
A dashboard endpoint makes five independent database queries one after another and takes 1.5 seconds. How would you speed it up?
Because the queries are independent, run them concurrently with Promise.all so total time is close to the slowest query instead of the sum. Check that the database connection pool is large enough to serve them in parallel. Then add indexes for slow queries, cache rarely changing parts in Redis, and use Promise.allSettled if the page can render with some widgets missing.
30
What is Redis and how is it used with Node.js backends?
Redis is an in-memory key-value store with data types like strings, hashes, lists, sets, sorted sets and streams. Node apps use it for caching database results, session storage, rate limiting counters, distributed locks, leaderboards, pub/sub between instances and job queues through BullMQ. Data lives in memory, so use TTLs and eviction policies and do not treat it as the only copy of important data.
31
How do you use the Node.js cluster module to use all CPU cores?
const cluster = require('cluster');
const os = require('os');
if (cluster.isPrimary) {
for (let i = 0; i < os.availableParallelism(); i++) cluster.fork();
cluster.on('exit', (worker) => {
console.log(`Worker ${worker.process.pid} died, restarting`);
cluster.fork();
});
} else {
require('./server'); // each worker listens on the same port
}
// In Kubernetes, prefer one process per container and more replicas.
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.
33
What is connection pooling and why is it important in Node.js?
Opening a database connection is slow, so a pool keeps a set of open connections that requests borrow and return. pg Pool, mysql2 and the MongoDB driver all pool by default. Size the pool based on database limits and instance count; too small causes waiting, too large overloads the database. In serverless functions, reuse the client across invocations or use a proxy like RDS Proxy.
34
How do you explain asynchronous programming to a non-technical stakeholder or junior teammate?
I use a restaurant analogy. One waiter takes an order, gives it to the kitchen and serves other tables instead of waiting at the stove; when the dish is ready, the kitchen rings a bell. Node.js works the same: it starts a database or network task, handles other requests and resumes when the result is ready. Then I show a short code example with async and await.
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.
36
A client reports that a large JSON POST request fails with 413 Payload Too Large. What do you do?
express.json() has a default body limit of 100 KB, so bigger payloads are rejected with 413. If the size is legitimate, raise it for that route only, for example express.json({ limit: '2mb' }), and check any proxy limit such as Nginx client_max_body_size. For very large data, switch to file upload to object storage or pagination instead of huge JSON bodies.
37
How do you mock a database or external service in Jest?
Browsers block cross-origin requests unless the server sends CORS headers. Use the cors package: app.use(cors({ origin: ['https://app.example.com'], credentials: true })). Avoid origin '*' with credentials, and restrict methods and headers you allow. CORS is a browser protection, not a security layer for your API, so you still need authentication and authorisation.
39
How do you implement rate limiting on a login endpoint?
Follow the twelve-factor approach: keep config in environment variables, not code. Load and validate them at startup with a schema, for example zod or envalid, and fail fast if any are missing. Use .env files only locally, and store production values in the platform's secret store or config maps. Keep the same Docker image across environments and change only configuration.
Frequently asked questions
What is asked in Full Stack with Node.js interviews for 1 year of experience?
With one year of experience, interviews check that you have written production code. Expect questions on middleware, error handling, validation, JWT authentication, pagination, indexes and debugging real bugs. You may get a machine coding task to build a small API in an hour with clean structure and tests. Show that you understand why you wrote code a certain way, not only what it does.
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 1 year of experience?
Focus first on Error handling and validation, JWT authentication, Database indexes, Writing tests.